Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

20.8 KB
Raw Blame
// Connection requests become OpenMausBot chat cards: the agent never authors an auth URL and credentials never pass
// through its transcript. stdout is the MCP transport: never log there.
import { randomUUID } from "node:crypto";
import { setTimeout as delay } from "node:timers/promises";
import {
  CONNECTOR_ALLOWED_TOOLS_ENV,
  CONNECTOR_SERVICE_SLUGS_ENV,
  filterToolsListFrame,
  parseConnectorAllowedToolsEnv,
  parseConnectorServiceSlugsEnv,
  withConnectionParameters,
} from "./connector-advertisement.ts";
import { APP_TOOL_NAMES_ENV, APP_TOOLS_ENV, appToolAnswer, appToolCall, appToolEntries, parseAppToolsEnv } from "./connector-app-tools.ts";
import { DISCOVERY_FALLBACK_TOOLS } from "./connector-discovery-fallback.ts";
import { ARGUMENT_REFUSAL, argumentRefusalNote, fitArguments, fittedArgumentsNote, preservesNumericText } from "./connector-arguments.ts";
import { annotateFailedCall } from "./connector-scope-hint.ts";
import { withSignedOutHint } from "./connector-signed-out-hint.ts";
import { AUTH_CONFIG_ID } from "../shared/connector-availability.ts";
import { fitToolListResult } from "./mcp-tool-schema.ts";
import { toolSchemaProfileFromEnv } from "./tool-schema-profile.ts";
import { capToolListResult, toolLimitFromEnv } from "./tool-count-limit.ts";
import { toolsListResultForSessionShare } from "./tool-list-share.ts";
import { readStdioLines } from "./stdio-lines.ts";

type Json = Record<string, unknown>;

const UPSTREAM = process.env.OMB_CONNECTOR_UPSTREAM_URL ?? "";
const HARNESS = process.env.OMB_HARNESS_URL ?? "http://127.0.0.1:8799";
const BOT_ID = process.env.OMB_BOT_ID ?? "";
const THREAD_ID = process.env.OMB_THREAD_ID ?? "";
const TOKEN = process.env.OMB_CONNECTOR_TOKEN ?? process.env.OMB_COMMS_TOKEN ?? "";
const ALLOWED_TOOLS = parseConnectorAllowedToolsEnv(process.env[CONNECTOR_ALLOWED_TOOLS_ENV]);
const SERVICE_SLUGS = parseConnectorServiceSlugsEnv(process.env[CONNECTOR_SERVICE_SLUGS_ENV]);
const SCHEMA_PROFILE = toolSchemaProfileFromEnv(process.env);
const TOOL_LIMIT = toolLimitFromEnv(process.env);
const APP_TOOLS = parseAppToolsEnv(process.env[APP_TOOLS_ENV]);
const APP_TOOL_NAMES = process.env[APP_TOOL_NAMES_ENV] === "dotted" ? "dotted" : "plain";
const MAX_RESPONSE_BYTES = 20 * 1024 * 1024;
const INITIALIZE_RELAY_TIMEOUT_MS = 1_000;
const RELAY_TIMEOUT_MS = 10 * 60_000;
const TOOLS_LIST_RETRY_MS = 500;
// Both listing attempts together: Antigravity's CLI drops a stdio server whose tool list is not back ~5 s after it starts.
const TOOLS_LIST_BUDGET_MS = 3_000;

function parsedHeaders(): Record<string, string> {
  try {
    const value: unknown = JSON.parse(process.env.OMB_CONNECTOR_UPSTREAM_HEADERS ?? "{}");
    if (!value || typeof value !== "object" || Array.isArray(value)) return {};
    return Object.fromEntries(
      Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === "string"),
    );
  } catch {
    return {};
  }
}

const upstreamHeaders = parsedHeaders();
let upstreamSessionId = "";
/** Each listed tool's input schema, as the connector service listed it: what a call's arguments are fitted to. */
const SCHEMAS = new Map<string, unknown>();
/** The connected apps this bot may use, named when a refused call might read as "no such tool". */
const USABLE_APPS = ALLOWED_TOOLS ? SERVICE_SLUGS.filter((slug) => Object.hasOwn(ALLOWED_TOOLS, slug)) : SERVICE_SLUGS;
const send = (message: Json) => process.stdout.write(`${JSON.stringify(message)}\n`);

