From d86952c59dfd8a2641b71f728a247767fa1944cc Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Fri, 31 Jul 2026 06:55:23 +0000 Subject: [PATCH 1/4] fix(openclaw): recover from transient remote MCP startup failures (#7958) OpenClaw 2026.7.1's bundle-mcp runtime turns one failed remote server startup into an empty tool set plus catalog diagnostics, caches that degraded catalog for the whole session, and never retries. A single transient Streamable HTTP reset or MCP request timeout therefore removes an expected integration until the user starts a new session, and the agent can report the integration or its credentials as unavailable. Add scripts/patch-openclaw-mcp-reliability.mts, a version-scoped fail-closed compatibility patch for the reviewed bundle-mcp dist shape: - retry a classified transient streamable-http server startup once with a fresh transport after 120-300 ms of jitter, capped at a 10000 ms connect timeout; - never retry an authentication, authorization, TLS, policy-denial, refused, unreachable, or invalid-configuration failure; - append a temporary-transport statement to an exhausted retry's diagnostic, and only when the surviving failure is itself transient, so a retry that ends in HTTP 401 does not claim credentials were accepted; - drop a diagnostics-carrying catalog at the next idle agent run boundary so a degraded catalog never becomes the session's stable catalog. The patch fails the image build on an unrecognized dist shape and records its removal criterion in the OpenClaw 2026.7.1 dependency review. Signed-off-by: Yimo Jiang Co-Authored-By: Claude Opus 5 (1M context) --- Dockerfile | 16 + ci/full-e2e-cold-path-calibration.json | 1 + ci/source-architecture-budget.json | 2 +- docs/reference/troubleshoot-mcp-servers.mdx | 21 + .../openclaw-2026.7.1-dependency-review.md | 75 +++ scripts/patch-openclaw-mcp-reliability.mts | 394 ++++++++++++ src/lib/sandbox/build-context.ts | 4 + .../openclaw-real-mcp-start-retry-proof.ts | 247 ++++++++ .../onboard-performance-config-schema.test.ts | 1 + test/openclaw-dependency-review.test.ts | 27 + test/openclaw-final-image-layout.test.ts | 1 + test/openclaw-mcp-reliability-patch.test.ts | 561 ++++++++++++++++++ ...openclaw-real-patched-dist-harness.test.ts | 19 +- test/sandbox-build-context.test.ts | 4 + 14 files changed, 1369 insertions(+), 4 deletions(-) create mode 100755 scripts/patch-openclaw-mcp-reliability.mts create mode 100644 test/helpers/openclaw-real-mcp-start-retry-proof.ts create mode 100644 test/openclaw-mcp-reliability-patch.test.ts diff --git a/Dockerfile b/Dockerfile index d78fbe53529..df472fe8070 100644 --- a/Dockerfile +++ b/Dockerfile @@ -81,6 +81,7 @@ FROM scratch AS openclaw-patch-payload COPY scripts/patch-openclaw-tool-catalog.mts /usr/local/lib/nemoclaw/patch-openclaw-tool-catalog.mts COPY scripts/patch-openclaw-chat-send.mts /usr/local/lib/nemoclaw/patch-openclaw-chat-send.mts COPY scripts/patch-openclaw-mcp-npx.mts /usr/local/lib/nemoclaw/patch-openclaw-mcp-npx.mts +COPY scripts/patch-openclaw-mcp-reliability.mts /usr/local/lib/nemoclaw/patch-openclaw-mcp-reliability.mts COPY scripts/patch-openclaw-issue-4434-diagnostics.mts /usr/local/lib/nemoclaw/patch-openclaw-issue-4434-diagnostics.mts COPY scripts/patch-openclaw-device-self-approval.mts /usr/local/lib/nemoclaw/patch-openclaw-device-self-approval.mts COPY scripts/extract-semver.sh /usr/local/lib/nemoclaw/extract-semver @@ -305,6 +306,7 @@ COPY --from=openclaw-patch-payload / / RUN chmod 755 /usr/local/lib/nemoclaw/patch-openclaw-tool-catalog.mts \ /usr/local/lib/nemoclaw/patch-openclaw-chat-send.mts \ /usr/local/lib/nemoclaw/patch-openclaw-mcp-npx.mts \ + /usr/local/lib/nemoclaw/patch-openclaw-mcp-reliability.mts \ /usr/local/lib/nemoclaw/patch-openclaw-issue-4434-diagnostics.mts \ /usr/local/lib/nemoclaw/patch-openclaw-device-self-approval.mts \ /usr/local/lib/nemoclaw/extract-semver \ @@ -921,6 +923,20 @@ RUN node --experimental-strip-types /usr/local/lib/nemoclaw/patch-openclaw-issue RUN node --experimental-strip-types /usr/local/lib/nemoclaw/patch-openclaw-mcp-npx.mts \ /usr/local/lib/node_modules/openclaw/dist +# Recover from a transient remote Streamable HTTP MCP startup failure. OpenClaw +# 2026.7.1 turns one reset or request timeout into an empty tool set plus +# catalog diagnostics, and keeps that degraded catalog for the whole session, so +# the agent reports the integration as unavailable until a new session starts. +# The patch retries a classified transient startup once with a fresh transport +# and drops a diagnostics-carrying catalog at the next agent run. Authentication, +# authorization, TLS, policy, and configuration failures are never retried. +# +# Removal criteria: drop when upstream OpenClaw provides bounded startup retry, +# negative-catalog invalidation, and temporary-transport failure attribution. +# hadolint ignore=DL3059 +RUN node --experimental-strip-types /usr/local/lib/nemoclaw/patch-openclaw-mcp-reliability.mts \ + /usr/local/lib/node_modules/openclaw/dist + # Run the compact tool catalog shim for OpenClaw selection runtimes that still # need it. OpenClaw 2026.7.1 ships a built-in catalog surface, so the script # skips cleanly after classifying the compiled selection-*.js shape. diff --git a/ci/full-e2e-cold-path-calibration.json b/ci/full-e2e-cold-path-calibration.json index 0c6652bf53a..ca581929318 100644 --- a/ci/full-e2e-cold-path-calibration.json +++ b/ci/full-e2e-cold-path-calibration.json @@ -189,6 +189,7 @@ "scripts/patch-openclaw-tool-catalog.mts", "scripts/patch-openclaw-chat-send.mts", "scripts/patch-openclaw-mcp-npx.mts", + "scripts/patch-openclaw-mcp-reliability.mts", "scripts/patch-openclaw-issue-4434-diagnostics.mts", "scripts/patch-openclaw-device-self-approval.mts", "scripts/verify-wechat-runtime-lock.mts", diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index 3168eb519ba..8d2fa6e43b0 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -148,6 +148,6 @@ "src/lib/actions/sandbox": 182, "src/lib/state": 38, "src/lib/inference": 62, - "scripts": 44 + "scripts": 45 } } diff --git a/docs/reference/troubleshoot-mcp-servers.mdx b/docs/reference/troubleshoot-mcp-servers.mdx index 04ba9cb261a..9f55f055489 100644 --- a/docs/reference/troubleshoot-mcp-servers.mdx +++ b/docs/reference/troubleshoot-mcp-servers.mdx @@ -68,6 +68,27 @@ If a Hermes sandbox is alive but its gateway is not running after a supervisor o Recovery re-establishes the managed service lifecycle, API forwarding, and the exit-75 reload loop used for transactional MCP configuration changes. +## Remote MCP Tools Are Missing for One Agent Turn + + +If a remote Streamable HTTP MCP server times out or resets while its tools are being loaded, NemoClaw retries that startup once with a fresh connection before the agent turn continues. +A successful retry loads the expected tools in the same turn, so no new session is needed. + +If the retry also fails, the sandbox log records a temporary MCP transport failure and states that credentials and configuration were not rejected. +Read that line before rotating a credential: + +```bash +$$nemoclaw logs --tail 100 +``` + +NemoClaw does not retry an authentication, authorization, TLS-validation, network-policy, or invalid-configuration failure inside a turn, because repeating the same request cannot succeed. +A refused or unreachable endpoint is also not retried inside a turn; check the endpoint and its egress policy instead. + +A turn in which any server failed to start does not become the session's cached tool catalog. +NemoClaw contacts that server again on the next agent turn, so a brief upstream outage clears on its own and a repaired credential or policy takes effect without a new session. +A turn in which every server started is cached and reused as usual. + + ## Policy or Provider Ownership Drifted If generated policy or provider metadata drifted, restart fails closed instead of overwriting same-name state. diff --git a/docs/security/openclaw-2026.7.1-dependency-review.md b/docs/security/openclaw-2026.7.1-dependency-review.md index 62b1c17ec8f..146e74399e7 100644 --- a/docs/security/openclaw-2026.7.1-dependency-review.md +++ b/docs/security/openclaw-2026.7.1-dependency-review.md @@ -253,6 +253,81 @@ enforcement without moving the gateway credential into OpenClaw state. After bootstrap, list calls and every `devices approve` remove the gateway URL, port, and shared token so the bounded approval flow uses that device credential. +## Transient Remote MCP Startup Recovery + +`scripts/patch-openclaw-mcp-reliability.mts` is a version-scoped, fail-closed +compatibility patch for issue #7958. In `2026.7.1`, the compiled bundle-mcp +session runtime turns one failed remote server startup into an empty tool set +plus catalog diagnostics, caches that degraded catalog for the whole session, +and never retries. A single transient Streamable HTTP reset or MCP request +timeout therefore removes an expected integration until the user starts a new +session, and the agent can report the integration or its credentials as +unavailable. + +The patch identifies its target by the `"openclaw-bundle-mcp"` client identity +and requires each rewritten anchor to appear exactly once. An unrecognized +compiled shape fails the image build instead of silently skipping, which is how +the removal criterion is enforced. `--audit` re-verifies the applied state. + +Reviewed behavior: + +- one retry, and only one, for a server *startup* failure on a + `streamable-http` transport. A refresh failure on an already-connected + session is not retried; +- the retry uses a fresh transport from the upstream `resolveMcpTransport` + factory after 120-300 ms of jitter, and caps its connection timeout at + 10000 ms so a dead server cannot double an agent run's worst-case latency; +- classification is a fail-closed allow-list over the whole `cause` chain: + MCP request timeout (`-32001`), the OpenClaw connect-timeout message, undici + and POSIX in-flight transport codes, and reset/disconnect-before-headers + text. A blocked-code and blocked-text pass runs first, so authentication, + authorization, OAuth token rejection, TLS and certificate validation, SSRF + and policy denial, and invalid configuration are never retried. A refused, + unreachable, or unresolvable destination is deliberately excluded from the + allow-list: an OpenShell L4 policy denial reaches the MCP client as a refused + connection, and a refused destination is deterministic rather than a + transient in-flight fault; +- an exhausted retry keeps the upstream diagnostic and appends a + temporary-transport statement that explicitly clears credentials and + configuration, so the agent does not report missing credentials for a + transport failure. That statement is added only when the *surviving* failure + is itself transient. A retry that reaches the server and is then rejected + with HTTP 401, a TLS error, or a policy denial keeps its own diagnostic; +- a catalog carrying a server diagnostic is not retained as the session's stable + catalog. It is dropped at the next agent run boundary, in `acquireLease()` and + only while the runtime is idle. Upstream fills `catalog.diagnostics` only from + a per-server start or refresh failure and omits the key when every server + started, so a non-empty array is exactly the degraded case and a healthy + catalog is still reused. A credential, TLS, policy, or configuration rejection + keeps its own diagnostic and is still never retried inside a run, but its + catalog is not sticky either, so a repaired credential is picked up on the + next agent run instead of requiring a new session. Scoping the drop to a run + boundary rather than to every `getCatalog()` call is deliberate: + `getCatalog()` is also the pre-flight for every `callTool`, `listResources`, + `readResource`, `listPrompts`, and `getPrompt`, so dropping it on every call + would rebuild the catalog per tool call and turn one unreachable optional + server into a per-call reconnect cost. Optional MCP servers stay best-effort; +- no credential, SSRF, OAuth, or network-policy behavior changes. + +A first version of this patch was rejected during review on two counts, both +now covered by tests: it retried an OpenShell L4 policy denial because undici +reports it as `TypeError: fetch failed`, and it reported a retry that ended in +HTTP 401 as a temporary transport failure that had not rejected credentials. + +Coverage: `test/openclaw-mcp-reliability-patch.test.ts` pins the compiled +preimage, patch idempotence, fail-closed rejection of an unrecognized shape, +the classification table, and the retry and diagnostic behavior of the injected +runtime. `test/helpers/openclaw-real-mcp-start-retry-proof.ts` runs inside the +`NEMOCLAW_REAL_OPENCLAW_DIST_HARNESS=1` harness and drives the real patched +runtime against a controlled Streamable HTTP MCP server for three scenarios: +first exchange resets then succeeds, every exchange resets, and a persistent +401. The proof asserts that the rejected-credential scenario is contacted once +per run, with no retry inside a run. + +Removal criteria: drop this patch when the reviewed OpenClaw release provides +equivalent bounded startup retry, negative-catalog invalidation, and +temporary-transport failure attribution. + ## Gateway Startup Migration Compatibility OpenClaw `2026.7.1` requires its migration checkpoint to complete without diff --git a/scripts/patch-openclaw-mcp-reliability.mts b/scripts/patch-openclaw-mcp-reliability.mts new file mode 100755 index 00000000000..920f9506c66 --- /dev/null +++ b/scripts/patch-openclaw-mcp-reliability.mts @@ -0,0 +1,394 @@ +#!/usr/bin/env -S node --experimental-strip-types +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const SCRIPT_PATH = fileURLToPath(import.meta.url); + +export const MARKER = "/* nemoclaw mcp transient startup recovery (#7958) */"; + +/** Client identity that only the compiled bundle-mcp session runtime carries. */ +const TARGET_SIGNATURE = '"openclaw-bundle-mcp"'; + +const TASK_OPEN_PATTERN = + "\t\t\t\t\ttasks: preparedEntries.map(({ serverName, rawServer, resolved, safeServerName }) => async () => {"; +const TASK_CLOSE_PATTERN = [ + "\t\t\t\t\t}),", + "\t\t\t\t\tlimit: BUNDLE_MCP_CATALOG_CONNECT_CONCURRENCY,", +].join("\n"); +const START_FAILURE_RETURN_PATTERN = [ + "\t\t\t\t\t\t\treturn {", + "\t\t\t\t\t\t\t\tserverName,", + "\t\t\t\t\t\t\t\tserverEntry: null,", + "\t\t\t\t\t\t\t\ttoolEntries: [],", + "\t\t\t\t\t\t\t\tdiagnostics: diags", + "\t\t\t\t\t\t\t};", +].join("\n"); +const ACQUIRE_LEASE_PATTERN = ["\t\tacquireLease() {", "\t\t\tactiveLeases += 1;"].join("\n"); +const TRANSPORT_FACTORY_PATTERN = "function resolveMcpTransport(serverName, rawServer) {"; +const LOG_WARN_PATTERN = "logWarn("; + +/** Anchors this patch rewrites; each must appear exactly once before patching. */ +const UNPATCHED_TARGET_PATTERNS = [ + TASK_OPEN_PATTERN, + TASK_CLOSE_PATTERN, + START_FAILURE_RETURN_PATTERN, + ACQUIRE_LEASE_PATTERN, +]; +/** Anchors this patch only reads; the retry reuses the upstream transport factory. */ +const REQUIRED_PATTERNS = [...UNPATCHED_TARGET_PATTERNS, TRANSPORT_FACTORY_PATTERN]; + +const TASK_OPEN_REPLACEMENT = [ + "\t\t\t\t\ttasks: preparedEntries.map(({ serverName, rawServer, resolved, safeServerName }) => nemoClawWithMcpStartRetry({", + "\t\t\t\t\t\tserverName,", + "\t\t\t\t\t\tinitialResolved: resolved,", + "\t\t\t\t\t\tresolveTransport: () => resolveMcpTransport(serverName, rawServer),", + "\t\t\t\t\t\tattempt: async (resolved) => {", +].join("\n"); +const TASK_CLOSE_REPLACEMENT = [ + "\t\t\t\t\t\t}", + "\t\t\t\t\t})),", + "\t\t\t\t\tlimit: BUNDLE_MCP_CATALOG_CONNECT_CONCURRENCY,", +].join("\n"); +const START_FAILURE_RETURN_REPLACEMENT = [ + "\t\t\t\t\t\t\treturn {", + "\t\t\t\t\t\t\t\tserverName,", + "\t\t\t\t\t\t\t\tserverEntry: null,", + "\t\t\t\t\t\t\t\ttoolEntries: [],", + "\t\t\t\t\t\t\t\tdiagnostics: diags,", + "\t\t\t\t\t\t\t\t[NEMOCLAW_MCP_START_FAILURE]: {", + "\t\t\t\t\t\t\t\t\terror,", + "\t\t\t\t\t\t\t\t\treusedSession", + "\t\t\t\t\t\t\t\t}", + "\t\t\t\t\t\t\t};", +].join("\n"); +const ACQUIRE_LEASE_REPLACEMENT = [ + "\t\tacquireLease() {", + "\t\t\tif (activeLeases === 0 && nemoClawCatalogHasStartDiagnostics(catalog)) catalog = null;", + "\t\t\tactiveLeases += 1;", +].join("\n"); + +const PATCHED_REQUIRED_PATTERNS = [ + MARKER, + TASK_OPEN_REPLACEMENT, + TASK_CLOSE_REPLACEMENT, + START_FAILURE_RETURN_REPLACEMENT, + ACQUIRE_LEASE_REPLACEMENT, +]; + +/** + * Injected compatibility runtime for OpenClaw `bundle-mcp`. + * + * Retries exactly one classified transient Streamable HTTP server *startup* + * failure with a fresh transport and bounded jitter, and stops a catalog that + * carries any server diagnostic from becoming the session's stable catalog. A + * credential, TLS, policy, or configuration rejection is never retried, and + * keeps its own diagnostic. + */ +export const INJECTED_START_RETRY_HELPER = [ + MARKER, + 'const NEMOCLAW_MCP_START_FAILURE = Symbol.for("nemoclaw.bundleMcpStartFailure");', + "const NEMOCLAW_MCP_RETRY_BASE_DELAY_MS = 120;", + "const NEMOCLAW_MCP_RETRY_JITTER_MS = 180;", + "const NEMOCLAW_MCP_RETRY_CONNECT_TIMEOUT_MS = 1e4;", + "const NEMOCLAW_MCP_ERROR_CHAIN_LIMIT = 8;", + 'const NEMOCLAW_MCP_TRANSIENT_DIAGNOSTIC_SUFFIX = " (temporary MCP transport failure; NemoClaw retried this startup once with a fresh transport. Credentials and configuration were not rejected. The server is retried on the next agent run.)";', + // A refused, unreachable, or unresolvable destination is deterministic, and + // an OpenShell L4 policy denial reaches the client as exactly that. Retrying + // it would repeat a denial the reporter never asked NemoClaw to retry, so + // only in-flight transport faults after a reachable connect are transient. + "const NEMOCLAW_MCP_TRANSIENT_CODES = new Set([", + '\t"ECONNABORTED",', + '\t"ECONNRESET",', + '\t"ENETRESET",', + '\t"EPIPE",', + '\t"ERR_STREAM_PREMATURE_CLOSE",', + '\t"ETIMEDOUT",', + '\t"UND_ERR_BODY_TIMEOUT",', + '\t"UND_ERR_CONNECT_TIMEOUT",', + '\t"UND_ERR_HEADERS_TIMEOUT",', + '\t"UND_ERR_SOCKET"', + "]);", + "const NEMOCLAW_MCP_BLOCKED_CODE_PATTERN = /^(?:CERT_|DEPTH_ZERO|EPROTO|ERR_INVALID_URL|ERR_SSL|ERR_TLS|SELF_SIGNED|UNABLE_TO_)/;", + "const NEMOCLAW_MCP_BLOCKED_TEXT_PATTERN = /\\bunauthorized\\b|\\bforbidden\\b|invalid[_ ](?:client|grant|token)|\\bcertificate\\b|self[- ]signed|\\btls\\b|\\bssrf\\b|blocked by|not allowed|\\bdenied\\b|\\bhttp 4\\d\\d\\b/i;", + // `TypeError: fetch failed` is deliberately absent. undici reports every + // failure that way, including refused, unreachable, and TLS-rejected + // destinations, so classification reads the cause chain instead. + "const NEMOCLAW_MCP_TRANSIENT_TEXT_PATTERN = /socket hang up|other side closed|premature close|before headers|connection reset|request timed out|-32001|mcp server connection timed out after \\d+ms/i;", + "function nemoClawMcpErrorChain(error) {", + "\tconst chain = [];", + "\tlet current = error;", + "\tfor (let depth = 0; depth < NEMOCLAW_MCP_ERROR_CHAIN_LIMIT && current; depth += 1) {", + '\t\tif (typeof current !== "object" && typeof current !== "string") break;', + "\t\tchain.push(current);", + '\t\tcurrent = typeof current === "object" ? current.cause : void 0;', + "\t}", + "\treturn chain;", + "}", + "function nemoClawMcpErrorText(entry) {", + '\tif (typeof entry === "string") return entry;', + '\tconst name = typeof entry.name === "string" ? entry.name : "";', + '\tconst message = typeof entry.message === "string" ? entry.message : "";', + "\treturn `${name} ${message}`;", + "}", + "function nemoClawMcpErrorCodes(entry) {", + '\tif (typeof entry !== "object") return [];', + '\treturn [entry.code, entry.errno].filter((value) => typeof value === "string");', + "}", + "function nemoClawIsTransientMcpStartFailure(error) {", + "\tconst chain = nemoClawMcpErrorChain(error);", + "\tif (chain.length === 0) return false;", + "\tfor (const entry of chain) {", + "\t\tfor (const code of nemoClawMcpErrorCodes(entry)) {", + "\t\t\tif (NEMOCLAW_MCP_BLOCKED_CODE_PATTERN.test(code)) return false;", + "\t\t}", + "\t\tif (NEMOCLAW_MCP_BLOCKED_TEXT_PATTERN.test(nemoClawMcpErrorText(entry))) return false;", + "\t}", + "\tfor (const entry of chain) {", + '\t\tif (typeof entry === "object" && entry.code === -32001) return true;', + "\t\tfor (const code of nemoClawMcpErrorCodes(entry)) {", + "\t\t\tif (NEMOCLAW_MCP_TRANSIENT_CODES.has(code)) return true;", + "\t\t}", + "\t\tif (NEMOCLAW_MCP_TRANSIENT_TEXT_PATTERN.test(nemoClawMcpErrorText(entry))) return true;", + "\t}", + "\treturn false;", + "}", + "function nemoClawMcpRetryDelay() {", + "\tconst delayMs = NEMOCLAW_MCP_RETRY_BASE_DELAY_MS + Math.floor(Math.random() * NEMOCLAW_MCP_RETRY_JITTER_MS);", + "\treturn new Promise((resolve) => setTimeout(resolve, delayMs));", + "}", + // The suffix is the user-facing attribution for an exhausted retry. Add it + // only when the surviving failure is itself transient, so a retry that lands + // on a real 401, TLS, or policy rejection keeps its own diagnostic instead of + // claiming that credentials were not rejected. + "function nemoClawFinalizeMcpStartResult(result, retried) {", + '\tif (!result || typeof result !== "object") return result;', + "\tconst failure = result[NEMOCLAW_MCP_START_FAILURE];", + "\tif (!failure) return result;", + "\tconst next = { ...result };", + "\tdelete next[NEMOCLAW_MCP_START_FAILURE];", + "\tconst transient = retried && nemoClawIsTransientMcpStartFailure(failure.error);", + "\tif (transient && Array.isArray(next.diagnostics)) next.diagnostics = next.diagnostics.map((diagnostic) => ({", + "\t\t...diagnostic,", + "\t\tmessage: `${diagnostic.message}${NEMOCLAW_MCP_TRANSIENT_DIAGNOSTIC_SUFFIX}`", + "\t}));", + "\treturn next;", + "}", + "function nemoClawWithMcpStartRetry(params) {", + "\treturn async () => {", + "\t\tconst first = await params.attempt(params.initialResolved);", + '\t\tconst failure = first && typeof first === "object" ? first[NEMOCLAW_MCP_START_FAILURE] : void 0;', + "\t\tif (!failure || failure.reusedSession) return nemoClawFinalizeMcpStartResult(first, false);", + '\t\tif (params.initialResolved.transportType !== "streamable-http") return nemoClawFinalizeMcpStartResult(first, false);', + "\t\tif (!nemoClawIsTransientMcpStartFailure(failure.error)) return nemoClawFinalizeMcpStartResult(first, false);", + "\t\tlet retryResolved;", + "\t\ttry {", + "\t\t\tretryResolved = params.resolveTransport();", + "\t\t} catch {", + "\t\t\tretryResolved = null;", + "\t\t}", + "\t\tif (!retryResolved) return nemoClawFinalizeMcpStartResult(first, true);", + '\t\tlogWarn(`bundle-mcp: retrying transient startup failure for server "${params.serverName}" once with a fresh transport.`);', + "\t\tawait nemoClawMcpRetryDelay();", + "\t\tconst second = await params.attempt({", + "\t\t\t...retryResolved,", + "\t\t\tconnectionTimeoutMs: Math.min(retryResolved.connectionTimeoutMs, NEMOCLAW_MCP_RETRY_CONNECT_TIMEOUT_MS)", + "\t\t});", + "\t\treturn nemoClawFinalizeMcpStartResult(second, true);", + "\t};", + "}", + // A catalog carrying any server diagnostic is degraded, so it must not become + // the session's stable catalog. Upstream fills `catalog.diagnostics` only from + // a per-server start or refresh failure and omits the key entirely when every + // server started, so a non-empty array is exactly "a server did not start". + "function nemoClawCatalogHasStartDiagnostics(catalog) {", + "\tif (!catalog || !Array.isArray(catalog.diagnostics)) return false;", + "\treturn catalog.diagnostics.length > 0;", + "}", + "", +].join("\n"); + +type PatchStatus = "already-patched" | "patched"; + +type PatchTextResult = { + readonly patched: boolean; + readonly status: PatchStatus; + readonly text: string; +}; + +function usage(): string { + return "Usage: patch-openclaw-mcp-reliability.mts [--audit] "; +} + +function countOccurrences(haystack: string, needle: string): number { + let count = 0; + let index = haystack.indexOf(needle); + while (index !== -1) { + count += 1; + index = haystack.indexOf(needle, index + needle.length); + } + return count; +} + +function readOpenClawVersion(distDir: string): string { + const packageJsonPath = path.resolve(distDir, "..", "package.json"); + let payload: { version?: unknown }; + try { + payload = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")); + } catch (err) { + throw new Error( + `Could not read OpenClaw package metadata at ${packageJsonPath}: ${ + err instanceof Error ? err.message : String(err) + }`, + ); + } + if (typeof payload.version !== "string") { + throw new Error(`OpenClaw package metadata missing string version at ${packageJsonPath}`); + } + return payload.version; +} + +function listJsFiles(dir: string): string[] { + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch (err) { + throw new Error( + `Could not read OpenClaw dist directory ${dir}: ${ + err instanceof Error ? err.message : String(err) + }`, + ); + } + const files: string[] = []; + for (const entry of entries) { + const entryPath = path.join(dir, entry.name); + if (entry.isDirectory()) files.push(...listJsFiles(entryPath)); + else if (entry.isFile() && entry.name.endsWith(".js")) files.push(entryPath); + } + return files.sort(); +} + +/** Fail closed: a recognized bundle-mcp runtime must expose every patch anchor exactly once. */ +export function patchBundleMcpRuntimeText(source: string, filePath: string): PatchTextResult { + if (source.includes(MARKER)) { + for (const pattern of PATCHED_REQUIRED_PATTERNS) { + if (!source.includes(pattern)) { + throw new Error(`${filePath}: MCP startup recovery marker is present but patch is partial`); + } + } + for (const pattern of UNPATCHED_TARGET_PATTERNS) { + if (source.includes(pattern)) { + throw new Error( + `${filePath}: MCP startup recovery marker is present but an unpatched target remains`, + ); + } + } + return { patched: false, status: "already-patched", text: source }; + } + + if (!source.includes(LOG_WARN_PATTERN)) { + throw new Error(`${filePath}: bundle-mcp runtime lacks the expected logWarn diagnostic helper`); + } + for (const pattern of REQUIRED_PATTERNS) { + const count = countOccurrences(source, pattern); + if (count !== 1) { + throw new Error( + `${filePath}: expected exactly one MCP startup recovery target, found ${count}`, + ); + } + } + + const importMatch = source.match(/^(?:import[^\n]*\n)+/); + if (!importMatch) { + throw new Error(`${filePath}: bundle-mcp runtime has no import prologue to anchor the helper`); + } + + let text = `${source.slice(0, importMatch[0].length)}${INJECTED_START_RETRY_HELPER}${source.slice( + importMatch[0].length, + )}`; + text = text.replace(TASK_OPEN_PATTERN, TASK_OPEN_REPLACEMENT); + text = text.replace(TASK_CLOSE_PATTERN, TASK_CLOSE_REPLACEMENT); + text = text.replace(START_FAILURE_RETURN_PATTERN, START_FAILURE_RETURN_REPLACEMENT); + text = text.replace(ACQUIRE_LEASE_PATTERN, ACQUIRE_LEASE_REPLACEMENT); + + for (const pattern of PATCHED_REQUIRED_PATTERNS) { + if (!text.includes(pattern)) { + throw new Error(`${filePath}: MCP startup recovery patch verification failed`); + } + } + return { patched: true, status: "patched", text }; +} + +function resolveBundleMcpRuntimeFile(distDir: string): string { + const targets = listJsFiles(distDir).filter((file) => + fs.readFileSync(file, "utf-8").includes(TARGET_SIGNATURE), + ); + if (targets.length !== 1) { + throw new Error( + `Expected exactly one OpenClaw bundle-mcp runtime in ${distDir}, found ${targets.length}`, + ); + } + return targets[0]; +} + +export function patchOpenClawMcpReliability(distDir: string): { + status: PatchStatus; + file: string; + version: string; +} { + const resolvedDist = path.resolve(distDir); + const version = readOpenClawVersion(resolvedDist); + const target = resolveBundleMcpRuntimeFile(resolvedDist); + const result = patchBundleMcpRuntimeText(fs.readFileSync(target, "utf-8"), target); + if (result.patched) fs.writeFileSync(target, result.text); + return { status: result.status, file: target, version }; +} + +export function auditOpenClawMcpReliability(distDir: string): { file: string; version: string } { + const resolvedDist = path.resolve(distDir); + const version = readOpenClawVersion(resolvedDist); + const target = resolveBundleMcpRuntimeFile(resolvedDist); + const source = fs.readFileSync(target, "utf-8"); + if (!source.includes(MARKER)) { + throw new Error(`${target}: MCP startup recovery patch is not applied`); + } + const result = patchBundleMcpRuntimeText(source, target); + if (result.status !== "already-patched") { + throw new Error(`${target}: MCP startup recovery patch state is not stable`); + } + return { file: target, version }; +} + +function main(argv: readonly string[]): number { + const args = argv.slice(2); + const audit = args[0] === "--audit"; + const distDir = audit ? args[1] : args[0]; + if (!distDir || args.length > (audit ? 2 : 1)) { + console.error(usage()); + return 2; + } + try { + if (audit) { + const result = auditOpenClawMcpReliability(distDir); + console.log( + `INFO: OpenClaw MCP startup recovery audit ok: ${result.file} (openclaw ${result.version})`, + ); + return 0; + } + const result = patchOpenClawMcpReliability(distDir); + console.log( + `INFO: OpenClaw MCP startup recovery ${result.status}: ${result.file} (openclaw ${result.version})`, + ); + return 0; + } catch (err) { + console.error(`ERROR: ${err instanceof Error ? err.message : String(err)}`); + return 1; + } +} + +if (process.argv[1] && path.resolve(process.argv[1]) === SCRIPT_PATH) { + process.exitCode = main(process.argv); +} diff --git a/src/lib/sandbox/build-context.ts b/src/lib/sandbox/build-context.ts index 2bb0abafe0d..b66717f0140 100644 --- a/src/lib/sandbox/build-context.ts +++ b/src/lib/sandbox/build-context.ts @@ -277,6 +277,10 @@ function stageOptimizedSandboxBuildContext( path.join(rootDir, "scripts", "patch-openclaw-mcp-npx.mts"), path.join(stagedScriptsDir, "patch-openclaw-mcp-npx.mts"), ); + fs.copyFileSync( + path.join(rootDir, "scripts", "patch-openclaw-mcp-reliability.mts"), + path.join(stagedScriptsDir, "patch-openclaw-mcp-reliability.mts"), + ); fs.copyFileSync( path.join(rootDir, "scripts", "patch-openclaw-issue-4434-diagnostics.mts"), path.join(stagedScriptsDir, "patch-openclaw-issue-4434-diagnostics.mts"), diff --git a/test/helpers/openclaw-real-mcp-start-retry-proof.ts b/test/helpers/openclaw-real-mcp-start-retry-proof.ts new file mode 100644 index 00000000000..216c2b9427a --- /dev/null +++ b/test/helpers/openclaw-real-mcp-start-retry-proof.ts @@ -0,0 +1,247 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; + +interface ProofOptions { + dist: string; + nodeExecutable: string; + patchScript: string; + timeoutMs: number; +} + +interface ProofScenario { + mode: "recover" | "always-reset" | "unauthorized"; + run1ToolCount: number; + run2ToolCount: number; + run1ServerAttempts: number; + run2ServerAttempts: number; + run1Diagnostics: string[]; + run2Diagnostics: string[]; +} + +function requireSuccess( + result: { status: number | null; stdout?: string | null; stderr?: string | null }, + label: string, +): void { + if (result.status === 0) return; + const detail = String(result.stderr || result.stdout || "").trim(); + throw new Error(`${label}${detail ? `: ${detail}` : ""}: expected exit 0, got ${result.status}`); +} + +function requireEqual(actual: string, expected: string, label: string): void { + if (actual === expected) return; + throw new Error(`${label}: expected ${expected}, got ${actual}`); +} + +/** + * Controlled reporter-workflow proof for NVIDIA/NemoClaw#7958. + * + * Drives the real patched `bundle-mcp` session runtime against a controlled + * Streamable HTTP MCP server whose first POST exchange resets before headers. + * Proves the tools materialize in the original agent run, that an exhausted + * retry reports a temporary transport failure, and that a non-retryable 401 is + * never retried. + */ +export function runRealOpenClawMcpStartRetryProof(options: ProofOptions): void { + const applied = spawnSync( + options.nodeExecutable, + ["--experimental-strip-types", options.patchScript, options.dist], + { encoding: "utf8", timeout: options.timeoutMs }, + ); + requireSuccess(applied, "apply MCP startup recovery patch"); + + const audit = spawnSync( + options.nodeExecutable, + ["--experimental-strip-types", options.patchScript, "--audit", options.dist], + { encoding: "utf8", timeout: options.timeoutMs }, + ); + requireSuccess(audit, "audit MCP startup recovery patch"); + if (!String(audit.stdout ?? "").includes("MCP startup recovery audit ok")) { + throw new Error("MCP startup recovery audit did not confirm the patched dist"); + } + + const runtimeTargets = fs + .readdirSync(options.dist) + .filter((file) => /^agent-bundle-mcp-runtime-.+\.js$/.test(file)) + .filter((file) => + fs + .readFileSync(path.join(options.dist, file), "utf8") + .includes("/* nemoclaw mcp transient startup recovery (#7958) */"), + ); + requireEqual(String(runtimeTargets.length), "1", "MCP startup recovery patch target count"); + + const syntax = spawnSync( + options.nodeExecutable, + ["--check", path.join(options.dist, runtimeTargets[0] as string)], + { encoding: "utf8", timeout: options.timeoutMs }, + ); + requireSuccess(syntax, "validate patched bundle-mcp runtime syntax"); + + // This behavioral proof imports the reviewed bundle-mcp runtime, so install + // its shrinkwrapped production dependencies in the throwaway extraction. + // Lifecycle scripts stay disabled, matching the reviewed Docker boundary. + const packageDir = path.dirname(options.dist); + const install = spawnSync( + "npm", + ["install", "--ignore-scripts", "--omit=dev", "--legacy-peer-deps", "--no-audit", "--no-fund"], + { cwd: packageDir, encoding: "utf8", timeout: options.timeoutMs }, + ); + requireSuccess(install, "install reviewed OpenClaw runtime dependencies without scripts"); + + const proofFile = path.join(options.dist, ".nemoclaw-mcp-start-retry-proof.mjs"); + fs.writeFileSync(proofFile, MCP_START_RETRY_PROOF_SCRIPT); + const proof = spawnSync(options.nodeExecutable, [proofFile], { + cwd: packageDir, + encoding: "utf8", + timeout: options.timeoutMs, + }); + requireSuccess(proof, "run controlled MCP startup recovery proof"); + + const marker = String(proof.stdout ?? "") + .split(/\r?\n/u) + .map((line) => line.trim()) + .find((line) => line.startsWith("NEMOCLAW_MCP_START_RETRY_PROOF=")); + if (!marker) throw new Error("controlled MCP startup recovery proof produced no result marker"); + const scenarios = JSON.parse( + marker.slice("NEMOCLAW_MCP_START_RETRY_PROOF=".length), + ) as ProofScenario[]; + + const byMode = new Map(scenarios.map((scenario) => [scenario.mode, scenario])); + + const recover = byMode.get("recover"); + if (!recover) throw new Error("controlled proof is missing the recover scenario"); + requireEqual(String(recover.run1ToolCount), "1", "recovered tool count in the original run"); + requireEqual(String(recover.run1Diagnostics.length), "0", "recovered run diagnostics"); + requireEqual(String(recover.run2ServerAttempts), "0", "healthy catalog reuse on the next run"); + + const exhausted = byMode.get("always-reset"); + if (!exhausted) throw new Error("controlled proof is missing the always-reset scenario"); + requireEqual(String(exhausted.run1ServerAttempts), "2", "one bounded retry per agent run"); + requireEqual(String(exhausted.run2ServerAttempts), "2", "degraded catalog re-probe on next run"); + for (const [label, diagnostics] of [ + ["run 1", exhausted.run1Diagnostics], + ["run 2", exhausted.run2Diagnostics], + ] as Array<[string, string[]]>) { + requireEqual(String(diagnostics.length), "1", `exhausted retry diagnostic count on ${label}`); + if (!diagnostics[0].includes("temporary MCP transport failure")) { + throw new Error(`exhausted retry diagnostic on ${label} omits the temporary-transport cause`); + } + if (!diagnostics[0].includes("Credentials and configuration were not rejected")) { + throw new Error(`exhausted retry diagnostic on ${label} does not clear credentials`); + } + } + + const unauthorized = byMode.get("unauthorized"); + if (!unauthorized) throw new Error("controlled proof is missing the unauthorized scenario"); + requireEqual(String(unauthorized.run1ServerAttempts), "1", "no retry after an authorization 401"); + requireEqual( + String(unauthorized.run2ServerAttempts), + "1", + "one un-retried attempt per run after an authorization 401", + ); + if (unauthorized.run1Diagnostics[0]?.includes("temporary MCP transport failure")) { + throw new Error("authorization failure was reported as a temporary transport failure"); + } +} + +const MCP_START_RETRY_PROOF_SCRIPT = `// Generated by test/helpers/openclaw-real-mcp-start-retry-proof.ts +import fs from "node:fs"; +import http from "node:http"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +const distDir = path.resolve(process.argv[1], ".."); +const pick = (pattern) => fs.readdirSync(distDir).find((file) => pattern.test(file)); +const runtimeMod = await import(pathToFileURL(path.join(distDir, pick(/^agent-bundle-mcp-runtime-.+\\.js$/))).href); +const materializeMod = await import(pathToFileURL(path.join(distDir, pick(/^agent-bundle-mcp-materialize-.+\\.js$/))).href); +const createSessionMcpRuntime = runtimeMod.n; +const materializeBundleMcpToolsForRun = materializeMod.r; + +const TOOLS = [{ name: "search_docs", description: "Search the remote knowledge base.", inputSchema: { type: "object", properties: { query: { type: "string" } } } }]; + +function startControlledServer(mode) { + let posts = 0; + const server = http.createServer((req, res) => { + if (req.method !== "POST") { + res.writeHead(405).end(); + return; + } + posts += 1; + const attempt = posts; + const chunks = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + if (mode === "unauthorized") { + res.writeHead(401, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: "invalid_token" })); + return; + } + if (mode === "always-reset" || attempt === 1) { + req.socket.destroy(); + return; + } + const body = JSON.parse(Buffer.concat(chunks).toString("utf-8")); + if (typeof body.id === "undefined") { + res.writeHead(202).end(); + return; + } + const result = body.method === "initialize" + ? { protocolVersion: "2025-06-18", capabilities: { tools: { listChanged: false } }, serverInfo: { name: "controlled-remote-mcp", version: "1.0.0" } } + : body.method === "tools/list" ? { tools: TOOLS } : {}; + res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "proof-7958" }); + res.end(JSON.stringify({ jsonrpc: "2.0", id: body.id, result })); + }); + }); + return { server, posts: () => posts }; +} + +async function runScenario(mode) { + const { server, posts } = startControlledServer(mode); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const url = \`http://127.0.0.1:\${server.address().port}/mcp\`; + const workspaceDir = fs.mkdtempSync(path.join(distDir, ".mcp-proof-ws-")); + const runtime = createSessionMcpRuntime({ + sessionId: \`proof-\${mode}\`, + sessionKey: \`proof-\${mode}\`, + workspaceDir, + cfg: { plugins: { enabled: false }, mcp: { servers: { remotedocs: { transport: "streamable-http", url, connectTimeout: 5, requestTimeoutMs: 5000 } } } }, + }); + + const agentRun = async () => { + const before = posts(); + const materialized = await materializeBundleMcpToolsForRun({ runtime, reservedToolNames: new Set() }); + const catalog = runtime.peekCatalog(); + materialized.dispose?.(); + return { + toolCount: materialized.tools.length, + attempts: posts() - before, + diagnostics: (catalog?.diagnostics ?? []).map((entry) => entry.message), + }; + }; + + const run1 = await agentRun(); + const run2 = await agentRun(); + await runtime.dispose?.(); + server.close(); + fs.rmSync(workspaceDir, { recursive: true, force: true }); + return { + mode, + run1ToolCount: run1.toolCount, + run2ToolCount: run2.toolCount, + run1ServerAttempts: run1.attempts, + run2ServerAttempts: run2.attempts, + run1Diagnostics: run1.diagnostics, + run2Diagnostics: run2.diagnostics, + }; +} + +const scenarios = []; +for (const mode of ["recover", "always-reset", "unauthorized"]) { + scenarios.push(await runScenario(mode)); +} +console.log(\`NEMOCLAW_MCP_START_RETRY_PROOF=\${JSON.stringify(scenarios)}\`); +process.exit(0); +`; diff --git a/test/onboard-performance-config-schema.test.ts b/test/onboard-performance-config-schema.test.ts index c9180f3ed70..0a8329c01de 100644 --- a/test/onboard-performance-config-schema.test.ts +++ b/test/onboard-performance-config-schema.test.ts @@ -403,6 +403,7 @@ describe("full-E2E cold-path calibration", () => { "scripts/patch-openclaw-tool-catalog.mts", "scripts/patch-openclaw-chat-send.mts", "scripts/patch-openclaw-mcp-npx.mts", + "scripts/patch-openclaw-mcp-reliability.mts", "scripts/patch-openclaw-issue-4434-diagnostics.mts", "scripts/patch-openclaw-device-self-approval.mts", ]), diff --git a/test/openclaw-dependency-review.test.ts b/test/openclaw-dependency-review.test.ts index 4db26e5e4cd..2fdee81b243 100644 --- a/test/openclaw-dependency-review.test.ts +++ b/test/openclaw-dependency-review.test.ts @@ -49,6 +49,7 @@ const SHARED_STATE_PERMISSIONS_PATCH = path.join( "scripts", "patch-openclaw-shared-state-permissions.mts", ); +const MCP_RELIABILITY_PATCH = path.join(REPO_ROOT, "scripts", "patch-openclaw-mcp-reliability.mts"); const REBUILD_RESUME_SESSION = path.join( REPO_ROOT, "src", @@ -155,6 +156,25 @@ describe("OpenClaw 2026.6.10 dependency review contract", () => { expect(review).toContain("NEMOCLAW_REAL_OPENCLAW_JAEGER_HARNESS=1"); }); + it("records the version-scoped transient remote MCP startup recovery patch (#7958)", () => { + const review = readFileSync(ACTIVE_DEPENDENCY_REVIEW, "utf-8"); + + expect(review).toContain("## Transient Remote MCP Startup Recovery"); + expect(review).toContain("scripts/patch-openclaw-mcp-reliability.mts"); + expect(review).toContain( + 'identifies its target by the `"openclaw-bundle-mcp"` client identity', + ); + expect(review).toContain("one retry, and only one, for a server *startup* failure"); + expect(review).toContain("are never retried"); + expect(review).toContain("dropped at the next agent run boundary"); + expect(review).toContain("test/openclaw-mcp-reliability-patch.test.ts"); + expect(review).toContain("test/helpers/openclaw-real-mcp-start-retry-proof.ts"); + expect(review).toContain("NEMOCLAW_REAL_OPENCLAW_DIST_HARNESS=1"); + expect(review).toContain( + "Removal criteria: drop this patch when the reviewed OpenClaw release", + ); + }); + it("records the active mcporter advisory remediations", () => { const review = readFileSync(ACTIVE_DEPENDENCY_REVIEW, "utf-8"); @@ -612,6 +632,13 @@ check_not_contains "$optional_plugin_block" 'pack_reviewed_npm_tarball' "optiona grep -Fq 'nemoclaw: ignore legacy OpenClaw update-check state' "$shared_state_permissions_patch" grep -Fq 'COPY scripts/patch-openclaw-shared-state-permissions.mts /usr/local/lib/nemoclaw/patch-openclaw-shared-state-permissions.mts' Dockerfile grep -Fq 'node --experimental-strip-types /usr/local/lib/nemoclaw/patch-openclaw-shared-state-permissions.mts \\' Dockerfile + mcp_reliability_patch=${JSON.stringify(MCP_RELIABILITY_PATCH)} + grep -Fq 'nemoclaw mcp transient startup recovery (#7958)' "$mcp_reliability_patch" + grep -Fq 'nemoClawIsTransientMcpStartFailure' "$mcp_reliability_patch" + grep -Fq 'nemoClawCatalogHasStartDiagnostics' "$mcp_reliability_patch" + grep -Fq 'COPY scripts/patch-openclaw-mcp-reliability.mts /usr/local/lib/nemoclaw/patch-openclaw-mcp-reliability.mts' Dockerfile + grep -Fq 'node --experimental-strip-types /usr/local/lib/nemoclaw/patch-openclaw-mcp-reliability.mts \\' Dockerfile + ! grep -Fq 'patch-openclaw-mcp-reliability.js' Dockerfile phase_count="$(grep -Ec -- '--phase (runtime-setup|agent-install|post-agent-install)' Dockerfile)" test "$phase_count" -eq 3 diff --git a/test/openclaw-final-image-layout.test.ts b/test/openclaw-final-image-layout.test.ts index 384c9a54863..1f2217c46b3 100644 --- a/test/openclaw-final-image-layout.test.ts +++ b/test/openclaw-final-image-layout.test.ts @@ -71,6 +71,7 @@ describe("OpenClaw final image layout", () => { "COPY scripts/patch-openclaw-tool-catalog.mts /usr/local/lib/nemoclaw/patch-openclaw-tool-catalog.mts", "COPY scripts/patch-openclaw-chat-send.mts /usr/local/lib/nemoclaw/patch-openclaw-chat-send.mts", "COPY scripts/patch-openclaw-mcp-npx.mts /usr/local/lib/nemoclaw/patch-openclaw-mcp-npx.mts", + "COPY scripts/patch-openclaw-mcp-reliability.mts /usr/local/lib/nemoclaw/patch-openclaw-mcp-reliability.mts", "COPY scripts/patch-openclaw-issue-4434-diagnostics.mts /usr/local/lib/nemoclaw/patch-openclaw-issue-4434-diagnostics.mts", "COPY scripts/patch-openclaw-device-self-approval.mts /usr/local/lib/nemoclaw/patch-openclaw-device-self-approval.mts", "COPY scripts/extract-semver.sh /usr/local/lib/nemoclaw/extract-semver", diff --git a/test/openclaw-mcp-reliability-patch.test.ts b/test/openclaw-mcp-reliability-patch.test.ts new file mode 100644 index 00000000000..b288e1757fa --- /dev/null +++ b/test/openclaw-mcp-reliability-patch.test.ts @@ -0,0 +1,561 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import vm from "node:vm"; + +import { beforeEach, describe, expect, it } from "vitest"; + +import { + INJECTED_START_RETRY_HELPER, + MARKER, + auditOpenClawMcpReliability, + patchBundleMcpRuntimeText, + patchOpenClawMcpReliability, +} from "../scripts/patch-openclaw-mcp-reliability.mts"; + +const PATCH_SCRIPT = path.join( + import.meta.dirname, + "..", + "scripts", + "patch-openclaw-mcp-reliability.mts", +); + +/** + * Mirrors the reviewed `openclaw@2026.7.1` + * `dist/agent-bundle-mcp-runtime-*.js` catalog shape, including its tab + * indentation, so patch anchors are exercised against the real preimage. + */ +function bundleMcpRuntimeFixture(): string { + return [ + 'import { a as logWarn } from "./logger.js";', + 'import { t as runTasksWithConcurrency } from "./run-with-concurrency.js";', + "function resolveMcpTransport(serverName, rawServer) {", + "\treturn null;", + "}", + "function createSessionMcpRuntime(params) {", + "\tlet catalog = null;", + "\tlet activeLeases = 0;", + "\tconst getCatalog = async () => {", + "\t\tconst inFlight = (async () => {", + "\t\t\ttry {", + "\t\t\t\tconst { results, firstError, hasError } = await runTasksWithConcurrency({", + "\t\t\t\t\ttasks: preparedEntries.map(({ serverName, rawServer, resolved, safeServerName }) => async () => {", + "\t\t\t\t\t\tfailIfDisposed();", + '\t\t\t\t\t\tlogWarn(`bundle-mcp: starting server "${serverName}".`);', + "\t\t\t\t\t\ttry {", + '\t\t\t\t\t\t\tconst client = new Client({ name: "openclaw-bundle-mcp" });', + "\t\t\t\t\t\t\treturn {", + "\t\t\t\t\t\t\t\tserverName,", + "\t\t\t\t\t\t\t\tserverEntry,", + "\t\t\t\t\t\t\t\ttoolEntries,", + "\t\t\t\t\t\t\t\tdiagnostics: []", + "\t\t\t\t\t\t\t};", + "\t\t\t\t\t\t} catch (error) {", + "\t\t\t\t\t\t\tconst diags = [{ serverName, message: redactErrorUrls(error) }];", + "\t\t\t\t\t\t\tif (!session.connected) await retireSessionIfCurrent(serverName, session);", + "\t\t\t\t\t\t\tfailIfDisposed();", + "\t\t\t\t\t\t\treturn {", + "\t\t\t\t\t\t\t\tserverName,", + "\t\t\t\t\t\t\t\tserverEntry: null,", + "\t\t\t\t\t\t\t\ttoolEntries: [],", + "\t\t\t\t\t\t\t\tdiagnostics: diags", + "\t\t\t\t\t\t\t};", + "\t\t\t\t\t\t} finally {", + "\t\t\t\t\t\t\tsession.catalogUseCount -= 1;", + "\t\t\t\t\t\t\tif (session.catalogUseCount === 0) session.sharedAcrossCatalogGenerations = false;", + "\t\t\t\t\t\t}", + "\t\t\t\t\t}),", + "\t\t\t\t\tlimit: BUNDLE_MCP_CATALOG_CONNECT_CONCURRENCY,", + '\t\t\t\t\terrorMode: "continue"', + "\t\t\t\t});", + "\t\t\t\tif (hasError) throw firstError;", + "\t\t\t} catch (error) {", + "\t\t\t\tthrow error;", + "\t\t\t}", + "\t\t})();", + "\t\treturn await inFlight;", + "\t};", + "\treturn {", + "\t\tget activeLeases() {", + "\t\t\treturn activeLeases;", + "\t\t},", + "\t\tacquireLease() {", + "\t\t\tactiveLeases += 1;", + "\t\t\tlet released = false;", + "\t\t\treturn () => {", + "\t\t\t\tif (released) return;", + "\t\t\t\treleased = true;", + "\t\t\t\tactiveLeases = Math.max(0, activeLeases - 1);", + "\t\t\t};", + "\t\t},", + "\t\tgetCatalog", + "\t};", + "}", + "", + ].join("\n"); +} + +function writeFixtureDist(version = "2026.7.1"): { dist: string; runtime: string; tmp: string } { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-reliability-")); + const dist = path.join(tmp, "dist"); + fs.mkdirSync(dist); + fs.writeFileSync(path.join(tmp, "package.json"), JSON.stringify({ version })); + const runtime = path.join(dist, "agent-bundle-mcp-runtime-Fixture.js"); + fs.writeFileSync(runtime, bundleMcpRuntimeFixture()); + fs.writeFileSync(path.join(dist, "unrelated.js"), "export const unrelated = 1;\n"); + return { dist, runtime, tmp }; +} + +interface InjectedHelper { + nemoClawIsTransientMcpStartFailure: (error: unknown) => boolean; + nemoClawWithMcpStartRetry: (params: Record) => () => Promise; + nemoClawCatalogHasStartDiagnostics: (catalog: unknown) => boolean; + nemoClawFinalizeMcpStartResult: (result: unknown, retried: boolean) => unknown; + NEMOCLAW_MCP_START_FAILURE: symbol; +} + +/** Evaluates the injected compatibility runtime exactly as the patch emits it. */ +function loadInjectedHelper(warnings: string[]): InjectedHelper { + const context = vm.createContext({ + logWarn: (message: string) => warnings.push(message), + setTimeout, + }); + return vm.runInContext( + [ + INJECTED_START_RETRY_HELPER, + "({", + "nemoClawIsTransientMcpStartFailure,", + "nemoClawWithMcpStartRetry,", + "nemoClawCatalogHasStartDiagnostics,", + "nemoClawFinalizeMcpStartResult,", + "NEMOCLAW_MCP_START_FAILURE", + "})", + ].join("\n"), + context, + ) as InjectedHelper; +} + +function startFailureResult(helper: InjectedHelper, error: unknown, reusedSession = false) { + return { + serverName: "remotedocs", + serverEntry: null, + toolEntries: [], + diagnostics: [{ serverName: "remotedocs", message: String(error) }], + [helper.NEMOCLAW_MCP_START_FAILURE]: { error, reusedSession }, + }; +} + +describe("OpenClaw MCP transient startup recovery patch (#7958)", () => { + const created: string[] = []; + + beforeEach(() => { + for (const dir of created.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); + }); + + it("rewrites the reviewed bundle-mcp catalog shape and stays idempotent", () => { + const { dist, runtime, tmp } = writeFixtureDist(); + created.push(tmp); + + const first = patchOpenClawMcpReliability(dist); + expect(first).toMatchObject({ status: "patched", file: runtime, version: "2026.7.1" }); + + const patched = fs.readFileSync(runtime, "utf-8"); + expect(patched).toContain(MARKER); + expect(patched).toContain("nemoClawWithMcpStartRetry({"); + expect(patched).toContain("attempt: async (resolved) => {"); + expect(patched).toContain("resolveTransport: () => resolveMcpTransport(serverName, rawServer)"); + expect(patched).toContain("[NEMOCLAW_MCP_START_FAILURE]: {"); + expect(patched).toContain( + "if (activeLeases === 0 && nemoClawCatalogHasStartDiagnostics(catalog)) catalog = null;", + ); + expect(patched).not.toContain( + "tasks: preparedEntries.map(({ serverName, rawServer, resolved, safeServerName }) => async () => {", + ); + + const syntax = spawnSync(process.execPath, ["--check", runtime], { encoding: "utf-8" }); + expect(syntax.stderr).toBe(""); + expect(syntax.status).toBe(0); + + expect(patchOpenClawMcpReliability(dist).status).toBe("already-patched"); + expect(fs.readFileSync(runtime, "utf-8")).toBe(patched); + expect(auditOpenClawMcpReliability(dist)).toMatchObject({ file: runtime }); + }); + + it("fails closed when the reviewed catalog shape is unrecognized", () => { + const { dist, runtime, tmp } = writeFixtureDist(); + created.push(tmp); + fs.writeFileSync( + runtime, + fs + .readFileSync(runtime, "utf-8") + .replace("\t\t\t\t\t\t\t\tdiagnostics: diags", "\t\t\t\t\t\t\t\tdiagnostics: serverDiags"), + ); + + expect(() => patchOpenClawMcpReliability(dist)).toThrow( + /expected exactly one MCP startup recovery target, found 0/, + ); + }); + + it("fails closed when a marked runtime still carries an unpatched target", () => { + const { dist, runtime, tmp } = writeFixtureDist(); + created.push(tmp); + fs.writeFileSync(runtime, `${MARKER}\n${fs.readFileSync(runtime, "utf-8")}`); + + expect(() => patchOpenClawMcpReliability(dist)).toThrow(/patch is partial/); + }); + + it("fails closed when no single bundle-mcp runtime can be identified", () => { + const { dist, runtime, tmp } = writeFixtureDist(); + created.push(tmp); + fs.copyFileSync(runtime, path.join(dist, "agent-bundle-mcp-runtime-Duplicate.js")); + + expect(() => patchOpenClawMcpReliability(dist)).toThrow( + /Expected exactly one OpenClaw bundle-mcp runtime .*found 2/, + ); + }); + + it("rejects an audit of an unpatched reviewed dist", () => { + const { dist, tmp } = writeFixtureDist(); + created.push(tmp); + + expect(() => auditOpenClawMcpReliability(dist)).toThrow(/patch is not applied/); + }); + + it("reports the reviewed OpenClaw version through the CLI entrypoint", () => { + const { dist, tmp } = writeFixtureDist(); + created.push(tmp); + + const applied = spawnSync( + process.execPath, + ["--experimental-strip-types", PATCH_SCRIPT, dist], + { + encoding: "utf-8", + }, + ); + expect(applied.status).toBe(0); + expect(applied.stdout).toContain("MCP startup recovery patched"); + expect(applied.stdout).toContain("openclaw 2026.7.1"); + + const audited = spawnSync( + process.execPath, + ["--experimental-strip-types", PATCH_SCRIPT, "--audit", dist], + { encoding: "utf-8" }, + ); + expect(audited.status).toBe(0); + expect(audited.stdout).toContain("MCP startup recovery audit ok"); + }); + + it("classifies only transient transport startup failures as retryable", () => { + const helper = loadInjectedHelper([]); + const transient: Array<[string, unknown]> = [ + [ + "upstream reset before headers", + Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("other side closed"), { code: "UND_ERR_SOCKET" }), + }), + ], + [ + "socket reset", + Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" }), + }), + ], + [ + "MCP request timeout", + Object.assign(new Error("MCP error -32001: Request timed out"), { + code: -32001, + }), + ], + ["OpenClaw connect timeout", new Error("MCP server connection timed out after 30000ms")], + [ + "headers timeout", + Object.assign(new Error("Headers Timeout Error"), { + code: "UND_ERR_HEADERS_TIMEOUT", + }), + ], + ]; + for (const [label, error] of transient) { + expect(helper.nemoClawIsTransientMcpStartFailure(error), label).toBe(true); + } + + const blocked: Array<[string, unknown]> = [ + ["unauthorized", new Error("Error POSTing to endpoint (HTTP 401): Unauthorized")], + ["forbidden", new Error("Streamable HTTP error: HTTP 403 Forbidden")], + [ + // An OpenShell L4 policy denial reaches the MCP client as a refused + // connection, so a refused destination must never be retried (#7958). + "sandbox network policy denial", + Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:9958"), { + code: "ECONNREFUSED", + }), + }), + ], + [ + "unresolvable host", + Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("getaddrinfo EAI_AGAIN mcp.example.com"), { + code: "EAI_AGAIN", + }), + }), + ], + ["oauth token rejection", new Error('token exchange failed: {"error":"invalid_grant"}')], + [ + "expired certificate", + Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("certificate has expired"), { code: "CERT_HAS_EXPIRED" }), + }), + ], + [ + "self-signed chain", + Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("self-signed certificate in certificate chain"), { + code: "SELF_SIGNED_CERT_IN_CHAIN", + }), + }), + ], + ["policy denial", new Error("request blocked by sandbox egress policy")], + ["SSRF guard", new Error("SSRF guard rejected destination")], + [ + "invalid configuration", + Object.assign(new Error("Invalid URL"), { code: "ERR_INVALID_URL" }), + ], + ["unknown failure", new Error("something else went wrong")], + ["missing error", undefined], + ]; + for (const [label, error] of blocked) { + expect(helper.nemoClawIsTransientMcpStartFailure(error), label).toBe(false); + } + }); + + it("retries a transient streamable-http startup once and returns the recovered result", async () => { + const warnings: string[] = []; + const helper = loadInjectedHelper(warnings); + const seen: Array> = []; + const success = { + serverName: "remotedocs", + serverEntry: {}, + toolEntries: [{}], + diagnostics: [], + }; + + const task = helper.nemoClawWithMcpStartRetry({ + serverName: "remotedocs", + initialResolved: { transportType: "streamable-http", connectionTimeoutMs: 30_000 }, + resolveTransport: () => ({ transportType: "streamable-http", connectionTimeoutMs: 30_000 }), + attempt: async (resolved: Record) => { + seen.push(resolved); + if (seen.length === 1) { + return startFailureResult( + helper, + Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("other side closed"), { code: "UND_ERR_SOCKET" }), + }), + ); + } + return success; + }, + }); + + await expect(task()).resolves.toEqual(success); + expect(seen).toHaveLength(2); + expect(seen[1].connectionTimeoutMs).toBe(10_000); + expect(warnings).toEqual([ + 'bundle-mcp: retrying transient startup failure for server "remotedocs" once with a fresh transport.', + ]); + }); + + it("marks an exhausted retry as a temporary transport failure without blaming credentials", async () => { + const helper = loadInjectedHelper([]); + const error = Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("other side closed"), { code: "UND_ERR_SOCKET" }), + }); + + const task = helper.nemoClawWithMcpStartRetry({ + serverName: "remotedocs", + initialResolved: { transportType: "streamable-http", connectionTimeoutMs: 5_000 }, + resolveTransport: () => ({ transportType: "streamable-http", connectionTimeoutMs: 5_000 }), + attempt: async () => startFailureResult(helper, error), + }); + + const result = (await task()) as { diagnostics: Array<{ message: string }> }; + expect(result.diagnostics[0].message).toContain("temporary MCP transport failure"); + expect(result.diagnostics[0].message).toContain( + "Credentials and configuration were not rejected", + ); + expect(Object.getOwnPropertySymbols(result)).toEqual([]); + }); + + it("never retries auth, non-streamable transports, or already-connected refresh failures", async () => { + const helper = loadInjectedHelper([]); + const cases = [ + { + label: "auth failure", + initialResolved: { transportType: "streamable-http", connectionTimeoutMs: 5_000 }, + error: new Error("Error POSTing to endpoint (HTTP 401): Unauthorized"), + reusedSession: false, + }, + { + label: "stdio transport", + initialResolved: { transportType: "stdio", connectionTimeoutMs: 5_000 }, + error: new TypeError("fetch failed"), + reusedSession: false, + }, + { + label: "sse transport", + initialResolved: { transportType: "sse", connectionTimeoutMs: 5_000 }, + error: new TypeError("fetch failed"), + reusedSession: false, + }, + { + label: "connected refresh failure", + initialResolved: { transportType: "streamable-http", connectionTimeoutMs: 5_000 }, + error: new TypeError("fetch failed"), + reusedSession: true, + }, + ]; + + for (const testCase of cases) { + let attempts = 0; + let resolvedTransports = 0; + const task = helper.nemoClawWithMcpStartRetry({ + serverName: "remotedocs", + initialResolved: testCase.initialResolved, + resolveTransport: () => { + resolvedTransports += 1; + return testCase.initialResolved; + }, + attempt: async () => { + attempts += 1; + return startFailureResult(helper, testCase.error, testCase.reusedSession); + }, + }); + + const result = (await task()) as { diagnostics: Array<{ message: string }> }; + expect(attempts, testCase.label).toBe(1); + expect(resolvedTransports, testCase.label).toBe(0); + expect(result.diagnostics[0].message, testCase.label).not.toContain( + "temporary MCP transport failure", + ); + } + }); + + it("treats any catalog carrying a server diagnostic as unfit for the stable session catalog", () => { + const helper = loadInjectedHelper([]); + const exhausted = helper.nemoClawFinalizeMcpStartResult( + startFailureResult( + helper, + Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("other side closed"), { code: "UND_ERR_SOCKET" }), + }), + ), + true, + ) as { diagnostics: Array<{ message: string }> }; + + // A catalog in which every server started omits the key entirely, so a + // healthy catalog is still reused. + expect(helper.nemoClawCatalogHasStartDiagnostics(null)).toBe(false); + expect(helper.nemoClawCatalogHasStartDiagnostics({ servers: {}, tools: [] })).toBe(false); + expect(helper.nemoClawCatalogHasStartDiagnostics({ tools: [], diagnostics: [] })).toBe(false); + expect( + helper.nemoClawCatalogHasStartDiagnostics({ + tools: [], + diagnostics: exhausted.diagnostics, + }), + ).toBe(true); + + // A credential, TLS, policy, or configuration rejection keeps its own + // diagnostic, but its catalog is still degraded, so it is not retained. + const rejected = helper.nemoClawFinalizeMcpStartResult( + startFailureResult(helper, new Error("Error POSTing to endpoint (HTTP 401): Unauthorized")), + true, + ) as { diagnostics: Array<{ message: string }> }; + expect(rejected.diagnostics[0].message).not.toContain("temporary MCP transport failure"); + expect( + helper.nemoClawCatalogHasStartDiagnostics({ + tools: [], + diagnostics: rejected.diagnostics, + }), + ).toBe(true); + }); + + it("keeps the real retry failure when a transient startup is followed by a rejection", async () => { + const helper = loadInjectedHelper([]); + const attempts: unknown[] = []; + + const task = helper.nemoClawWithMcpStartRetry({ + serverName: "remotedocs", + initialResolved: { transportType: "streamable-http", connectionTimeoutMs: 5_000 }, + resolveTransport: () => ({ transportType: "streamable-http", connectionTimeoutMs: 5_000 }), + attempt: async () => { + attempts.push(1); + return attempts.length === 1 + ? startFailureResult( + helper, + Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("other side closed"), { code: "UND_ERR_SOCKET" }), + }), + ) + : startFailureResult( + helper, + new Error("Error POSTing to endpoint (HTTP 401): Unauthorized"), + ); + }, + }); + + const result = (await task()) as { diagnostics: Array<{ message: string }> }; + expect(attempts).toHaveLength(2); + expect(result.diagnostics[0].message).toContain("HTTP 401"); + expect(result.diagnostics[0].message).not.toContain("temporary MCP transport failure"); + }); + + it("drops a diagnostics-carrying catalog at the next agent run boundary", async () => { + const { dist, runtime, tmp } = writeFixtureDist(); + created.push(tmp); + patchOpenClawMcpReliability(dist); + + const patched = fs.readFileSync(runtime, "utf-8"); + const leaseBody = patched.slice( + patched.indexOf("\t\tacquireLease() {"), + patched.indexOf("\t\tgetCatalog"), + ); + expect(leaseBody).toContain( + "if (activeLeases === 0 && nemoClawCatalogHasStartDiagnostics(catalog)) catalog = null;", + ); + + // The invalidation must be scoped to an idle runtime so an in-flight agent + // run keeps its catalog and cannot trigger a per-tool-call reconnect sweep. + const helper = loadInjectedHelper([]); + const exhausted = helper.nemoClawFinalizeMcpStartResult( + startFailureResult( + helper, + Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("other side closed"), { code: "UND_ERR_SOCKET" }), + }), + ), + true, + ) as { diagnostics: Array<{ message: string }> }; + const degraded = { tools: [], diagnostics: exhausted.diagnostics }; + let catalog: unknown = degraded; + let activeLeases = 1; + const acquireLease = () => { + if (activeLeases === 0 && helper.nemoClawCatalogHasStartDiagnostics(catalog)) catalog = null; + activeLeases += 1; + }; + acquireLease(); + expect(catalog).toBe(degraded); + activeLeases = 0; + acquireLease(); + expect(catalog).toBeNull(); + }); + + it("keeps the compiled helper free of unpatched-target text", () => { + expect(INJECTED_START_RETRY_HELPER).toContain(MARKER); + expect(INJECTED_START_RETRY_HELPER).not.toContain("preparedEntries.map"); + expect(patchBundleMcpRuntimeText(bundleMcpRuntimeFixture(), "fixture.js").patched).toBe(true); + }); +}); diff --git a/test/openclaw-real-patched-dist-harness.test.ts b/test/openclaw-real-patched-dist-harness.test.ts index 9cb9578ecb9..2c49669a67f 100644 --- a/test/openclaw-real-patched-dist-harness.test.ts +++ b/test/openclaw-real-patched-dist-harness.test.ts @@ -10,6 +10,7 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; import { runRealOpenClawDeviceSelfApprovalProof } from "./helpers/openclaw-real-device-self-approval-proof"; +import { runRealOpenClawMcpStartRetryProof } from "./helpers/openclaw-real-mcp-start-retry-proof"; const REPO_ROOT = path.join(import.meta.dirname, ".."); const DOCKERFILE = path.join(REPO_ROOT, "Dockerfile"); @@ -24,6 +25,11 @@ const PATCH_OPENCLAW_SHARED_STATE_PERMISSIONS = path.join( "scripts", "patch-openclaw-shared-state-permissions.mts", ); +const PATCH_OPENCLAW_MCP_RELIABILITY = path.join( + REPO_ROOT, + "scripts", + "patch-openclaw-mcp-reliability.mts", +); const OPENCLAW_VERSION_EXTRACTOR = path.join(REPO_ROOT, "scripts", "extract-semver.sh"); const REAL_OPENCLAW_NODE_ENV = "NEMOCLAW_REAL_OPENCLAW_NODE"; // Focused patch scripts also scan the full generated dist. APFS cold-cache @@ -695,9 +701,16 @@ describe.skipIf(process.env.NEMOCLAW_REAL_OPENCLAW_DIST_HARNESS !== "1")( requireSpawnSuccess(syntax, `validate reviewed OpenClaw dist syntax: ${target}`); } - // This proof installs the reviewed shrinkwrapped runtime dependencies - // with lifecycle scripts disabled. Keep it after every shape-only dist - // scan so dependency materialization cannot perturb their timing. + // These proofs install the reviewed shrinkwrapped runtime dependencies + // with lifecycle scripts disabled. Keep them after every shape-only + // dist scan so dependency materialization cannot perturb their timing. + runRealOpenClawMcpStartRetryProof({ + dist, + nodeExecutable: nodeRuntime.executable, + patchScript: PATCH_OPENCLAW_MCP_RELIABILITY, + timeoutMs: PATCH_COMMAND_TIMEOUT_MS, + }); + await runRealOpenClawDeviceSelfApprovalProof({ dist, nodeExecutable: nodeRuntime.executable, diff --git a/test/sandbox-build-context.test.ts b/test/sandbox-build-context.test.ts index ada24769f72..b213b9a2330 100644 --- a/test/sandbox-build-context.test.ts +++ b/test/sandbox-build-context.test.ts @@ -131,6 +131,7 @@ describe("sandbox build context staging", () => { writeFixture(path.join("scripts", "patch-openclaw-tool-catalog.mts")); writeFixture(path.join("scripts", "patch-openclaw-chat-send.mts")); writeFixture(path.join("scripts", "patch-openclaw-mcp-npx.mts")); + writeFixture(path.join("scripts", "patch-openclaw-mcp-reliability.mts")); writeFixture(path.join("scripts", "patch-openclaw-issue-4434-diagnostics.mts")); writeFixture(path.join("scripts", "patch-openclaw-device-self-approval.mts")); writeFixture(path.join("scripts", "extract-semver.sh")); @@ -557,6 +558,9 @@ describe("sandbox build context staging", () => { expect(fs.existsSync(path.join(buildCtx, "scripts", "patch-openclaw-mcp-npx.mts"))).toBe( true, ); + expect( + fs.existsSync(path.join(buildCtx, "scripts", "patch-openclaw-mcp-reliability.mts")), + ).toBe(true); expect( fs.existsSync(path.join(buildCtx, "scripts", "patch-openclaw-issue-4434-diagnostics.mts")), ).toBe(true); From d7c254ccd00140e07babbd9e3578d43c6bd503b8 Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Fri, 31 Jul 2026 07:01:07 +0000 Subject: [PATCH 2/4] test(openclaw): keep MCP reliability test bodies linear (#7958) The codebase-growth-guardrails check requires changed test files not to add if statements. Replace the two conditionals with linear equivalents: script the per-attempt retry results in an array, and compute the run-boundary catalog drop as a named boolean. Signed-off-by: Yimo Jiang Co-Authored-By: Claude Opus 5 (1M context) --- test/openclaw-mcp-reliability-patch.test.ts | 25 ++++++++++++--------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/test/openclaw-mcp-reliability-patch.test.ts b/test/openclaw-mcp-reliability-patch.test.ts index b288e1757fa..aa82d14f5ef 100644 --- a/test/openclaw-mcp-reliability-patch.test.ts +++ b/test/openclaw-mcp-reliability-patch.test.ts @@ -343,21 +343,25 @@ describe("OpenClaw MCP transient startup recovery patch (#7958)", () => { diagnostics: [], }; + // Scripted per-attempt results: the first startup resets in flight, the + // retry succeeds. + const scriptedResults = [ + startFailureResult( + helper, + Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("other side closed"), { code: "UND_ERR_SOCKET" }), + }), + ), + success, + ]; + const task = helper.nemoClawWithMcpStartRetry({ serverName: "remotedocs", initialResolved: { transportType: "streamable-http", connectionTimeoutMs: 30_000 }, resolveTransport: () => ({ transportType: "streamable-http", connectionTimeoutMs: 30_000 }), attempt: async (resolved: Record) => { seen.push(resolved); - if (seen.length === 1) { - return startFailureResult( - helper, - Object.assign(new TypeError("fetch failed"), { - cause: Object.assign(new Error("other side closed"), { code: "UND_ERR_SOCKET" }), - }), - ); - } - return success; + return scriptedResults[seen.length - 1]; }, }); @@ -543,7 +547,8 @@ describe("OpenClaw MCP transient startup recovery patch (#7958)", () => { let catalog: unknown = degraded; let activeLeases = 1; const acquireLease = () => { - if (activeLeases === 0 && helper.nemoClawCatalogHasStartDiagnostics(catalog)) catalog = null; + const dropsCatalog = activeLeases === 0 && helper.nemoClawCatalogHasStartDiagnostics(catalog); + catalog = dropsCatalog ? null : catalog; activeLeases += 1; }; acquireLease(); From b7ac63dc97b1e2244dea611c82bdc61d992052ef Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Fri, 31 Jul 2026 07:29:15 +0000 Subject: [PATCH 3/4] test(openclaw): pin the preserved MCP credential-rejection diagnostic (#7958) Address CodeRabbit review on #7984. The controlled-proof check for the persistent 401 scenario used optional chaining, so it passed silently when the diagnostic list was empty. Assert that exactly one diagnostic survives and that it carries the server's rejection reason. The reviewed runtime surfaces the OAuth payload rather than the status line, so the preserved text is `Error POSTing to endpoint: {"error":"invalid_token"}`; that token is also what the patch's blocked-text pattern keys on, so the assertion pins both the preserved attribution and the reason the retry was refused. Also mirror the reviewed package's "type": "module" in the fixture dist, and reformat the dependency-review section to one sentence per line. Signed-off-by: Yimo Jiang Co-Authored-By: Claude Opus 5 (1M context) --- .../openclaw-2026.7.1-dependency-review.md | 102 ++++++------------ .../openclaw-real-mcp-start-retry-proof.ts | 17 ++- test/openclaw-dependency-review.test.ts | 2 +- test/openclaw-mcp-reliability-patch.test.ts | 4 +- 4 files changed, 53 insertions(+), 72 deletions(-) diff --git a/docs/security/openclaw-2026.7.1-dependency-review.md b/docs/security/openclaw-2026.7.1-dependency-review.md index 146e74399e7..4c4388d7d52 100644 --- a/docs/security/openclaw-2026.7.1-dependency-review.md +++ b/docs/security/openclaw-2026.7.1-dependency-review.md @@ -255,78 +255,42 @@ and shared token so the bounded approval flow uses that device credential. ## Transient Remote MCP Startup Recovery -`scripts/patch-openclaw-mcp-reliability.mts` is a version-scoped, fail-closed -compatibility patch for issue #7958. In `2026.7.1`, the compiled bundle-mcp -session runtime turns one failed remote server startup into an empty tool set -plus catalog diagnostics, caches that degraded catalog for the whole session, -and never retries. A single transient Streamable HTTP reset or MCP request -timeout therefore removes an expected integration until the user starts a new -session, and the agent can report the integration or its credentials as -unavailable. - -The patch identifies its target by the `"openclaw-bundle-mcp"` client identity -and requires each rewritten anchor to appear exactly once. An unrecognized -compiled shape fails the image build instead of silently skipping, which is how -the removal criterion is enforced. `--audit` re-verifies the applied state. +`scripts/patch-openclaw-mcp-reliability.mts` is a version-scoped, fail-closed compatibility patch for issue #7958. +In `2026.7.1`, the compiled bundle-mcp session runtime turns one failed remote server startup into an empty tool set plus catalog diagnostics, caches that degraded catalog for the whole session, and never retries. +A single transient Streamable HTTP reset or MCP request timeout therefore removes an expected integration until the user starts a new session, and the agent can report the integration or its credentials as unavailable. + +The patch identifies its target by the `"openclaw-bundle-mcp"` client identity and requires each rewritten anchor to appear exactly once. +An unrecognized compiled shape fails the image build instead of silently skipping, which is how the removal criterion is enforced. +`--audit` re-verifies the applied state. Reviewed behavior: -- one retry, and only one, for a server *startup* failure on a - `streamable-http` transport. A refresh failure on an already-connected - session is not retried; -- the retry uses a fresh transport from the upstream `resolveMcpTransport` - factory after 120-300 ms of jitter, and caps its connection timeout at - 10000 ms so a dead server cannot double an agent run's worst-case latency; -- classification is a fail-closed allow-list over the whole `cause` chain: - MCP request timeout (`-32001`), the OpenClaw connect-timeout message, undici - and POSIX in-flight transport codes, and reset/disconnect-before-headers - text. A blocked-code and blocked-text pass runs first, so authentication, - authorization, OAuth token rejection, TLS and certificate validation, SSRF - and policy denial, and invalid configuration are never retried. A refused, - unreachable, or unresolvable destination is deliberately excluded from the - allow-list: an OpenShell L4 policy denial reaches the MCP client as a refused - connection, and a refused destination is deterministic rather than a - transient in-flight fault; -- an exhausted retry keeps the upstream diagnostic and appends a - temporary-transport statement that explicitly clears credentials and - configuration, so the agent does not report missing credentials for a - transport failure. That statement is added only when the *surviving* failure - is itself transient. A retry that reaches the server and is then rejected - with HTTP 401, a TLS error, or a policy denial keeps its own diagnostic; -- a catalog carrying a server diagnostic is not retained as the session's stable - catalog. It is dropped at the next agent run boundary, in `acquireLease()` and - only while the runtime is idle. Upstream fills `catalog.diagnostics` only from - a per-server start or refresh failure and omits the key when every server - started, so a non-empty array is exactly the degraded case and a healthy - catalog is still reused. A credential, TLS, policy, or configuration rejection - keeps its own diagnostic and is still never retried inside a run, but its - catalog is not sticky either, so a repaired credential is picked up on the - next agent run instead of requiring a new session. Scoping the drop to a run - boundary rather than to every `getCatalog()` call is deliberate: - `getCatalog()` is also the pre-flight for every `callTool`, `listResources`, - `readResource`, `listPrompts`, and `getPrompt`, so dropping it on every call - would rebuild the catalog per tool call and turn one unreachable optional - server into a per-call reconnect cost. Optional MCP servers stay best-effort; -- no credential, SSRF, OAuth, or network-policy behavior changes. - -A first version of this patch was rejected during review on two counts, both -now covered by tests: it retried an OpenShell L4 policy denial because undici -reports it as `TypeError: fetch failed`, and it reported a retry that ended in -HTTP 401 as a temporary transport failure that had not rejected credentials. - -Coverage: `test/openclaw-mcp-reliability-patch.test.ts` pins the compiled -preimage, patch idempotence, fail-closed rejection of an unrecognized shape, -the classification table, and the retry and diagnostic behavior of the injected -runtime. `test/helpers/openclaw-real-mcp-start-retry-proof.ts` runs inside the -`NEMOCLAW_REAL_OPENCLAW_DIST_HARNESS=1` harness and drives the real patched -runtime against a controlled Streamable HTTP MCP server for three scenarios: -first exchange resets then succeeds, every exchange resets, and a persistent -401. The proof asserts that the rejected-credential scenario is contacted once -per run, with no retry inside a run. - -Removal criteria: drop this patch when the reviewed OpenClaw release provides -equivalent bounded startup retry, negative-catalog invalidation, and -temporary-transport failure attribution. +- One retry, and only one, for a server *startup* failure on a `streamable-http` transport. + A refresh failure on an already-connected session is not retried. +- The retry uses a fresh transport from the upstream `resolveMcpTransport` factory after 120-300 ms of jitter, and caps its connection timeout at 10000 ms so a dead server cannot double an agent run's worst-case latency. +- Classification is a fail-closed allow-list over the whole `cause` chain: MCP request timeout (`-32001`), the OpenClaw connect-timeout message, undici and POSIX in-flight transport codes, and reset/disconnect-before-headers text. + A blocked-code and blocked-text pass runs first, so authentication, authorization, OAuth token rejection, TLS and certificate validation, SSRF and policy denial, and invalid configuration are never retried. + A refused, unreachable, or unresolvable destination is deliberately excluded from the allow-list: an OpenShell L4 policy denial reaches the MCP client as a refused connection, and a refused destination is deterministic rather than a transient in-flight fault. +- An exhausted retry keeps the upstream diagnostic and appends a temporary-transport statement that explicitly clears credentials and configuration, so the agent does not report missing credentials for a transport failure. + That statement is added only when the *surviving* failure is itself transient. + A retry that reaches the server and is then rejected with HTTP 401, a TLS error, or a policy denial keeps its own diagnostic. +- A catalog carrying a server diagnostic is not retained as the session's stable catalog. + It is dropped at the next agent run boundary, in `acquireLease()` and only while the runtime is idle. + Upstream fills `catalog.diagnostics` only from a per-server start or refresh failure and omits the key when every server started, so a non-empty array is the degraded case and a healthy catalog is still reused. + A credential, TLS, policy, or configuration rejection keeps its own diagnostic and is still never retried inside a run, but its catalog is not sticky either, so a repaired credential is picked up on the next agent run instead of requiring a new session. + Scoping the drop to a run boundary rather than to every `getCatalog()` call is deliberate. + `getCatalog()` is also the pre-flight for every `callTool`, `listResources`, `readResource`, `listPrompts`, and `getPrompt`, so dropping it on every call would rebuild the catalog per tool call and turn one unreachable optional server into a per-call reconnect cost. + Optional MCP servers stay best-effort. +- No credential, SSRF, OAuth, or network-policy behavior changes. + +A first version of this patch was rejected during review on two counts, both now covered by tests. +It retried an OpenShell L4 policy denial because undici reports it as `TypeError: fetch failed`, and it reported a retry that ended in HTTP 401 as a temporary transport failure that had not rejected credentials. + +Coverage: `test/openclaw-mcp-reliability-patch.test.ts` pins the compiled preimage, patch idempotence, fail-closed rejection of an unrecognized shape, the classification table, and the retry and diagnostic behavior of the injected runtime. +`test/helpers/openclaw-real-mcp-start-retry-proof.ts` runs inside the `NEMOCLAW_REAL_OPENCLAW_DIST_HARNESS=1` harness and drives the real patched runtime against a controlled Streamable HTTP MCP server for three scenarios: first exchange resets then succeeds, every exchange resets, and a persistent 401. +The proof asserts that the rejected-credential scenario is contacted once per run, with no retry inside a run. + +Removal criteria: drop this patch when the reviewed OpenClaw release provides equivalent bounded startup retry, negative-catalog invalidation, and temporary-transport failure attribution. ## Gateway Startup Migration Compatibility diff --git a/test/helpers/openclaw-real-mcp-start-retry-proof.ts b/test/helpers/openclaw-real-mcp-start-retry-proof.ts index 216c2b9427a..f7e9ce65c8e 100644 --- a/test/helpers/openclaw-real-mcp-start-retry-proof.ts +++ b/test/helpers/openclaw-real-mcp-start-retry-proof.ts @@ -142,9 +142,24 @@ export function runRealOpenClawMcpStartRetryProof(options: ProofOptions): void { "1", "one un-retried attempt per run after an authorization 401", ); - if (unauthorized.run1Diagnostics[0]?.includes("temporary MCP transport failure")) { + requireEqual( + String(unauthorized.run1Diagnostics.length), + "1", + "authorization diagnostic count on run 1", + ); + if (unauthorized.run1Diagnostics[0].includes("temporary MCP transport failure")) { throw new Error("authorization failure was reported as a temporary transport failure"); } + // OpenClaw surfaces the server's OAuth rejection payload rather than the + // status line, so the preserved diagnostic reads + // `Error POSTing to endpoint: {"error":"invalid_token"}`. That `invalid_token` + // token is also what the patch's blocked-text pattern keys on, so asserting it + // pins both the preserved attribution and the reason the retry was refused. + if (!/invalid_token|401|unauthoriz|credential/i.test(unauthorized.run1Diagnostics[0])) { + throw new Error( + `authorization diagnostic does not attribute the failure to the credential rejection: ${unauthorized.run1Diagnostics[0]}`, + ); + } } const MCP_START_RETRY_PROOF_SCRIPT = `// Generated by test/helpers/openclaw-real-mcp-start-retry-proof.ts diff --git a/test/openclaw-dependency-review.test.ts b/test/openclaw-dependency-review.test.ts index 2fdee81b243..5a2e1570726 100644 --- a/test/openclaw-dependency-review.test.ts +++ b/test/openclaw-dependency-review.test.ts @@ -164,7 +164,7 @@ describe("OpenClaw 2026.6.10 dependency review contract", () => { expect(review).toContain( 'identifies its target by the `"openclaw-bundle-mcp"` client identity', ); - expect(review).toContain("one retry, and only one, for a server *startup* failure"); + expect(review).toContain("One retry, and only one, for a server *startup* failure"); expect(review).toContain("are never retried"); expect(review).toContain("dropped at the next agent run boundary"); expect(review).toContain("test/openclaw-mcp-reliability-patch.test.ts"); diff --git a/test/openclaw-mcp-reliability-patch.test.ts b/test/openclaw-mcp-reliability-patch.test.ts index aa82d14f5ef..75ba187be4d 100644 --- a/test/openclaw-mcp-reliability-patch.test.ts +++ b/test/openclaw-mcp-reliability-patch.test.ts @@ -103,7 +103,9 @@ function writeFixtureDist(version = "2026.7.1"): { dist: string; runtime: string const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-reliability-")); const dist = path.join(tmp, "dist"); fs.mkdirSync(dist); - fs.writeFileSync(path.join(tmp, "package.json"), JSON.stringify({ version })); + // The reviewed openclaw@2026.7.1 package declares "type": "module"; mirror it + // so the fixture carries the same module classification as the real package. + fs.writeFileSync(path.join(tmp, "package.json"), JSON.stringify({ type: "module", version })); const runtime = path.join(dist, "agent-bundle-mcp-runtime-Fixture.js"); fs.writeFileSync(runtime, bundleMcpRuntimeFixture()); fs.writeFileSync(path.join(dist, "unrelated.js"), "export const unrelated = 1;\n"); From a21544dc03a4b5e868c006e2f5e5c6d0ba6641ee Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sun, 2 Aug 2026 07:01:45 -0700 Subject: [PATCH 4/4] fix(openclaw): harden MCP retry patch audit Signed-off-by: Carlos Villela --- Dockerfile | 2 +- docs/reference/troubleshoot-mcp-servers.mdx | 11 +-- .../openclaw-2026.7.1-dependency-review.md | 21 +++--- scripts/patch-openclaw-mcp-reliability.mts | 29 +++++--- .../openclaw-real-mcp-start-retry-proof.ts | 4 +- test/openclaw-dependency-review.test.ts | 16 ++++- test/openclaw-mcp-reliability-patch.test.ts | 71 ++++++++++++++++++- 7 files changed, 123 insertions(+), 31 deletions(-) diff --git a/Dockerfile b/Dockerfile index df472fe8070..817afb36daa 100644 --- a/Dockerfile +++ b/Dockerfile @@ -931,7 +931,7 @@ RUN node --experimental-strip-types /usr/local/lib/nemoclaw/patch-openclaw-mcp-n # and drops a diagnostics-carrying catalog at the next agent run. Authentication, # authorization, TLS, policy, and configuration failures are never retried. # -# Removal criteria: drop when upstream OpenClaw provides bounded startup retry, +# Removal criterion: drop when upstream OpenClaw provides bounded startup retry, # negative-catalog invalidation, and temporary-transport failure attribution. # hadolint ignore=DL3059 RUN node --experimental-strip-types /usr/local/lib/nemoclaw/patch-openclaw-mcp-reliability.mts \ diff --git a/docs/reference/troubleshoot-mcp-servers.mdx b/docs/reference/troubleshoot-mcp-servers.mdx index 9f55f055489..ec7bd338b2a 100644 --- a/docs/reference/troubleshoot-mcp-servers.mdx +++ b/docs/reference/troubleshoot-mcp-servers.mdx @@ -68,13 +68,14 @@ If a Hermes sandbox is alive but its gateway is not running after a supervisor o Recovery re-establishes the managed service lifecycle, API forwarding, and the exit-75 reload loop used for transactional MCP configuration changes. + + ## Remote MCP Tools Are Missing for One Agent Turn - If a remote Streamable HTTP MCP server times out or resets while its tools are being loaded, NemoClaw retries that startup once with a fresh connection before the agent turn continues. A successful retry loads the expected tools in the same turn, so no new session is needed. -If the retry also fails, the sandbox log records a temporary MCP transport failure and states that credentials and configuration were not rejected. +If the retry also ends in a classified transient transport failure, the sandbox log records a temporary MCP transport failure and states that credentials and configuration were not rejected. Read that line before rotating a credential: ```bash @@ -84,9 +85,9 @@ $$nemoclaw logs --tail 100 NemoClaw does not retry an authentication, authorization, TLS-validation, network-policy, or invalid-configuration failure inside a turn, because repeating the same request cannot succeed. A refused or unreachable endpoint is also not retried inside a turn; check the endpoint and its egress policy instead. -A turn in which any server failed to start does not become the session's cached tool catalog. -NemoClaw contacts that server again on the next agent turn, so a brief upstream outage clears on its own and a repaired credential or policy takes effect without a new session. -A turn in which every server started is cached and reused as usual. +A catalog that contains a server diagnostic is not cached for the session. +NemoClaw rebuilds the catalog on the next agent turn and contacts the affected server again, so a brief upstream outage clears on its own and a repaired credential or policy takes effect without a new session. +A catalog without server diagnostics is cached and reused as usual. ## Policy or Provider Ownership Drifted diff --git a/docs/security/openclaw-2026.7.1-dependency-review.md b/docs/security/openclaw-2026.7.1-dependency-review.md index 42c5ad91d0b..80c3cd0b4a5 100644 --- a/docs/security/openclaw-2026.7.1-dependency-review.md +++ b/docs/security/openclaw-2026.7.1-dependency-review.md @@ -288,32 +288,35 @@ persisted. ## Transient Remote MCP Startup Recovery `scripts/patch-openclaw-mcp-reliability.mts` is a version-scoped, fail-closed compatibility patch for issue #7958. -In `2026.7.1`, the compiled bundle-mcp session runtime turns one failed remote server startup into an empty tool set plus catalog diagnostics, caches that degraded catalog for the whole session, and never retries. +In `2026.7.1`, the compiled `bundle-mcp` session runtime turns one failed remote server startup into an empty tool set plus catalog diagnostics, caches that degraded catalog for the whole session, and never retries. A single transient Streamable HTTP reset or MCP request timeout therefore removes an expected integration until the user starts a new session, and the agent can report the integration or its credentials as unavailable. The patch identifies its target by the `"openclaw-bundle-mcp"` client identity and requires each rewritten anchor to appear exactly once. -An unrecognized compiled shape fails the image build instead of silently skipping, which is how the removal criterion is enforced. +An unrecognized compiled shape fails the image build instead of silently skipping and forces review before the patch can be updated or removed. `--audit` re-verifies the applied state. Reviewed behavior: - One retry, and only one, for a server *startup* failure on a `streamable-http` transport. A refresh failure on an already-connected session is not retried. -- The retry uses a fresh transport from the upstream `resolveMcpTransport` factory after 120-300 ms of jitter, and caps its connection timeout at 10000 ms so a dead server cannot double an agent run's worst-case latency. -- Classification is a fail-closed allow-list over the whole `cause` chain: MCP request timeout (`-32001`), the OpenClaw connect-timeout message, undici and POSIX in-flight transport codes, and reset/disconnect-before-headers text. +- The retry uses a fresh transport from the upstream `resolveMcpTransport` factory after 120 to 299 ms of jitter, and caps its connection timeout at 10,000 ms so a dead server cannot double an agent run's worst-case latency. + If fresh transport construction fails, the first diagnostic is preserved and NemoClaw does not claim that a retry occurred. +- Classification is a fail-closed allowlist over a bounded `cause` chain: MCP request timeout (`-32001`), the OpenClaw connect-timeout message, undici and POSIX in-flight transport codes, and reset/disconnect-before-headers text. + A truncated or cyclic cause chain is unclassifiable and is not retried. A blocked-code and blocked-text pass runs first, so authentication, authorization, OAuth token rejection, TLS and certificate validation, SSRF and policy denial, and invalid configuration are never retried. - A refused, unreachable, or unresolvable destination is deliberately excluded from the allow-list: an OpenShell L4 policy denial reaches the MCP client as a refused connection, and a refused destination is deterministic rather than a transient in-flight fault. -- An exhausted retry keeps the upstream diagnostic and appends a temporary-transport statement that explicitly clears credentials and configuration, so the agent does not report missing credentials for a transport failure. + A refused, unreachable, or unresolvable destination is deliberately excluded from the allowlist. + An OpenShell L4 policy denial reaches the MCP client as a refused connection, so retrying refusals would risk retrying policy denials. +- An exhausted retry keeps the upstream diagnostic and appends a temporary-transport statement that states that credentials and configuration were not rejected, so the agent does not report missing credentials for a transport failure. That statement is added only when the *surviving* failure is itself transient. A retry that reaches the server and is then rejected with HTTP 401, a TLS error, or a policy denial keeps its own diagnostic. - A catalog carrying a server diagnostic is not retained as the session's stable catalog. It is dropped at the next agent run boundary, in `acquireLease()` and only while the runtime is idle. - Upstream fills `catalog.diagnostics` only from a per-server start or refresh failure and omits the key when every server started, so a non-empty array is the degraded case and a healthy catalog is still reused. + Upstream fills `catalog.diagnostics` only from a per-server start or refresh failure and omits the key when no server produced a diagnostic, so a non-empty array is the degraded case and a healthy catalog is still reused. A credential, TLS, policy, or configuration rejection keeps its own diagnostic and is still never retried inside a run, but its catalog is not sticky either, so a repaired credential is picked up on the next agent run instead of requiring a new session. Scoping the drop to a run boundary rather than to every `getCatalog()` call is deliberate. `getCatalog()` is also the pre-flight for every `callTool`, `listResources`, `readResource`, `listPrompts`, and `getPrompt`, so dropping it on every call would rebuild the catalog per tool call and turn one unreachable optional server into a per-call reconnect cost. Optional MCP servers stay best-effort. -- No credential, SSRF, OAuth, or network-policy behavior changes. +- The patch does not bypass or weaken credential, SSRF, OAuth, or network-policy enforcement. A first version of this patch was rejected during review on two counts, both now covered by tests. It retried an OpenShell L4 policy denial because undici reports it as `TypeError: fetch failed`, and it reported a retry that ended in HTTP 401 as a temporary transport failure that had not rejected credentials. @@ -322,7 +325,7 @@ Coverage: `test/openclaw-mcp-reliability-patch.test.ts` pins the compiled preima `test/helpers/openclaw-real-mcp-start-retry-proof.ts` runs inside the `NEMOCLAW_REAL_OPENCLAW_DIST_HARNESS=1` harness and drives the real patched runtime against a controlled Streamable HTTP MCP server for three scenarios: first exchange resets then succeeds, every exchange resets, and a persistent 401. The proof asserts that the rejected-credential scenario is contacted once per run, with no retry inside a run. -Removal criteria: drop this patch when the reviewed OpenClaw release provides equivalent bounded startup retry, negative-catalog invalidation, and temporary-transport failure attribution. +Removal criterion: drop this patch when the reviewed OpenClaw release provides equivalent bounded startup retry, negative-catalog invalidation, and temporary-transport failure attribution. ## Gateway Startup Migration Compatibility diff --git a/scripts/patch-openclaw-mcp-reliability.mts b/scripts/patch-openclaw-mcp-reliability.mts index 920f9506c66..171e0d5520b 100755 --- a/scripts/patch-openclaw-mcp-reliability.mts +++ b/scripts/patch-openclaw-mcp-reliability.mts @@ -96,10 +96,10 @@ export const INJECTED_START_RETRY_HELPER = [ "const NEMOCLAW_MCP_RETRY_CONNECT_TIMEOUT_MS = 1e4;", "const NEMOCLAW_MCP_ERROR_CHAIN_LIMIT = 8;", 'const NEMOCLAW_MCP_TRANSIENT_DIAGNOSTIC_SUFFIX = " (temporary MCP transport failure; NemoClaw retried this startup once with a fresh transport. Credentials and configuration were not rejected. The server is retried on the next agent run.)";', - // A refused, unreachable, or unresolvable destination is deterministic, and - // an OpenShell L4 policy denial reaches the client as exactly that. Retrying - // it would repeat a denial the reporter never asked NemoClaw to retry, so - // only in-flight transport faults after a reachable connect are transient. + // A refused, unreachable, or unresolvable destination is excluded because an + // OpenShell L4 policy denial reaches the client as a refused connection. + // Retrying refusals could therefore repeat a policy denial, so only in-flight + // transport faults after a reachable connect are transient. "const NEMOCLAW_MCP_TRANSIENT_CODES = new Set([", '\t"ECONNABORTED",', '\t"ECONNRESET",', @@ -126,6 +126,7 @@ export const INJECTED_START_RETRY_HELPER = [ "\t\tchain.push(current);", '\t\tcurrent = typeof current === "object" ? current.cause : void 0;', "\t}", + "\tif (current !== void 0 && current !== null) return [];", "\treturn chain;", "}", "function nemoClawMcpErrorText(entry) {", @@ -190,7 +191,7 @@ export const INJECTED_START_RETRY_HELPER = [ "\t\t} catch {", "\t\t\tretryResolved = null;", "\t\t}", - "\t\tif (!retryResolved) return nemoClawFinalizeMcpStartResult(first, true);", + "\t\tif (!retryResolved) return nemoClawFinalizeMcpStartResult(first, false);", '\t\tlogWarn(`bundle-mcp: retrying transient startup failure for server "${params.serverName}" once with a fresh transport.`);', "\t\tawait nemoClawMcpRetryDelay();", "\t\tconst second = await params.attempt({", @@ -202,8 +203,8 @@ export const INJECTED_START_RETRY_HELPER = [ "}", // A catalog carrying any server diagnostic is degraded, so it must not become // the session's stable catalog. Upstream fills `catalog.diagnostics` only from - // a per-server start or refresh failure and omits the key entirely when every - // server started, so a non-empty array is exactly "a server did not start". + // a per-server start or refresh failure and omits the key entirely when no + // server produced a diagnostic. "function nemoClawCatalogHasStartDiagnostics(catalog) {", "\tif (!catalog || !Array.isArray(catalog.diagnostics)) return false;", "\treturn catalog.diagnostics.length > 0;", @@ -275,8 +276,11 @@ function listJsFiles(dir: string): string[] { export function patchBundleMcpRuntimeText(source: string, filePath: string): PatchTextResult { if (source.includes(MARKER)) { for (const pattern of PATCHED_REQUIRED_PATTERNS) { - if (!source.includes(pattern)) { - throw new Error(`${filePath}: MCP startup recovery marker is present but patch is partial`); + const count = countOccurrences(source, pattern); + if (count !== 1) { + throw new Error( + `${filePath}: MCP startup recovery patch is partial or ambiguous; expected exactly one patched target, found ${count}`, + ); } } for (const pattern of UNPATCHED_TARGET_PATTERNS) { @@ -315,8 +319,11 @@ export function patchBundleMcpRuntimeText(source: string, filePath: string): Pat text = text.replace(ACQUIRE_LEASE_PATTERN, ACQUIRE_LEASE_REPLACEMENT); for (const pattern of PATCHED_REQUIRED_PATTERNS) { - if (!text.includes(pattern)) { - throw new Error(`${filePath}: MCP startup recovery patch verification failed`); + const count = countOccurrences(text, pattern); + if (count !== 1) { + throw new Error( + `${filePath}: MCP startup recovery patch verification failed; expected exactly one patched target, found ${count}`, + ); } } return { patched: true, status: "patched", text }; diff --git a/test/helpers/openclaw-real-mcp-start-retry-proof.ts b/test/helpers/openclaw-real-mcp-start-retry-proof.ts index f7e9ce65c8e..c1d3c0193d2 100644 --- a/test/helpers/openclaw-real-mcp-start-retry-proof.ts +++ b/test/helpers/openclaw-real-mcp-start-retry-proof.ts @@ -130,7 +130,9 @@ export function runRealOpenClawMcpStartRetryProof(options: ProofOptions): void { throw new Error(`exhausted retry diagnostic on ${label} omits the temporary-transport cause`); } if (!diagnostics[0].includes("Credentials and configuration were not rejected")) { - throw new Error(`exhausted retry diagnostic on ${label} does not clear credentials`); + throw new Error( + `exhausted retry diagnostic on ${label} does not state that credentials and configuration were not rejected`, + ); } } diff --git a/test/openclaw-dependency-review.test.ts b/test/openclaw-dependency-review.test.ts index 5a2e1570726..d375913890a 100644 --- a/test/openclaw-dependency-review.test.ts +++ b/test/openclaw-dependency-review.test.ts @@ -22,6 +22,12 @@ const ACTIVE_DEPENDENCY_REVIEW = path.join( "security", "openclaw-2026.7.1-dependency-review.md", ); +const MCP_TROUBLESHOOTING = path.join( + REPO_ROOT, + "docs", + "reference", + "troubleshoot-mcp-servers.mdx", +); const CODEX_ACP_TARBALL = "https://registry.npmjs.org/@zed-industries/codex-acp/-/codex-acp-0.11.1.tgz"; const OPENCLAW_TARBALL = "https://registry.npmjs.org/openclaw/-/openclaw-2026.7.1.tgz"; @@ -158,6 +164,7 @@ describe("OpenClaw 2026.6.10 dependency review contract", () => { it("records the version-scoped transient remote MCP startup recovery patch (#7958)", () => { const review = readFileSync(ACTIVE_DEPENDENCY_REVIEW, "utf-8"); + const troubleshooting = readFileSync(MCP_TROUBLESHOOTING, "utf-8"); expect(review).toContain("## Transient Remote MCP Startup Recovery"); expect(review).toContain("scripts/patch-openclaw-mcp-reliability.mts"); @@ -171,7 +178,14 @@ describe("OpenClaw 2026.6.10 dependency review contract", () => { expect(review).toContain("test/helpers/openclaw-real-mcp-start-retry-proof.ts"); expect(review).toContain("NEMOCLAW_REAL_OPENCLAW_DIST_HARNESS=1"); expect(review).toContain( - "Removal criteria: drop this patch when the reviewed OpenClaw release", + "Removal criterion: drop this patch when the reviewed OpenClaw release", + ); + expect(review).toContain("only when the *surviving* failure is itself transient"); + expect(review).toContain("credentials and configuration were not rejected"); + expect(review).not.toContain("explicitly clears credentials and configuration"); + expect(review).not.toContain("a refused destination is deterministic"); + expect(troubleshooting).toMatch( + /\n\n## Remote MCP Tools Are Missing for One Agent Turn[\s\S]*?<\/AgentOnly>/, ); }); diff --git a/test/openclaw-mcp-reliability-patch.test.ts b/test/openclaw-mcp-reliability-patch.test.ts index 75ba187be4d..eeeaf69fffa 100644 --- a/test/openclaw-mcp-reliability-patch.test.ts +++ b/test/openclaw-mcp-reliability-patch.test.ts @@ -10,9 +10,9 @@ import vm from "node:vm"; import { beforeEach, describe, expect, it } from "vitest"; import { + auditOpenClawMcpReliability, INJECTED_START_RETRY_HELPER, MARKER, - auditOpenClawMcpReliability, patchBundleMcpRuntimeText, patchOpenClawMcpReliability, } from "../scripts/patch-openclaw-mcp-reliability.mts"; @@ -187,6 +187,17 @@ describe("OpenClaw MCP transient startup recovery patch (#7958)", () => { expect(auditOpenClawMcpReliability(dist)).toMatchObject({ file: runtime }); }); + it("fails closed when an audited runtime carries a duplicate patch marker", () => { + const { dist, runtime, tmp } = writeFixtureDist(); + created.push(tmp); + patchOpenClawMcpReliability(dist); + fs.appendFileSync(runtime, `\n${MARKER}\n`); + + expect(() => auditOpenClawMcpReliability(dist)).toThrow( + /expected exactly one patched target, found 2/, + ); + }); + it("fails closed when the reviewed catalog shape is unrecognized", () => { const { dist, runtime, tmp } = writeFixtureDist(); created.push(tmp); @@ -396,8 +407,50 @@ describe("OpenClaw MCP transient startup recovery patch (#7958)", () => { expect(Object.getOwnPropertySymbols(result)).toEqual([]); }); + it("preserves the first diagnostic when a fresh transport cannot be constructed", async () => { + const warnings: string[] = []; + const helper = loadInjectedHelper(warnings); + const error = Object.assign(new TypeError("fetch failed"), { + cause: Object.assign(new Error("other side closed"), { code: "UND_ERR_SOCKET" }), + }); + let attempts = 0; + + const task = helper.nemoClawWithMcpStartRetry({ + serverName: "remotedocs", + initialResolved: { transportType: "streamable-http", connectionTimeoutMs: 5_000 }, + resolveTransport: () => { + throw new Error("fresh transport construction failed"); + }, + attempt: async () => { + attempts += 1; + return startFailureResult(helper, error); + }, + }); + + const result = (await task()) as { diagnostics: Array<{ message: string }> }; + expect(attempts).toBe(1); + expect(warnings).toEqual([]); + expect(result.diagnostics[0].message).toBe(String(error)); + expect(result.diagnostics[0].message).not.toContain("temporary MCP transport failure"); + expect(result.diagnostics[0].message).not.toContain("retried"); + }); + it("never retries auth, non-streamable transports, or already-connected refresh failures", async () => { const helper = loadInjectedHelper([]); + const deepBlockedCause = Object.assign(new Error("connection reset"), { + code: "ECONNRESET", + }) as Error & { cause?: unknown }; + let deepCursor: { cause?: unknown } = deepBlockedCause; + for (let depth = 0; depth < 8; depth += 1) { + const next: { cause?: unknown } = {}; + deepCursor.cause = next; + deepCursor = next; + } + deepCursor.cause = new Error("Error POSTing to endpoint (HTTP 401): Unauthorized"); + const cyclicCause = Object.assign(new Error("connection reset"), { + code: "ECONNRESET", + }) as Error & { cause?: unknown }; + cyclicCause.cause = cyclicCause; const cases = [ { label: "auth failure", @@ -423,6 +476,18 @@ describe("OpenClaw MCP transient startup recovery patch (#7958)", () => { error: new TypeError("fetch failed"), reusedSession: true, }, + { + label: "blocked cause beyond the bounded classifier depth", + initialResolved: { transportType: "streamable-http", connectionTimeoutMs: 5_000 }, + error: deepBlockedCause, + reusedSession: false, + }, + { + label: "cyclic cause chain", + initialResolved: { transportType: "streamable-http", connectionTimeoutMs: 5_000 }, + error: cyclicCause, + reusedSession: false, + }, ]; for (const testCase of cases) { @@ -462,8 +527,8 @@ describe("OpenClaw MCP transient startup recovery patch (#7958)", () => { true, ) as { diagnostics: Array<{ message: string }> }; - // A catalog in which every server started omits the key entirely, so a - // healthy catalog is still reused. + // A catalog without server diagnostics omits the key entirely, so a healthy + // catalog is still reused. expect(helper.nemoClawCatalogHasStartDiagnostics(null)).toBe(false); expect(helper.nemoClawCatalogHasStartDiagnostics({ servers: {}, tools: [] })).toBe(false); expect(helper.nemoClawCatalogHasStartDiagnostics({ tools: [], diagnostics: [] })).toBe(false);