Skip to content

Commit ee86b24

Browse files
authored
fix(node-host): recover MCP catalogs and sessions (#125092)
* fix(node-host): recover MCP catalogs and sessions Share placement-neutral MCP lifecycle and result projection while keeping Gateway session ownership and node process ownership separate. Refresh node catalogs live, recover closed or expired transports without replay, and preserve MCP application errors across node.invoke.\n\nFixes #125044 * test: register node MCP CI inventory * fix(node-host): stop MCP recovery after abort
1 parent fcb499a commit ee86b24

20 files changed

Lines changed: 2586 additions & 393 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1687,7 +1687,7 @@ src/agents/agent-bundle-mcp-manager-api.ts 2
16871687
src/agents/agent-bundle-mcp-manager-lifecycle.ts 1
16881688
src/agents/agent-bundle-mcp-materialize.ts 4
16891689
src/agents/agent-bundle-mcp-runtime-shared.ts 2
1690-
src/agents/agent-bundle-mcp-runtime.ts 10
1690+
src/agents/agent-bundle-mcp-runtime.ts 9
16911691
src/agents/agent-command-restart-recovery.ts 4
16921692
src/agents/agent-command.ts 1
16931693
src/agents/agent-hooks/compaction-safeguard.ts 19
@@ -3486,7 +3486,7 @@ src/node-host/invoke-agent-cli-claude-params.ts 4
34863486
src/node-host/invoke-agent-cli-claude.ts 2
34873487
src/node-host/invoke-file-commands.ts 1
34883488
src/node-host/invoke-payload.ts 5
3489-
src/node-host/invoke.ts 8
3489+
src/node-host/invoke.ts 7
34903490
src/node-host/mcp.ts 3
34913491
src/node-host/node-worker-bundle-installer.ts 1
34923492
src/node-host/node-worker-supervisor.ts 1

‎config/knip.all-exports.config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ const ROOT_TEST_ENTRY_GLOBS = [
5151
"test/e2e/qa-lab/runtime/agent-bundle-mcp-tools-docker-client.ts!",
5252
"test/e2e/qa-lab/runtime/docker-e2e-lane.ts!",
5353
"test/e2e/qa-lab/runtime/mcp-channels-docker-client.ts!",
54+
// The Gateway/node MCP parity tests spawn this transport fixture by path.
55+
"test/e2e/qa-lab/runtime/gateway-node-mcp.fixture.mjs!",
5456
// The identity scenario spawns this process-isolated repeated-turn driver by path.
5557
"test/e2e/qa-lab/runtime/agent-run-identity-repeated-turn-child.ts!",
5658
// Invoked directly by the Docker image-auth scenario.

‎docs/nodes/index.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,12 @@ require re-pairing because the approved command family is unchanged. Restart
215215
`openclaw node run` or `openclaw node restart` to apply node MCP config changes;
216216
the node host does not watch this config.
217217

218+
Server-advertised tool-list changes apply live and replace the published node
219+
catalog. If an MCP transport closes or a stateful Streamable HTTP session
220+
expires, the node withdraws that server's stale tools and reconnects with
221+
bounded backoff. The failed call that detects an expired session is not replayed;
222+
a later call can use the replacement connection after its tools are republished.
223+
218224
Gateway operators can ignore all agent-visible tools published by paired nodes,
219225
including node-hosted MCP tools, with
220226
`gateway.nodes.pluginTools.enabled: false`. Exact command denies such as

‎src/agents/agent-bundle-mcp-materialize.ts‎

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import type {
2020
McpToolCatalog,
2121
SessionMcpRuntime,
2222
} from "./agent-bundle-mcp-types.js";
23-
import { mcpContentBlockToAgentContent } from "./mcp-content.js";
23+
import { projectMcpCallToolResultContent } from "./mcp-content.js";
2424
import { isMcpToolAllowed } from "./mcp-tool-filter.js";
2525
import { buildMcpAppCanvasPayload, fetchMcpAppView } from "./mcp-ui-resource.js";
2626
import type { AgentToolResult } from "./runtime/index.js";
@@ -100,27 +100,9 @@ function toAgentToolResult(params: {
100100
toolName: string;
101101
result: CallToolResult;
102102
}): AgentToolResult<unknown> {
103-
const sourceContent = Array.isArray(params.result.content) ? params.result.content : [];
104-
const content: AgentToolResult<unknown>["content"] = sourceContent.map(
105-
mcpContentBlockToAgentContent,
106-
);
107-
const structuredContentBlock =
108-
params.result.structuredContent !== undefined
109-
? ({
110-
type: "text",
111-
text: `structuredContent:\n${JSON.stringify(params.result.structuredContent, null, 2)}`,
112-
} as const)
113-
: null;
114-
// Structured results replace mirrored text, but original non-text blocks
115-
// still carry images, linked resources, and audio that the JSON cannot mirror.
116-
const normalizedContent: AgentToolResult<unknown>["content"] = structuredContentBlock
117-
? [
118-
structuredContentBlock,
119-
...sourceContent
120-
.filter((block) => block.type !== "text")
121-
.map(mcpContentBlockToAgentContent),
122-
]
123-
: content.length > 0
103+
const content = projectMcpCallToolResultContent(params.result);
104+
const normalizedContent: AgentToolResult<unknown>["content"] =
105+
content.length > 0
124106
? content
125107
: ([
126108
{

‎src/agents/agent-bundle-mcp-runtime.test.ts‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5787,12 +5787,6 @@ process.on("SIGINT", shutdown);`,
57875787
} else {
57885788
expect(secondCatalog.servers.slow).toBeDefined();
57895789
}
5790-
await waitForFileText(
5791-
slowLogPath,
5792-
"slow first initialize",
5793-
LIST_TOOLS_SERVER_LOG_TIMEOUT_MS,
5794-
);
5795-
57965790
await expect(runtime.callTool("trigger", "poke", {})).resolves.toMatchObject({
57975791
content: [{ type: "text", text: "poked" }],
57985792
isError: false,

‎src/agents/agent-bundle-mcp-runtime.ts‎

Lines changed: 31 additions & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
/** Session-scoped MCP runtime catalog loader and transport lifecycle. */
22
import { Client, type ClientOptions } from "@modelcontextprotocol/sdk/client/index.js";
3-
import {
4-
StreamableHTTPClientTransport,
5-
StreamableHTTPError,
6-
} from "@modelcontextprotocol/sdk/client/streamableHttp.js";
73
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
84
import {
95
ErrorCode,
@@ -56,6 +52,12 @@ import type {
5652
SessionMcpRuntime,
5753
SessionMcpRuntimeManager,
5854
} from "./agent-bundle-mcp-types.js";
55+
import {
56+
connectMcpClient,
57+
disposeMcpClient,
58+
isStatefulMcpHttpSessionExpired,
59+
McpClientConnectTimeoutError,
60+
} from "./mcp-client-lifecycle.js";
5961
import {
6062
normalizeMcpCodexToolAnnotations,
6163
resolveMcpCodexToolApprovalMode,
@@ -67,7 +69,6 @@ import {
6769
import { createMcpJsonSchemaValidator } from "./mcp-json-schema-validator.js";
6870
import { sanitizeMcpMetadataText } from "./mcp-metadata.js";
6971
import { collectMcpPaginatedItems } from "./mcp-pagination.js";
70-
import { OpenClawStdioClientTransport } from "./mcp-stdio-transport.js";
7172
import { isMcpToolAllowed, normalizeMcpToolFilter } from "./mcp-tool-filter.js";
7273
import { resolveMcpTransport } from "./mcp-transport.js";
7374

@@ -122,53 +123,6 @@ type McpServerBackoffState = {
122123

123124
export { createMcpJsonSchemaValidator as createBundleMcpJsonSchemaValidator };
124125

125-
async function connectWithTimeout(
126-
serverName: string,
127-
client: Client,
128-
transport: Transport,
129-
timeoutMs: number,
130-
): Promise<void> {
131-
const abortController = new AbortController();
132-
let timeout: ReturnType<typeof setTimeout> | undefined;
133-
let deadlineExpired = false;
134-
try {
135-
// Client.connect() owns both transport startup and the initialize round trip.
136-
// Give the SDK the deadline so initialize is cancelled, while the outer race
137-
// also bounds transports whose start() has not reached initialize yet.
138-
await Promise.race([
139-
client.connect(transport, {
140-
signal: abortController.signal,
141-
timeout: timeoutMs,
142-
maxTotalTimeout: timeoutMs,
143-
}),
144-
new Promise<never>((_, reject) => {
145-
timeout = setTimeout(() => {
146-
deadlineExpired = true;
147-
abortController.abort();
148-
reject(new Error("MCP connect deadline expired"));
149-
}, timeoutMs);
150-
}),
151-
]);
152-
} catch (error) {
153-
if (deadlineExpired || (isRecord(error) && error.code === ErrorCode.RequestTimeout)) {
154-
if (transport instanceof OpenClawStdioClientTransport) {
155-
await transport.forceClose();
156-
}
157-
// Closing the SDK client settles its pending initialize request. Without
158-
// this, later runtime disposal waits its full teardown timeout even though
159-
// the stdio child is already dead.
160-
await settleWithin(client.close(), Math.min(timeoutMs, 1_000));
161-
throw new Error(
162-
`MCP server "${serverName}" timed out: did not complete initialize within ${timeoutMs / 1_000}s`,
163-
{ cause: error },
164-
);
165-
}
166-
throw error;
167-
} finally {
168-
clearTimeout(timeout);
169-
}
170-
}
171-
172126
function redactMcpDiagnosticError(error: unknown): string {
173127
return redactToolPayloadText(redactSensitiveUrlLikeString(String(error)));
174128
}
@@ -266,6 +220,13 @@ function setBundleMcpDisposeTimeoutMsForTest(timeoutMs?: number): void {
266220
: undefined;
267221
}
268222

223+
function disposeBundleMcpSession(session: BundleMcpSession): Promise<void> {
224+
return disposeMcpClient(
225+
session,
226+
getBundleMcpTestState().disposeTimeoutMs ?? BUNDLE_MCP_DISPOSE_TIMEOUT_MS,
227+
);
228+
}
229+
269230
function buildMcpClientCapabilities(mcpAppsEnabled: boolean): ClientCapabilities {
270231
return mcpAppsEnabled
271232
? {
@@ -303,53 +264,6 @@ function summarizeServerCapabilities(capabilities: ServerCapabilities | undefine
303264
: undefined,
304265
};
305266
}
306-
async function settleWithin(promise: Promise<unknown>, timeoutMs: number): Promise<boolean> {
307-
let timer: ReturnType<typeof setTimeout> | undefined;
308-
return await Promise.race([
309-
promise.then(
310-
() => true,
311-
() => true,
312-
),
313-
new Promise<void>((resolve) => {
314-
timer = setTimeout(() => {
315-
resolve();
316-
}, timeoutMs);
317-
timer.unref?.();
318-
}).then(() => false),
319-
]).finally(() => {
320-
if (timer) {
321-
clearTimeout(timer);
322-
}
323-
});
324-
}
325-
326-
async function disposeSession(session: BundleMcpSession) {
327-
session.detachStderr?.();
328-
const timeoutMs = getBundleMcpTestState().disposeTimeoutMs ?? BUNDLE_MCP_DISPOSE_TIMEOUT_MS;
329-
const closed = await settleWithin(
330-
(async () => {
331-
if (session.transportType === "streamable-http") {
332-
await (session.transport as StreamableHTTPClientTransport)
333-
.terminateSession()
334-
.catch(() => {});
335-
}
336-
await session.transport.close().catch(() => {});
337-
await session.client.close().catch(() => {});
338-
})(),
339-
timeoutMs,
340-
);
341-
if (!closed) {
342-
// Force-close transport and client so a hung terminateSession() DELETE
343-
// gets its AbortSignal triggered by teardown. Stdio owns a process group,
344-
// so force it dead before disposal can report completion.
345-
const transportClose =
346-
session.transport instanceof OpenClawStdioClientTransport
347-
? session.transport.forceClose()
348-
: session.transport.close();
349-
await settleWithin(Promise.allSettled([transportClose, session.client.close()]), timeoutMs);
350-
}
351-
}
352-
353267
function createDisposedError(sessionId: string): Error {
354268
return new Error(`bundle-mcp runtime disposed for session ${sessionId}`);
355269
}
@@ -486,12 +400,20 @@ export function createSessionMcpRuntime(params: {
486400
if (session.connected) {
487401
return;
488402
}
489-
session.connectPromise ??= connectWithTimeout(
490-
session.serverName,
491-
session.client,
492-
session.transport,
493-
connectionTimeoutMs,
494-
)
403+
session.connectPromise ??= connectMcpClient({
404+
client: session.client,
405+
transport: session.transport,
406+
timeoutMs: connectionTimeoutMs,
407+
})
408+
.catch((error: unknown) => {
409+
if (error instanceof McpClientConnectTimeoutError) {
410+
throw new Error(
411+
`MCP server "${session.serverName}" timed out: did not complete initialize within ${connectionTimeoutMs / 1_000}s`,
412+
{ cause: error },
413+
);
414+
}
415+
throw error;
416+
})
495417
.then(() => {
496418
session.connected = true;
497419
})
@@ -509,7 +431,7 @@ export function createSessionMcpRuntime(params: {
509431
}
510432
session.retiring = true;
511433
sessions.delete(serverName);
512-
await disposeSession(session);
434+
await disposeBundleMcpSession(session);
513435
return true;
514436
};
515437
const localRequestTimeouts = new WeakSet<object>();
@@ -580,12 +502,7 @@ export function createSessionMcpRuntime(params: {
580502
} catch (error) {
581503
// A stateful server uses HTTP 404 to invalidate an expired MCP session.
582504
// Reinitialize a fresh client, but never replay a possibly mutating call.
583-
const sessionExpired =
584-
session.transportType === "streamable-http" &&
585-
session.transport instanceof StreamableHTTPClientTransport &&
586-
session.transport.sessionId !== undefined &&
587-
error instanceof StreamableHTTPError &&
588-
error.code === 404;
505+
const sessionExpired = isStatefulMcpHttpSessionExpired(session, error);
589506
let recycleReason: "expired HTTP session" | "repeated request timeouts" | undefined;
590507
if (sessionExpired && !requestSignal?.aborted) {
591508
recycleReason = "expired HTTP session";
@@ -1012,7 +929,7 @@ export function createSessionMcpRuntime(params: {
1012929
};
1013930
} catch (error) {
1014931
await Promise.allSettled(
1015-
Array.from(sessions.values(), (session) => disposeSession(session)),
932+
Array.from(sessions.values(), (session) => disposeBundleMcpSession(session)),
1016933
);
1017934
sessions.clear();
1018935
throw error;
@@ -1172,7 +1089,7 @@ export function createSessionMcpRuntime(params: {
11721089
catalogInFlight = undefined;
11731090
const sessionsToClose = Array.from(sessions.values());
11741091
sessions.clear();
1175-
await Promise.allSettled(sessionsToClose.map((session) => disposeSession(session)));
1092+
await Promise.allSettled(sessionsToClose.map((session) => disposeBundleMcpSession(session)));
11761093
},
11771094
};
11781095
return runtime;

0 commit comments

Comments
 (0)