function textResult(id: unknown, text: string, isError = false): Json {
  return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text }], ...(isError ? { isError: true } : {}) } };
}

function jsonRpcError(id: unknown, message: string): Json {
  return { jsonrpc: "2.0", id, error: { code: -32000, message } };
}

function initializeResult(id: unknown, protocolVersion: unknown): Json {
  return {
    jsonrpc: "2.0",
    id,
    result: {
      protocolVersion: typeof protocolVersion === "string" && protocolVersion ? protocolVersion : "2024-11-05",
      capabilities: { tools: {} },
      serverInfo: { name: "openmausbot-connectors", version: "1" },
    },
  };
}

async function readBounded(response: Response): Promise<string> {
  const declared = Number(response.headers.get("content-length") ?? "0");
  if (declared > MAX_RESPONSE_BYTES) throw new Error("connector response exceeded 20 MB");
  if (!response.body) return "";
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let size = 0;
  let text = "";
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    size += value.byteLength;
    if (size > MAX_RESPONSE_BYTES) {
      await reader.cancel();
      throw new Error("connector response exceeded 20 MB");
    }
    text += decoder.decode(value, { stream: true });
  }
  return text + decoder.decode();
}

function parseUpstream(text: string, id: unknown): Json | null {
  const trimmed = text.trim();
  if (!trimmed) return null;
  if (trimmed.startsWith("{")) return JSON.parse(trimmed) as Json;
  const frames = trimmed
    .split(/\r?\n/)
    .filter((line) => line.startsWith("data:"))
    .map((line) => line.slice(5).trim())
    .filter((line) => line && line !== "[DONE]")
    .flatMap((line) => {
      try {
        return [JSON.parse(line) as Json];
      } catch {
        return [];
      }
    });
  return frames.findLast((frame) => frame.id === id) ?? frames.at(-1) ?? null;
}

async function relay(message: Json, timeoutMs = RELAY_TIMEOUT_MS): Promise<Json | null> {
  if (!UPSTREAM) throw new Error("connected apps are unavailable");
  const response = await fetch(UPSTREAM, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      accept: "application/json, text/event-stream",
      ...upstreamHeaders,
      ...(upstreamSessionId ? { "mcp-session-id": upstreamSessionId } : {}),
    },
    body: JSON.stringify(message),
    signal: AbortSignal.timeout(timeoutMs),
  });
  const nextSession = response.headers.get("mcp-session-id");
  if (nextSession) upstreamSessionId = nextSession;
  if (!response.ok) throw Object.assign(new Error(`connector service returned HTTP ${response.status}`), { status: response.status });
  return parseUpstream(await readBounded(response), message.id);
}

interface ConnectorRequest {
  slug: string;
  alias?: string;
  authConfigId?: string;
}

const BAD_AUTH_CONFIG_ID = "OpenMausBot showed no card: auth_config_id must be a Composio auth config id (ac_ and then letters "
  + "or digits), copied from Auth Configs in the person's Composio project. Leave it out to use their newest enabled config.";

/** Composio's own error names `auth_config_override`, so either spelling is read: on a toolkit entry, or at the top level
 * as one id for a single toolkit or a { toolkit: id } map. */
function requestedAuthConfig(row: Record<string, unknown>): unknown {
  return row.auth_config_id ?? row.auth_config_override;
}

function topLevelAuthConfig(args: Record<string, unknown>, slug: string, toolkitCount: number): unknown {
  const value = requestedAuthConfig(args);
  if (value && typeof value === "object" && !Array.isArray(value)) {
    return Object.entries(value).find(([key]) => key.trim().toLowerCase() === slug)?.[1];
  }
  // One id cannot say which of several toolkits it belongs to.
  return value !== undefined && toolkitCount !== 1 ? null : value;
}

