Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
MCP saved results: scrub turn secrets, say when masked, save in rooms too
AdityaUmale42516e325ceb
diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex a4da6c5535..ba71742bfc 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -73,9 +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, resultFolder?: string, serverName = "audit") {+ async mount(computerUse = false, localComputer = false, toolScope?: ToolScope, resultFolder?: string, serverName = "audit", scrub?: (text: string) => string) {const session = await mountChatTools(localComputer ? { localComputer: server } : { custom: { [serverName]: server } }, controller.signal, computerUse, toolScope,- undefined, undefined, resultFolder);+ undefined, undefined, resultFolder, scrub);sessions.push(session);return session;},@@ -434,7 +434,7 @@ describe("Chat MCP session", () => {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(`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);});@@ -469,6 +469,19 @@ describe("Chat MCP session", () => {expect(text).not.toContain(key);});+ it("masks the turn's own secrets too, and says so in the notice", async () => {+ const secret = "plain-configured-api-key-value";+ const f = fixture(`if (message.method === "tools/call") { reply(message,{content:[{type:"text",text:${JSON.stringify(`${big}auth ${secret} end`)}}]}); continue; }`);+ const folder = workFolder();+ const scrub = (text: string) => text.split(secret).join("[redacted]");+ const result = await (await f.mount(false, false, undefined, folder, "audit", scrub)).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).not.toContain(secret);+ expect(text).toContain("auth [redacted] end");+ expect(result.text).toContain("(secret-looking values in it are masked)");+ });+it(`keeps only the newest ${SAVED_RESULTS_KEPT} saved results`, async () => {const f = bigFixture();const folder = workFolder();diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex 0cedc8bf21..a44345ed99 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -297,9 +297,9 @@ async function pruneSavedResults(dir: string): Promise<void> {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.+/** A result over the limit is kept whole (secrets masked by `scrub`) 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> {+async function savedOrBounded(value: string, tool: string, folder: string | undefined, scrub: (text: string) => string): Promise<string> {const bytes = Buffer.from(value);if (bytes.length <= OUTPUT_BYTES || !folder) return boundedText(value, bytes);try {@@ -309,10 +309,11 @@ async function savedOrBounded(value: string, tool: string, folder: string | undeif (!(await lstat(dir)).isDirectory()) throw new Error("not a folder");const file = join(dir, `${tool}-${Date.now()}-${randomBytes(3).toString("hex")}.txt`);// 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 });+ const kept = scrub(value);+ await writeFile(file, kept, { 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}]`;+ const kb = Math.ceil(bytes.length / 1024), masked = kept === value ? "" : " (secret-looking values in it are masked)";+ return `${preview(bytes)}\n[MCP result is ${kb}KB; only the first 50KB is shown above. The full result is saved in ${file}${masked}]`;} catch {return boundedText(value, bytes);}@@ -367,9 +368,9 @@ export function directServers(servers: ReadonlyArray<{ name: string; tools: numb}/** 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). */+ * A tool result over 50KB is saved whole in `resultFolder`, the bot's working folder, after `scrub` masks secrets (see savedOrBounded). */export async function mountChatTools(integrations: SendTurnInput["integrations"], signal: AbortSignal, computerUse = false, toolScope?: ToolScope, callTimeoutMs: number = DEFAULT_CALL_MS,- schemaProfile?: ToolSchemaProfile, resultFolder?: string): Promise<ChatToolSession> {+ schemaProfile?: ToolSchemaProfile, resultFolder?: string, scrub: (text: string) => string = redactSecretsInText): Promise<ChatToolSession> {const parsed = parseToolScope(toolScope);if (!parsed.ok) throw new Error(parsed.error);const scope = parsed.scope;@@ -603,7 +604,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: await savedOrBounded(parts.join("\n") || (images.length ? "Screenshot captured." : "(empty result)"), chatToolName(tool.server, tool.name), resultFolder), 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, scrub), 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 da77f4316f..42bc0cc976 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 }), turn.cwd ?? turn.toolResultFolder);+ toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText);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 1e05334877..de2419bde2 100644--- a/server/index.ts+++ b/server/index.ts@@ -10465,7 +10465,7 @@ async function runClaimedGroupMemberTurn(system: roomSystem.text,systemStable: roomSystem.stable,systemVolatile: roomSystem.volatile,- cwd,+ cwd, ...(worksInWorkspace || roomGuestConfined || cloudGuestOpened(threadId) ? {} : { toolResultFolder: messageFileRootsForThread(readyBot.id, threadId)[0] }),integrations,...(integrations.browser && browserIsThePlace(roomPlan) ? { preloadBrowserTools: true } : {}),...settingsTurnFields(cfg, DATA_DIR, managedPolicy.restrictsMcp()),