Skip to content

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

fix(codex): start a turn only after its MCP servers finish starting

Viniciusd3e774ecde88
diff --git a/server/drivers/codex-mcp-startup.ts b/server/drivers/codex-mcp-startup.ts
new file mode 100644
index 0000000000..af439ccd7e
--- /dev/null
+++ b/server/drivers/codex-mcp-startup.ts
@@ -0,0 +1,58 @@
+/** The `mcpServer/startupStatus/updated` states that end a server's startup (codex-cli 0.166.0). */
+const SETTLED_STATES = new Set(["ready", "failed", "cancelled"]);
+
+/** Codex's own limit for one MCP server's startup (codex-rs `DEFAULT_STARTUP_TIMEOUT`), after which it reports it failed. */
+export const MCP_STARTUP_WAIT_MS = 30_000;
+
+export type McpStartupTracker = {
+ /** Records one `mcpServer/startupStatus/updated` params object. */
+ record(update: unknown): void;
+ /**
+ * Waits until every named server reported a settled state or `timeoutMs` passed: true. False when
+ * the wait was aborted or the app-server exited first, so the turn must not start.
+ */
+ settled(names: readonly string[], signal: AbortSignal, timeoutMs?: number): Promise<boolean>;
+};
+
+/**
+ * Codex starts MCP servers alongside `thread/start` and `thread/resume` and does not wait for them
+ * before sampling (codex-cli 0.166.0): a model request built while a server is still starting has
+ * none of its tools, and the model reports them as unavailable. Codex reports every configured
+ * server's startup since codex-cli 0.117.0, after its reply to the thread request.
+ */
+export function mcpStartupTracker(appServer: { once(event: "exit", listener: () => void): unknown }): McpStartupTracker {
+ const states = new Map<string, string>();
+ const waiters = new Set<() => void>();
+ const exited = new AbortController();
+ appServer.once("exit", () => exited.abort());
+ return {
+ record(update) {
+ const record = update && typeof update === "object" ? update as { name?: unknown; status?: unknown } : null;
+ if (typeof record?.name !== "string" || typeof record.status !== "string") return;
+ states.set(record.name, record.status);
+ for (const wake of waiters) wake();
+ },
+ async settled(names, signal, timeoutMs = MCP_STARTUP_WAIT_MS) {
+ const stop = AbortSignal.any([signal, exited.signal]);
+ const done = () => names.every((name) => SETTLED_STATES.has(states.get(name) ?? ""));
+ if (!stop.aborted && !done()) {
+ await new Promise<void>((resolve) => {
+ const finish = () => {
+ clearTimeout(timer);
+ waiters.delete(check);
+ stop.removeEventListener("abort", finish);
+ resolve();
+ };
+ const check = () => {
+ if (done()) finish();
+ };
+ const timer = setTimeout(finish, timeoutMs);
+ timer.unref?.();
+ waiters.add(check);
+ stop.addEventListener("abort", finish, { once: true });
+ });
+ }
+ return !stop.aborted;
+ },
+ };
+}
diff --git a/server/drivers/codex.ts b/server/drivers/codex.ts
index 0c57e0cf79..a15f2e2acc 100644
--- a/server/drivers/codex.ts
+++ b/server/drivers/codex.ts
@@ -1,6 +1,7 @@
import { codexToolSurfaceArgs } from "./codex-tool-surface.ts";
import { codexShellDisabled, GUEST_CONFINED_CODEX_ARGS } from "./codex-guest.ts";
import { TEAM_TOOLS_FAILED, teamToolsFailed } from "./team-tools.ts";
+import { mcpStartupTracker } from "./codex-mcp-startup.ts";
import { type McpApprovalMode, mountMcpServer } from "./codex-mcp-mount.ts";
import { reportUnsupportedCalls, rolloutMark, type RolloutMark } from "./codex-unsupported-calls.ts";
// The `codex` CLI headless over its app-server JSON-RPC (NDJSON on stdio): completion is
@@ -652,6 +653,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const selectedMcp = new Map<string, StdioMcpSpec>();
const selectedApprovals = new Map<string, McpApprovalMode>();
const directoryMounts = new Set<string>();
+ const directMounts: string[] = [];
const literalEnvs = new Map<string, Record<string, string>>();
const scopedServer = (name: string, mountName: string, server: McpServerSpec): StdioMcpSpec | null => {
if (!canUseMcpServer(turn.toolScope, name)) return null;
@@ -718,6 +720,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
Object.assign(env, bridge.env);
for (const name of Object.keys(bridge.env)) mountedNames.add(name);
const prefix = "mcp_servers.openmausbot_phone";
+ directMounts.push("openmausbot_phone");
appServerArgs.push(
"-c", `${prefix}.command=${JSON.stringify(bridge.command)}`,
"-c", `${prefix}.args=${JSON.stringify(bridge.args)}`,
@@ -760,6 +763,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
let codexTurnId: string | null = null;
let startingNativeTurn = false;
const earlyNotifications: any[] = [];
+ const mcpStartup = mcpStartupTracker(child);
const state = {
settled: false,
lastError: "",
@@ -1105,6 +1109,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const p = msg.params ?? {};
// MCP servers start with the thread, before it has an id; this process serves this turn alone.
if (msg.method === "mcpServer/startupStatus/updated") {
+ mcpStartup.record(p);
if (!teamToolsNoticed && teamToolsFailed(p)) {
teamToolsNoticed = true;
emit({ ...base(threadId, turnId), type: "runtime.notice", message: TEAM_TOOLS_FAILED });
@@ -1580,6 +1585,8 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
...(turn.effort ? { effort: turn.effort } : {}),
});
};
+ const mcpReady = await mcpStartup.settled([...selectedMcp.keys(), ...directMounts], stopSignal.signal);
+ if (!mcpReady || stopRequested || state.settled) return releaseSlot();
try {
await startTurn();
} catch (error) {
diff --git a/server/testing/fake-codex-app-server.ts b/server/testing/fake-codex-app-server.ts
index 41929842c9..6433ba62dd 100755
--- a/server/testing/fake-codex-app-server.ts
+++ b/server/testing/fake-codex-app-server.ts
@@ -54,6 +54,9 @@
// and model/list also offers gpt-6.1-sol
// FAKE_CODEX_MCP_START "1": on thread/start, start each `-c mcp_servers.*` mount as codex-cli 0.160.1 does
// (its initialize, or FAKE_CODEX_MCP_HANDSHAKE) and dump mcpStartup[name]
+// FAKE_CODEX_MCP_READY_MS each `-c mcp_servers.*` mount is reported starting after the thread/start or
+// thread/resume reply and ready at once, as codex-cli 0.166.0 does; with this, ready only this many ms
+// later, and the dump records mcpReadyAtTurnStart
// FAKE_CODEX_ROLLOUT rollout path thread/start and thread/resume report as `thread.path`; each happy turn appends a
// namespace-less function_call for retry_thread and codex's "unsupported call: retry_thread" output to it
import { spawn } from "node:child_process";
@@ -281,7 +284,32 @@ const startMcpServers = async (): Promise<Record<string, McpStartup>> => {
return Object.fromEntries(entries);
};
+let mcpPending: string[] = [];
+let mcpReadyAtTurnStart: boolean | undefined;
+// codex-cli 0.166.0 answers the thread request first and reports each server's startup after it.
+const announceMcpStartup = () => {
+ const report = (name: string, status: string, error: string | null = null) =>
+ out({ jsonrpc: "2.0", method: "mcpServer/startupStatus/updated", params: { threadId: null, name, status, error, failureReason: null } });
+ mcpPending = Object.entries(mcpMounts())
+ .filter(([name, fields]) => "command" in fields && name !== process.env.FAKE_CODEX_MCP_FAILED)
+ .map(([name]) => name);
+ for (const name of mcpPending) report(name, "starting");
+ const settle = () => {
+ for (const name of mcpPending.splice(0)) {
+ const started = mcpStartup?.[name];
+ if (started?.status === "failed") report(name, "failed", started.error);
+ else report(name, "ready");
+ }
+ };
+ const delayMs = Number(process.env.FAKE_CODEX_MCP_READY_MS) || 0;
+ if (delayMs > 0) setTimeout(settle, delayMs);
+ else settle();
+};
const threadReply = (response: unknown) => {
+ replyToThread(response);
+ announceMcpStartup();
+};
+const replyToThread = (response: unknown) => {
if (!process.env.FAKE_CODEX_RESTORED_USAGE) return out(response);
const restored = {
jsonrpc: "2.0", method: "thread/tokenUsage/updated",
@@ -318,7 +346,8 @@ const dump = () => {
if (process.env.FAKE_CODEX_DUMP) {
writeDumpAtomic(
process.env.FAKE_CODEX_DUMP,
- JSON.stringify({ pid: process.pid, argv: process.argv.slice(2), env: process.env, calls, decision, ...(mcpStartup ? { mcpStartup } : {}) }, null, 2),
+ JSON.stringify({ pid: process.pid, argv: process.argv.slice(2), env: process.env, calls, decision, ...(mcpStartup ? { mcpStartup } : {}),
+ ...(mcpReadyAtTurnStart !== undefined ? { mcpReadyAtTurnStart } : {}) }, null, 2),
);
}
};
@@ -609,6 +638,7 @@ process.stdin.on("data", (chunk) => {
}
break;
case "turn/start": {
+ if (process.env.FAKE_CODEX_MCP_READY_MS) mcpReadyAtTurnStart = mcpPending.length === 0;
dump();
logStartup("turn/start");
nativeThreadId = msg.params?.threadId ?? nativeThreadId;