function connectorAdds(args: unknown): { requests: ConnectorRequest[]; badAuthConfig: boolean } {
  if (!args || typeof args !== "object" || Array.isArray(args)) return { requests: [], badAuthConfig: false };
  const toolkits = (args as { toolkits?: unknown }).toolkits;
  if (!Array.isArray(toolkits)) return { requests: [], badAuthConfig: false };
  const seen = new Set<string>();
  const requests: Array<ConnectorRequest & { authConfig?: unknown }> = [];
  for (const item of toolkits) {
    if (typeof item === "string") {
      const slug = item.trim().toLowerCase();
      const key = JSON.stringify([slug, ""]);
      if (!seen.has(key)) {
        seen.add(key);
        requests.push({ slug });
      }
      continue;
    }
    if (!item || typeof item !== "object" || Array.isArray(item)) continue;
    const row = item as { name?: unknown; toolkit?: unknown; action?: unknown; alias?: unknown; account?: unknown };
    const action = String(row.action ?? "add").toLowerCase();
    if (!["add", "connect", "initiate"].includes(action)) continue;
    const slug = typeof row.toolkit === "string" ? row.toolkit : row.name;
    if (typeof slug !== "string") continue;
    const normalized = slug.trim().toLowerCase();
    const alias = (typeof row.alias === "string" ? row.alias : typeof row.account === "string" ? row.account : "").trim();
    const key = JSON.stringify([normalized, alias.toLowerCase()]);
    if (seen.has(key)) continue;
    seen.add(key);
    const authConfig = requestedAuthConfig(row as Record<string, unknown>);
    requests.push({ slug: normalized, ...(alias ? { alias } : {}), ...(authConfig !== undefined ? { authConfig } : {}) });
  }
  let badAuthConfig = false;
  const checked = requests.map(({ authConfig, ...request }) => {
    const value = authConfig ?? topLevelAuthConfig(args as Record<string, unknown>, request.slug, requests.length);
    if (value === undefined) return request;
    if (typeof value !== "string" || !AUTH_CONFIG_ID.test(value.trim())) {
      badAuthConfig = true;
      return request;
    }
    return { ...request, authConfigId: value.trim() };
  });
  return { requests: checked, badAuthConfig };
}

/** Resolves to the harness's lines on which auth config each toolkit connects with, and on apps already connected, when it has any. */
async function showConnectorCards(items: ConnectorRequest[]): Promise<{ notes: string; nothingToSignIn: boolean }> {
  const response = await fetch(`${HARNESS}/api/internal/connectors/request`, {
    method: "POST",
    headers: { "content-type": "application/json", authorization: `Bearer ${TOKEN}` },
    body: JSON.stringify({ botId: BOT_ID, threadId: THREAD_ID, items, resumeKey: randomUUID() }),
    signal: AbortSignal.timeout(30_000),
  });
  const body = (await response.json().catch(() => ({}))) as { error?: unknown; authConfigNote?: unknown; connectedNote?: unknown; nothingToSignIn?: unknown };
  if (!response.ok) throw new Error(String(body.error ?? `could not show connection card (HTTP ${response.status})`));
  const notes = [body.authConfigNote, body.connectedNote].map((note) => (typeof note === "string" && note ? ` ${note}` : "")).join("");
  return { notes, nothingToSignIn: body.nothingToSignIn === true };
}

/** The harness's answer to a bot's search of the catalog. */
async function findApps(query: string): Promise<string> {
  const response = await fetch(`${HARNESS}/api/internal/connectors/find`, {
    method: "POST",
    headers: { "content-type": "application/json", authorization: `Bearer ${TOKEN}` },
    body: JSON.stringify({ botId: BOT_ID, threadId: THREAD_ID, query }),
    signal: AbortSignal.timeout(30_000),
  });
  const body = (await response.json().catch(() => ({}))) as { error?: unknown; text?: unknown };
  if (!response.ok || typeof body.text !== "string") throw new Error(String(body.error ?? `could not search the apps (HTTP ${response.status})`));
  return body.text;
}

/** The upstream list with the app tools after it, unless it already has one by that name. */
function withAppTools(frame: Json): Json {
  const result = frame.result as { tools?: unknown } | undefined;
  if (!APP_TOOLS.length || !result || !Array.isArray(result.tools)) return frame;
  const listed = new Set(result.tools.map((tool) => (tool as { name?: unknown })?.name));
  const added = appToolEntries(APP_TOOLS, APP_TOOL_NAMES).filter((tool) => !listed.has(tool.name));
  return { ...frame, result: { ...result, tools: [...result.tools, ...added] } };
}

function rememberSchemas(frame: Json): Json {
  const tools = (frame.result as { tools?: unknown } | undefined)?.tools;
  if (Array.isArray(tools)) {
    for (const tool of tools) {
      const { name, inputSchema } = (tool ?? {}) as { name?: unknown; inputSchema?: unknown };
      if (typeof name === "string" && inputSchema !== undefined) SCHEMAS.set(name, inputSchema);
    }
  }
  return frame;
}

