fix(server): log MCP startup failures at warning level (#10566)

MCP startup failures previously reached only the unhandled trace log. Keep a diagnostic summary at warning level and omit raw error text from tracing because it can contain credentials and response bodies.
This commit is contained in:
Mohamed Boudra authored and GitHub committed 2026-11-23 11:40:10 +07:00
1 parent cd66d8fd18
commit eedb6ff675
3 files changed
+136 -1

No files matched your search

@@ -18,6 +18,7 @@ import type {
import { CodexAppServerAgentSession } from "./codex-app-server-agent.js";
import {
createFakeCodexAppServer,
waitForNextTimelineItem,
type FakeCodexAppServer,
} from "./codex/test-utils/fake-app-server.js";
import { createTestLogger } from "../../../test-utils/test-logger.js";
@@ -172,6 +173,80 @@ async function createConnectedSession(
return harness;
}
describe("Codex MCP startup logging", () => {
test("warns on failed startup without logging credentials even at trace level", async () => {
const capture = createCapturedLogger();
capture.logger.level = "trace";
const { session, appServer } = await createConnectedSession({}, { logger: capture.logger });
try {
const processed = waitForNextTimelineItem(session);
const secret = "test-mcp-bearer-secret";
const responseBody = `Authorization: Bearer ${secret}; private response body`;
appServer.child.stdout.write(
JSON.stringify({
method: "mcpServer/startupStatus/updated",
params: {
threadId: "thread-1",
name: "paseo",
status: "failed",
error: `MCP client for \`paseo\` failed to start: MCP startup failed: handshaking with MCP server failed: Send message error Transport [test] error: unexpected server response: HTTP 502: ${responseBody}`,
failureReason: null,
},
}) + "\n",
);
appServer.warns({ threadId: "thread-1", message: "Notification queue drained" });
await processed;
expect(capture.entries.filter((entry) => (entry.level ?? 0) >= 40)).toEqual([
expect.objectContaining({
level: 40,
msg: "Codex MCP server startup failed",
serverName: "paseo",
status: "failed",
error: "HTTP 502",
sessionId: "thread-1",
}),
]);
expect(JSON.stringify(capture.entries)).not.toContain(secret);
expect(JSON.stringify(capture.entries)).not.toContain("private response body");
} finally {
await session.close();
}
});
test("logs non-failure startup updates at debug level", async () => {
const capture = createCapturedLogger();
const { session, appServer } = await createConnectedSession({}, { logger: capture.logger });
try {
const processed = waitForNextTimelineItem(session);
const statuses = ["starting", "ready", "cancelled"];
for (const status of statuses) {
appServer.child.stdout.write(
JSON.stringify({
method: "mcpServer/startupStatus/updated",
params: {
threadId: "thread-1",
name: "paseo",
status,
error: null,
failureReason: null,
},
}) + "\n",
);
}
appServer.warns({ threadId: "thread-1", message: "Notification queue drained" });
await processed;
expect(capture.entries.filter((entry) => (entry.level ?? 0) >= 40)).toEqual([]);
expect(capture.entries.filter((entry) => entry.serverName === "paseo")).toEqual(
statuses.map((status) => expect.objectContaining({ level: 20, status })),
);
} finally {
await session.close();
}
});
});
describe("Codex app-server provider controls", () => {
test("GPT-6.1 Sol offers catalog speed tiers and sends Ultrafast", async () => {
const { session, appServer } = await createConnectedSession(
@@ -92,6 +92,7 @@ import {
type CodexServiceTier,
} from "./codex-feature-definitions.js";
import {
CODEX_MCP_STARTUP_STATUS_METHOD,
CodexAppServerClient,
CodexAppServerRpcError,
parseCodexThreadForkResponse,
@@ -2945,6 +2946,32 @@ function isCodexDeltaNotification(
);
}
const CodexMcpStartupStatusSchema = z.object({
name: z.string(),
threadId: z.string().nullish(),
status: z.enum(["starting", "ready", "failed", "cancelled"]),
error: z.string().nullish(),
failureReason: z.string().nullish(),
});
function summarizeCodexMcpStartupError(
error: string | null | undefined,
failureReason: string | null | undefined,
): string {
if (failureReason === "reauthenticationRequired") {
return "Reauthentication required";
}
// Codex includes the remote response body in this error. Keep only the HTTP status.
const httpStatus = error?.match(/\bunexpected server response: HTTP ([45]\d{2}):/)?.[1];
if (httpStatus) {
return `HTTP ${httpStatus}`;
}
if (error?.includes("handshaking with MCP server failed")) {
return "MCP handshake failed";
}
return "Startup error details omitted";
}
const CodexNotificationSchema = z.union([
z
.object({ method: z.literal("thread/started"), params: ThreadStartedNotificationSchema })
@@ -6151,6 +6178,10 @@ export class CodexAppServerAgentSession implements AgentSession {
}
private async processNotification(method: string, params: unknown): Promise<void> {
if (method === CODEX_MCP_STARTUP_STATUS_METHOD) {
this.logMcpStartupStatus(params);
return;
}
const notificationParams = toObjectRecord(params);
if (method === "serverRequest/resolved" && typeof notificationParams?.requestId === "number") {
const requestId = this.mcpElicitationPermissionIds.get(notificationParams.requestId);
@@ -7688,6 +7719,30 @@ export class CodexAppServerAgentSession implements AgentSession {
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item });
}
private logMcpStartupStatus(params: unknown): void {
const parsed = CodexMcpStartupStatusSchema.safeParse(params);
if (!parsed.success) {
this.logger.trace("Invalid Codex MCP server startup status");
return;
}
const { name, threadId, status, error, failureReason } = parsed.data;
const context = {
agentId: this.agentId,
provider: CODEX_PROVIDER,
sessionId: threadId ?? this.currentThreadId,
serverName: name,
status,
};
if (status === "failed") {
this.logger.warn(
{ ...context, error: summarizeCodexMcpStartupError(error, failureReason) },
"Codex MCP server startup failed",
);
return;
}
this.logger.debug(context, "Codex MCP server startup status updated");
}
private warnUnknownNotificationMethod(method: string, params: unknown): void {
if (this.warnedUnknownNotificationMethods.has(method)) {
return;
@@ -9,6 +9,7 @@ import { ProviderLineReader, ProviderStreamLimitError } from "../jsonl-frame-dec
// A measured long-thread resume was 19.75 MB; preserve the existing 32 MiB fixture
// with 4x margin for longer threads. This is provider stdout, not the client protocol.
export const CODEX_PROVIDER_LINE_BYTES = 128 * 1024 * 1024;
export const CODEX_MCP_STARTUP_STATUS_METHOD = "mcpServer/startupStatus/updated";
const DEFAULT_TIMEOUT_MS = 14 * 24 * 60 * 60 * 1000;
const APP_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT_MS = 2_000;
@@ -478,7 +479,11 @@ export class CodexAppServerClient {
}
if (isJsonRpcNotification(raw)) {
this.traceRawEvent(raw);
// Startup errors can include credentials and remote response bodies.
// The session logs a safe summary for this method.
if (raw.method !== CODEX_MCP_STARTUP_STATUS_METHOD) {
this.traceRawEvent(raw);
}
this.notificationHandler?.(raw.method, raw.params);
}
}