11/** Session-scoped MCP runtime catalog loader and transport lifecycle. */
22import { Client , type ClientOptions } from "@modelcontextprotocol/sdk/client/index.js" ;
3- import {
4- StreamableHTTPClientTransport ,
5- StreamableHTTPError ,
6- } from "@modelcontextprotocol/sdk/client/streamableHttp.js" ;
73import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js" ;
84import {
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" ;
5961import {
6062 normalizeMcpCodexToolAnnotations ,
6163 resolveMcpCodexToolApprovalMode ,
@@ -67,7 +69,6 @@ import {
6769import { createMcpJsonSchemaValidator } from "./mcp-json-schema-validator.js" ;
6870import { sanitizeMcpMetadataText } from "./mcp-metadata.js" ;
6971import { collectMcpPaginatedItems } from "./mcp-pagination.js" ;
70- import { OpenClawStdioClientTransport } from "./mcp-stdio-transport.js" ;
7172import { isMcpToolAllowed , normalizeMcpToolFilter } from "./mcp-tool-filter.js" ;
7273import { resolveMcpTransport } from "./mcp-transport.js" ;
7374
@@ -122,53 +123,6 @@ type McpServerBackoffState = {
122123
123124export { 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-
172126function 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+
269230function 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-
353267function 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