Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(pi): make the extension a complete MCP Apps client and never drop a result block
itsaxelhugoe5843ea27b63
diff --git a/server/drivers/pi-mcp-extension.test.ts b/server/drivers/pi-mcp-extension.test.tsindex 2e4c5ae2ed..7e8a261640 100644--- a/server/drivers/pi-mcp-extension.test.ts+++ b/server/drivers/pi-mcp-extension.test.ts@@ -16,6 +16,7 @@ import extension, {toTypebox,truncateToolText,} from "./pi-mcp-extension.ts";+import { mcpContentToPiContent } from "../mcp-tool-content.ts";const tempDirs: string[] = [];const clients: StdioMcp[] = [];@@ -63,6 +64,32 @@ afterEach(async () => {else process.env.OMB_MCP_CONFIG = originalMcpConfig;});+describe("MCP content conversion", () => {+ it("keeps every content kind and never drops a block silently", () => {+ expect(mcpContentToPiContent([+ { type: "text", text: "hi" },+ { type: "image", data: "aW1n", mimeType: "image/png" },+ { type: "audio", data: "YXVk", mimeType: "audio/mpeg" },+ { type: "resource_link", name: "note", uri: "voicenote://audio/1" },+ { type: "resource", resource: { uri: "x://text", mimeType: "text/plain", text: "body" } },+ { type: "resource", resource: { uri: "x://img", mimeType: "image/jpeg", blob: "aW1n" } },+ { type: "resource", resource: { uri: "x://bin", mimeType: "application/pdf", blob: "Ymlu" } },+ { type: "weird", foo: 1 },+ "nonsense",+ ])).toEqual([+ { type: "text", text: "hi" },+ { type: "image", data: "aW1n", mimeType: "image/png" },+ { type: "text", text: "[audio audio/mpeg omitted]" },+ { type: "text", text: "note: voicenote://audio/1" },+ { type: "text", text: "body" },+ { type: "image", data: "aW1n", mimeType: "image/jpeg" },+ { type: "text", text: "[binary resource x://bin (application/pdf) omitted]" },+ { type: "text", text: "[unsupported MCP content weird]" },+ { type: "text", text: "[unsupported MCP content]" },+ ]);+ });+});+describe("Pi MCP JSON Schema conversion", () => {it("keeps the cua browser_prepare regression schema object-shaped at the root", () => {const schema = toTypebox({@@ -167,6 +194,37 @@ describe("Pi MCP tool names and output bounds", () => {});describe("StdioMcp", () => {+ it("advertises the MCP Apps extension and retries without it when a server refuses", async () => {+ const dump = join(tempDir(), "init.jsonl");+ const script = fakeMcpScript(`+ import { appendFileSync } from "node:fs";+ let buffer = "";+ process.stdin.setEncoding("utf8");+ const send = (value) => process.stdout.write(JSON.stringify(value) + "\\n");+ process.stdin.on("data", (chunk) => {+ buffer += chunk;+ let newline;+ while ((newline = buffer.indexOf("\\n")) !== -1) {+ const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);+ if (!line.trim()) continue;+ const msg = JSON.parse(line);+ if (msg.id === undefined) continue;+ if (msg.method === "initialize") {+ const extensions = msg.params?.capabilities?.extensions;+ const hasUi = Boolean(extensions && Object.prototype.hasOwnProperty.call(extensions, "io.modelcontextprotocol/ui"));+ appendFileSync(process.env.DUMP, JSON.stringify(hasUi) + "\\n");+ if (hasUi) send({ jsonrpc: "2.0", id: msg.id, error: { code: -32602, message: "unknown capability" } });+ else send({ jsonrpc: "2.0", id: msg.id, result: { capabilities: { tools: {} } } });+ } else if (msg.method === "tools/list") send({ jsonrpc: "2.0", id: msg.id, result: { tools: [] } });+ }+ });+ `);+ const client = createClient(script, { DUMP: dump });+ await client.init(true);+ expect(readFileSync(dump, "utf8").trim().split("\n")).toEqual(["true", "false"]);+ await expect(client.listTools()).resolves.toEqual([]);+ });+it("initializes, paginates tools/list, preserves images and truncates text", async () => {const client = createClient(`let buffer = "";@@ -448,6 +506,44 @@ describe("Pi MCP extension registration", () => {expect(payload.tools).toEqual([]);});+ it("carries an app tool's _meta, structuredContent and every content kind, filtering app-only tools", async () => {+ const script = fakeMcpScript(`+ let buffer = "";+ process.stdin.setEncoding("utf8");+ const send = (value) => process.stdout.write(JSON.stringify(value) + "\\n");+ process.stdin.on("data", (chunk) => {+ buffer += chunk;+ let newline;+ while ((newline = buffer.indexOf("\\n")) !== -1) {+ const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);+ if (!line.trim()) continue;+ const msg = JSON.parse(line);+ if (msg.id === undefined) continue;+ if (msg.method === "initialize") send({ jsonrpc: "2.0", id: msg.id, result: { capabilities: { tools: {} }, serverInfo: { name: "voicenote", title: "MausBot Voice" } } });+ else if (msg.method === "tools/list") send({ jsonrpc: "2.0", id: msg.id, result: { tools: [+ { name: "show_voice_note", description: "play", inputSchema: { type: "object" }, _meta: { ui: { resourceUri: "ui://voicenote/player.html" } } },+ { name: "app_only", inputSchema: { type: "object" }, _meta: { ui: { resourceUri: "ui://voicenote/other", visibility: ["app"] } } }+ ] } });+ else if (msg.method === "tools/call") send({ jsonrpc: "2.0", id: msg.id, result: { content: [{ type: "audio", data: "TURU", mimeType: "audio/mpeg" }], structuredContent: { id: "abc" }, _meta: { voicenote: { id: "abc" } } } });+ }+ });+ `);+ scopeConfig(undefined, { mcpServers: { voicenote: { command: process.execPath, args: [script], scope: "custom" } }, approvalMode: "full" });+ const tools: RegisteredTool[] = [];+ const handlers = new Map<string, ShutdownHandler>();+ await extension({ registerTool(tool) { tools.push(tool); }, on(event, handler) { handlers.set(event, handler); } });+ try {+ expect(tools.map((tool) => tool.name)).toEqual(["voicenote_show_voice_note"]);+ expect(tools[0].outputSchema).toBeDefined();+ const result = await tools[0].execute("call", {}, undefined, undefined, { ui: { confirm: async () => true } });+ expect(result.structuredContent).toEqual({ id: "abc" });+ expect(result.details).toMatchObject({ server: "voicenote", tool: "show_voice_note", meta: { voicenote: { id: "abc" } } });+ expect(result.content[0]).toMatchObject({ type: "text", text: "[audio audio/mpeg omitted]" });+ } finally {+ await handlers.get("session_shutdown")?.();+ }+ });+it("filters raw MCP identities and still asks before custom execution", async () => {const receipt = join(tempDir(), "execution.txt");const script = fakeMcpScript(`diff --git a/server/drivers/pi-mcp-extension.ts b/server/drivers/pi-mcp-extension.tsindex f825de0b53..798dc1708e 100644--- a/server/drivers/pi-mcp-extension.ts+++ b/server/drivers/pi-mcp-extension.ts@@ -8,6 +8,8 @@ import { allowsTool, canUseMcpServer, parseToolScope, type ToolIdentity } from "import { ASK_USER_TOOL, formatQuestionAnswers, MAX_OPTIONS, MAX_QUESTIONS, parseAskQuestions } from "../../shared/ask-question.ts";import { CALL_TOOL, directoryCallTarget, isDirectoryTool } from "../mcp-directory.ts";import { REMOTE_MCP_STARTUP_MS } from "../mcp-http.ts";+import { modelVisible, withUiExtension } from "../mcp-app-observer.ts";+import { MCP_RESULT_OUTPUT_SCHEMA, mcpContentToPiContent, type PiToolContent } from "../mcp-tool-content.ts";import { AGENTS_TOOL_TIMEOUT_SECONDS } from "./agents-tool-limit.ts";interface McpServerDef {@@ -34,21 +36,27 @@ interface McpTool {name: string;description?: string;inputSchema?: unknown;+ outputSchema?: unknown;+ annotations?: unknown;+ /** `_meta.ui` decides whether a tool is model-visible and whether it has an app; kept so this+ * client filters app-only tools and preserves the app payload for the host, as the gate does. */+ _meta?: unknown;}-interface McpTextContent {- type: "text";- text: unknown;+interface McpCallResult {+ content?: unknown;+ structuredContent?: unknown;+ isError?: boolean;+ _meta?: unknown;}-interface McpImageContent {- type: "image";- data: unknown;- mimeType: unknown;+interface ConvertedMcpResult {+ content: PiToolContent[];+ isError: boolean;+ structuredContent?: unknown;+ _meta?: Record<string, unknown>;}-type PiToolContent = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string };-interface PiToolContext {ui: {confirm(title: string, message: string): Promise<boolean>;@@ -63,6 +71,8 @@ interface PiToolDefinition {label: string;description: string;parameters: TSchema;+ /** The MCP `CallToolResult` shape, so a codemode script receives the tool's `structuredContent`. */+ outputSchema?: unknown;/** Pi 1.0+: declared to the model and never callable from other tools, as Pi documents for tools that ask the user. */exposure?: "model-only";execute(@@ -71,7 +81,7 @@ interface PiToolDefinition {signal: AbortSignal | undefined,onUpdate: unknown,context: PiToolContext,- ): Promise<{ content: PiToolContent[]; details: Record<string, never> }>;+ ): Promise<{ content: PiToolContent[]; details: Record<string, unknown>; structuredContent?: unknown; isError?: boolean }>;}/** The slice of Pi 0.84's ExtensionAPI this standalone file uses; the user's installed Pi supplies it. */@@ -92,6 +102,10 @@ const TOOL_NAME_MAX_LENGTH = 64;const SHELL_DEFAULT_TIMEOUT_SECONDS = 120;const SHELL_MAX_TIMEOUT_SECONDS = 900;+/** A server answered with a JSON-RPC error (as opposed to timing out or aborting), so a capability+ * it refused can be retried without it. */+class McpRequestRefused extends Error {}+export class StdioMcp {private child: ChildProcessWithoutNullStreams;private buf = "";@@ -156,7 +170,7 @@ export class StdioMcp {if (typeof msg.id === "number" && this.pending.has(msg.id)) {const p = this.pending.get(msg.id)!;this.pending.delete(msg.id);- if (msg.error) p.reject(new Error(msg.error.message ?? "MCP error"));+ if (msg.error) p.reject(new McpRequestRefused(msg.error.message ?? "MCP error"));else p.resolve(msg.result);continue;}@@ -226,18 +240,29 @@ export class StdioMcp {this.write({ jsonrpc: "2.0", method, params });}- async init(): Promise<void> {+ /** `advertiseUi` adds the MCP Apps extension to the handshake (the same `withUiExtension` the+ * gate and the chat client use), so a server that adapts to the client capability sends its app+ * `_meta`. A server that refuses the extension is reconnected without it, exactly as the gate+ * does, so a strict server keeps working. */+ async init(advertiseUi = false): Promise<void> {const budget = this.remote ? REMOTE_MCP_STARTUP_MS : this.startupMs;this.listDeadline = this.remote ? Date.now() + budget : undefined;- await this.call(- "initialize",- {- protocolVersion: "2024-11-05",- capabilities: {},- clientInfo: { name: "openmausbot-pi", version: "1" },- },- budget,- );+ const handshake = {+ protocolVersion: "2024-11-05",+ capabilities: {},+ clientInfo: { name: "openmausbot-pi", version: "1" },+ };+ if (advertiseUi) {+ try {+ await this.call("initialize", withUiExtension(handshake), budget);+ } catch (err) {+ // Only a server that refused the extension is retried; a timeout must not double the budget.+ if (!(err instanceof McpRequestRefused)) throw err;+ await this.call("initialize", handshake, budget);+ }+ } else {+ await this.call("initialize", handshake, budget);+ }this.notify("notifications/initialized");}@@ -263,34 +288,33 @@ export class StdioMcp {throw new Error(`MCP tools/list exceeded ${MCP_MAX_LIST_PAGES} pages`);}- /** Text is bounded so a remote server cannot flood the model context. */- async callTool(name: string, args: unknown, signal?: AbortSignal): Promise<{ content: PiToolContent[]; isError: boolean }> {+ /** Text is bounded so a remote server cannot flood the model context. Every content kind is+ * converted (never silently dropped), and `structuredContent`/`_meta` ride along for the host. */+ async callTool(name: string, args: unknown, signal?: AbortSignal): Promise<ConvertedMcpResult> {const res = (await this.call("tools/call",{ name, arguments: args ?? {} },MCP_TOOL_TIMEOUT_MS,signal,- )) as { content?: unknown; isError?: boolean } | undefined;- const rawContent = Array.isArray(res?.content) ? res.content : [];- const text = rawContent- .filter((c): c is McpTextContent => Boolean(c) && (c as { type?: unknown }).type === "text")- .map((c) => String(c.text ?? ""))+ )) as McpCallResult | undefined;+ const converted = mcpContentToPiContent(res?.content);+ const text = converted+ .filter((c): c is { type: "text"; text: string } => c.type === "text")+ .map((c) => c.text).join("\n");- const images = rawContent- .filter(- (c): c is McpImageContent =>- Boolean(c) &&- (c as { type?: unknown }).type === "image" &&- typeof (c as McpImageContent).data === "string" &&- typeof (c as McpImageContent).mimeType === "string",- )- .map((c) => ({ type: "image" as const, data: String(c.data), mimeType: String(c.mimeType) }));- const unsupported = rawContent.length - rawContent.filter((c) => (c as { type?: unknown })?.type === "text").length - images.length;- let boundedText = truncateToolText(text || (images.length ? "" : "(empty result)"));- if (unsupported > 0) boundedText += `${boundedText ? "\n" : ""}[${unsupported} unsupported MCP content item(s) omitted]`;+ const images = converted.filter((c): c is { type: "image"; data: string; mimeType: string } => c.type === "image");+ // A structured result without content blocks is shown as its JSON, so the model sees it too.+ const fallback = res?.structuredContent !== undefined+ ? JSON.stringify(res.structuredContent, null, 2)+ : "(empty result)";+ const boundedText = truncateToolText(text || (images.length ? "" : fallback));return {content: [...(boundedText ? [{ type: "text" as const, text: boundedText }] : []), ...images],isError: Boolean(res?.isError),+ ...(res?.structuredContent !== undefined ? { structuredContent: res.structuredContent } : {}),+ ...(res?._meta && typeof res._meta === "object" && !Array.isArray(res._meta)+ ? { _meta: res._meta as Record<string, unknown> }+ : {}),};}@@ -680,7 +704,7 @@ export default async function (pi: PiExtensionApi): Promise<void> {let client: StdioMcp | undefined;try {client = new StdioMcp(def);- await client.init();+ await client.init(true);return { serverName, def, client, tools: await client.listTools() };} catch (err) {const message = err instanceof Error ? err.message : String(err);@@ -702,6 +726,9 @@ export default async function (pi: PiExtensionApi): Promise<void> {process.stderr.write(`[openmausbot-pi-mcp] ${serverName}: skipped a tool with no valid name\n`);continue;}+ // App-only tools (`_meta.ui.visibility: ["app"]`) are for the app's own view, never the model.+ // The gate already removes them behind a gate; a directly mounted server is filtered here.+ if (!modelVisible(tool)) continue;const toolName = tool.name;const identity: ToolIdentity = { kind: "mcp", server: serverName, name: toolName };const directoryTool = def.directory === true && isDirectoryTool(toolName);@@ -714,6 +741,8 @@ export default async function (pi: PiExtensionApi): Promise<void> {label: `${serverName}:${toolName}`,description: typeof tool.description === "string" ? tool.description : `${toolName} (MCP tool from ${serverName})`,parameters,+ // The full CallToolResult, so a codemode script receives the MCP `structuredContent`.+ outputSchema: MCP_RESULT_OUTPUT_SCHEMA,async execute(_toolCallId, params, signal, _onUpdate, ctx) {const target = directoryTool ? directoryCallTarget(toolName, params) : toolName;if (scope !== undefined && (enforcementFailed@@ -742,7 +771,15 @@ export default async function (pi: PiExtensionApi): Promise<void> {// Pi marks a custom tool failed only when execute throws.throw new Error(message || `MCP tool ${serverName}:${toolName} returned an error`);}- return { content: res.content, details: {} };+ return {+ content: res.content,+ details: {+ server: serverName,+ tool: toolName,+ ...(res._meta ? { meta: res._meta } : {}),+ },+ ...(res.structuredContent !== undefined ? { structuredContent: res.structuredContent } : {}),+ };},});used.add(name);diff --git a/server/mcp-tool-content.ts b/server/mcp-tool-content.tsnew file mode 100644index 0000000000..e1ffcce960--- /dev/null+++ b/server/mcp-tool-content.ts@@ -0,0 +1,76 @@+// MCP tool-result content, converted once for every adapter that renders a server's result to a+// model. A new engine adapter imports this instead of copying a per-driver switch, so a content+// kind added by the spec reaches every adapter at the same time.+//+// The mapping follows pi's own MCP extension (`@earendil-works/pi-mcp` `toLlmContent`): a model+// reads text and images, so the other kinds keep an explicit placeholder rather than being dropped+// silently — a `show_voice_note`-style tool whose audio would otherwise vanish leaves a line the+// model and the log can see. The raw block still rides in the tool result's `structuredContent` and+// `_meta`, which a host can use to attach the audio itself.++/** pi's model-facing content: text and base64 images. */+export type PiToolContent = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string };++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function oneContentBlock(block: unknown): PiToolContent {+ if (!isRecord(block)) return { type: "text", text: "[unsupported MCP content]" };+ const type = typeof block.type === "string" ? block.type : "";+ switch (type) {+ case "text":+ return { type: "text", text: String(block.text ?? "") };+ case "image":+ return { type: "image", data: String(block.data ?? ""), mimeType: String(block.mimeType ?? "") };+ case "audio":+ // pi's model content has no audio; keep a placeholder so the block is visible, never silent.+ return { type: "text", text: `[audio ${String(block.mimeType ?? "unknown type")} omitted]` };+ case "resource_link":+ return { type: "text", text: `${String(block.name ?? "resource")}: ${String(block.uri ?? "")}` };+ case "resource": {+ const resource = isRecord(block.resource) ? block.resource : undefined;+ if (resource && typeof resource.text === "string") return { type: "text", text: resource.text };+ if (resource && typeof resource.blob === "string" && String(resource.mimeType ?? "").startsWith("image/")) {+ return { type: "image", data: resource.blob, mimeType: String(resource.mimeType) };+ }+ const uri = resource && typeof resource.uri === "string" ? resource.uri : "";+ const mime = resource && typeof resource.mimeType === "string" ? resource.mimeType : "unknown type";+ return { type: "text", text: `[binary resource ${uri} (${mime}) omitted]` };+ }+ default:+ return { type: "text", text: `[unsupported MCP content ${type || "unknown"}]` };+ }+}++/** The content blocks of an MCP `tools/call` result as pi's model content, one output per input. */+export function mcpContentToPiContent(content: unknown): PiToolContent[] {+ return (Array.isArray(content) ? content : []).map(oneContentBlock);+}++/** Schema of the `CallToolResult` every MCP tool returns: what programmatic callers (pi codemode+ * scripts) receive in `structuredContent`. `structuredContent` stays open because a server may+ * send any JSON value, including one it declares no schema for. */+export const MCP_RESULT_OUTPUT_SCHEMA = {+ type: "object",+ properties: {+ content: {+ type: "array",+ items: {+ type: "object",+ properties: {+ type: { enum: ["text", "image", "audio", "resource_link", "resource"] },+ text: { type: "string" },+ data: { type: "string" },+ mimeType: { type: "string" },+ },+ required: ["type"],+ additionalProperties: true,+ },+ },+ structuredContent: {},+ isError: { type: "boolean" },+ },+ required: ["content"],+ additionalProperties: true,+} as const;