/** A call refused over its arguments says how to call again; one whose arguments were fitted says how they were read. */
function withArgumentNotes(name: string, response: Json, changed: readonly string[]): Json {
  const error = response.error as { message?: unknown } | undefined;
  if (error && typeof error.message === "string" && ARGUMENT_REFUSAL.test(error.message)) {
    return textResult(response.id, `${error.message}\n\n${argumentRefusalNote(name, SCHEMAS.get(name), USABLE_APPS)}`, true);
  }
  if (annotateFailedCall(response, ARGUMENT_REFUSAL, (tools) => argumentRefusalNote(tools[0] ?? name, SCHEMAS.get(tools[0] ?? name), USABLE_APPS), [name])) return response;
  const result = response.result as { content?: unknown; isError?: unknown } | undefined;
  if (changed.length && result && result.isError !== true && Array.isArray(result.content)) result.content.push({ type: "text", text: fittedArgumentsNote(name, changed) });
  return response;
}

function fittedList(frame: Json): Json {
  if (!("result" in frame)) return frame;
  const log = (line: string) => process.stderr.write(`connector-proxy: ${line}\n`);
  return { ...frame, result: toolsListResultForSessionShare(capToolListResult(fitToolListResult(frame.result, SCHEMA_PROFILE, log), TOOL_LIMIT, log), process.env, log) };
}

/** A refusal that answers the same way every time: an HTTP 4xx other than 429, or a result that is not a list (the
 * harness's own refusal of this bot). A timeout, a dropped connection, a 5xx, a 429, a JSON-RPC error or a reply that
 * cannot be read is an outage. */
function refusedListing(failure: { status?: number } | Json | null): boolean {
  if (failure && "status" in failure && typeof failure.status === "number") return failure.status < 500 && failure.status !== 429;
  return Boolean(failure && "result" in failure && !("error" in failure));
}

async function listTools(message: Json): Promise<Json> {
  let refused = false;
  const deadline = Date.now() + TOOLS_LIST_BUDGET_MS;
  for (let attempt = 0; attempt < 2; attempt += 1) {
    if (attempt) {
      if (deadline - Date.now() <= TOOLS_LIST_RETRY_MS) break;
      await delay(TOOLS_LIST_RETRY_MS);
    }
    try {
      const response = await relay(message, deadline - Date.now());
      if (response && !response.error && Array.isArray((response.result as Json | undefined)?.tools)) return response;
      refused = refusedListing(response);
    } catch (error) {
      refused = refusedListing(error as { status?: number });
    }
    if (refused) break;
  }
  process.stderr.write(refused
    ? "connector-proxy: Connected apps refused this bot's tool list.\n"
    : "connector-proxy: Connected apps are temporarily unavailable; start a new session to retry discovery.\n");
  // In an outage, with a service to send calls to, its own tools still go on the list: calls reach it once it answers again.
  return { jsonrpc: "2.0", id: message.id, result: { tools: UPSTREAM && !refused ? structuredClone(DISCOVERY_FALLBACK_TOOLS) : [] } };
}

async function handle(received: Json): Promise<void> {
  let message = received;
  const id = message.id;
  const method = String(message.method ?? "");
  // OpenCode and other MCP clients mark a stdio server failed unless initialize returns capabilities and serverInfo.
  if (method === "notifications/initialized" || method === "initialized") {
    if (UPSTREAM) void relay(message).catch(() => {});
    return;
  }
  if (method === "initialize") {
    if (UPSTREAM) {
      try {
        // A stalled provider must never keep the local MCP client from mounting the connector tools.
        await relay(message, INITIALIZE_RELAY_TIMEOUT_MS);
      } catch {
      }
    }
    if (id !== undefined) {
      const params = (message.params ?? {}) as Json;
      send(initializeResult(id, params.protocolVersion));
    }
    return;
  }
  // Clients that probe with MCP 2026-07-28's server/discover before initialize (Antigravity CLI 1.5.16, Claude Code 2.1.292)
  // fall back to initialize on Method not found; this proxy answers initialize itself, so it answers the probe too, with
  // no relay of its own: the Antigravity CLI drops a server that has not listed its tools about 5 s after it started it.
  if (method === "server/discover") {
    if (id !== undefined) send({ jsonrpc: "2.0", id, error: { code: -32601, message: "Method not found: server/discover" } });
    return;
  }
  let changed: string[] = [];
  if (method === "tools/call") {
    const given = (message.params ?? {}) as Json;
    const name = String(given.name ?? "");
    const fitted = SCHEMAS.has(name) ? fitArguments(given.arguments, SCHEMAS.get(name)) : { args: given.arguments, changed: [] };
    changed = fitted.changed;
    if (changed.length) message = { ...message, params: { ...given, arguments: fitted.args } };
    const params = (message.params ?? {}) as Json;
    const { requests, badAuthConfig } = /MANAGE_CONNECTIONS$/i.test(name)
      ? connectorAdds(params.arguments)
      : { requests: [], badAuthConfig: false };
    if (badAuthConfig) {
      send(textResult(id, BAD_AUTH_CONFIG_ID, true));
      return;
    }
    if (requests.length) {
      const { notes, nothingToSignIn } = await showConnectorCards(requests);
      const labels = requests.map((r) => (r.alias ? `${r.slug} (${r.alias})` : r.slug)).join(", ");
      send(textResult(
        id,
        nothingToSignIn
          ? `OpenMausBot showed the user a card that ${labels} is already connected; no sign-in started.${notes} Do not end this turn: carry on now.`
          : `OpenMausBot showed the user a secure connection card for ${labels}.${notes} End this turn now. The app will continue the task automatically after the connection finishes.`,
      ));
      return;
    }
    const find = /MANAGE_CONNECTIONS$/i.test(name) ? (params.arguments as { find?: unknown } | undefined)?.find : undefined;
    if (typeof find === "string" && find.trim()) {
      send(textResult(id, await findApps(find)));
      return;
    }
    if (/WAIT_FOR_CONNECTIONS$/i.test(name)) {
      send(textResult(id, "OpenMausBot is handling connection completion and will continue the task automatically."));
      return;
    }
    const app = appToolCall(name, params.arguments);
    if (app) {
      const call = app.frame(id);
      const response = await relay(call);
      if (response && id !== undefined) send(appToolAnswer(app.slug, withSignedOutHint(call, response, SERVICE_SLUGS)));
      return;
    }
  }
  try {
    const response = method === "tools/list"
      ? await listTools(message)
      : await relay(message);
    if (response && id !== undefined) {
      const name = String((message.params as Json | undefined)?.name ?? "");
      send(method === "tools/list" ? fittedList(rememberSchemas(withAppTools(withConnectionParameters(ALLOWED_TOOLS ? filterToolsListFrame(response, ALLOWED_TOOLS, SERVICE_SLUGS) : response))))
        : method === "tools/call" ? withArgumentNotes(name, withSignedOutHint(message, response, SERVICE_SLUGS), changed) : response);
    }
  } catch (error) {
    if (id === undefined) return;
    const messageText = error instanceof Error ? error.message : String(error);
    if (method === "tools/call") send(textResult(id, messageText, true));
    else send(jsonRpcError(id, messageText));
  }
}

readStdioLines(process.stdin, (line) => {
  const trimmed = line.trim();
  if (!trimmed) return;
  let message: Json;
  const unsafeContainers = new WeakSet<object>();
  const unsafeArgumentOwners = new WeakSet<object>();
  try {
    message = JSON.parse(trimmed, function (key: string, value: unknown, context?: { source?: string }) {
      const unsafe = typeof value === "number"
        ? context?.source === undefined || !preservesNumericText(context.source, value)
        : value !== null && typeof value === "object" && unsafeContainers.has(value);
      if (unsafe) {
        unsafeContainers.add(this);
        if (key === "arguments") unsafeArgumentOwners.add(this);
      }
      return value;
    }) as Json;
  } catch {
    return;
  }
  if (message.method === "tools/call" && message.params !== null && typeof message.params === "object"
    && unsafeArgumentOwners.has(message.params)) {
    if (message.id !== undefined) send(textResult(message.id,
      'This connected-app call was not sent: an argument contains a numeric literal that cannot be preserved. '
      + 'Send precision-sensitive IDs as JSON strings when the tool schema accepts strings, for example '
      + '{"record_id":"9007199254740993"}; otherwise check the original value before retrying.', true));
    return;
  }
  void handle(message).catch((error) => {
    if (message.id === undefined) return;
    const method = String(message.method ?? "");
    const messageText = error instanceof Error ? error.message : String(error);
    if (method === "tools/call") send(textResult(message.id, messageText, true));
    else send(jsonRpcError(message.id, messageText));
  });
}, () => process.exit(0));