fix(providers): reconnect MCP servers on demand #8737
main fromrefs/pull/8737/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:S
- apps/server/src/provider/Layers/CodexSessionRuntime.ts lines 2299 to 2307OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2296,12 +2296,12 @@22962296 sendTurn: (input) =>22972297 Effect.gen(function* () {22982298 const providerThreadId = yield* readProviderThreadId;2299- if (hasConfiguredMcpServer(options.appServerArgs)) {2300- yield* client.request("config/mcpServer/reload", undefined).pipe(2301- Effect.catch((cause) =>2302- Effect.logWarning("Failed to refresh Codex MCP tool catalog before turn.", {2303- cause,2304- }),2305- ),2306- );2307- }2299+ // Codex owns configured MCP subprocesses and caches their tool catalogs2300+ // for the lifetime of this app-server process. Reload before every turn2301+ // so rebuilt local servers are reinitialized and their latest tools/list2302+ // response is used without discarding the provider thread. The request2303+ // is intentionally unconditional: appServerArgs only describes T3's2304+ // injected browser MCP, while users' other servers come from Codex's2305+ // config files. A reload failure must abort the turn rather than quietly2306+ // sending it with stale tool definitions.2307+ yield* client.request("config/mcpServer/reload", undefined);
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:S
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
- apps/server/src/provider/Layers/CodexSessionRuntime.ts line 55OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -41,3 +41,15 @@4141 import { expandHomePath } from "../../pathExpansion.ts";4242 import { buildCodexDeveloperInstructions } from "../CodexDeveloperInstructions.ts";4343 const decodeV2TurnStartResponse = Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse);44+const isCodexAppServerRequestError = Schema.is(CodexErrors.CodexAppServerRequestError);45+46+function isUnsupportedMcpReloadError(cause: CodexErrors.CodexAppServerError): boolean {47+ return isCodexAppServerRequestError(cause) && cause.code === -32601;48+}49+50+export const startCodexTurn = Effect.fn("codex.startTurn")(function* (51+ client: CodexClient.CodexAppServerClient["Service"],52+ params: CodexTurnStartParamsWithCollaborationMode,53+) {54+ yield* client55+ .request("config/mcpServer/reload", undefined)
- apps/server/src/provider/Layers/CodexSessionRuntime.ts lines 60 to 66OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -43,0 +46,21 @@46+const MCP_RELOAD_TIMEOUT = "10 seconds" as const;47+48+function isUnsupportedMcpReloadError(cause: CodexErrors.CodexAppServerError): boolean {49+ return isCodexAppServerRequestError(cause) && cause.code === -32601;50+}51+52+export const startCodexTurn = Effect.fn("codex.startTurn")(function* (53+ client: CodexClient.CodexAppServerClient["Service"],54+ params: CodexTurnStartParamsWithCollaborationMode,55+) {56+ yield* client.request("config/mcpServer/reload", undefined).pipe(57+ Effect.timeoutOption(MCP_RELOAD_TIMEOUT),58+ Effect.flatMap(59+ Option.match({60+ onNone: () =>61+ Effect.fail(62+ new CodexErrors.CodexAppServerRequestError({63+ code: -32000,64+ errorMessage: `MCP reload timed out after ${MCP_RELOAD_TIMEOUT}.`,65+ }),66+ ),
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:M
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XS
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XS
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
chrisdeeming(GitHub profile, opens in a new tab) changed the title
- apps/web/src/components/chat/ChatComposer.tsx line 1993OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1975,3 +1986,8 @@19751986 }19761987 return;19771988 }1989+ if (item.command === "reconnect-mcp") {1990+ const applied = applyPromptReplacement(1991+ trigger.rangeStart,1992+ trigger.rangeEnd,1993+ "/reconnect-mcp",apps/web/src/components/ChatView.tsx line 7485Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -5556,0 +5571,21 @@5571+ if (!isServerThread || activeThread.session === null) {5572+ toastManager.add(5573+ stackedThreadToast({5574+ type: "warning",5575+ title: "Start a Codex thread first",5576+ description: "Send a message before reconnecting its MCP servers.",5577+ }),5578+ );5579+ return;5580+ }5581+ if (activeThread.session.status === "starting" || activeThread.session.status === "running") {5582+ toastManager.add(5583+ stackedThreadToast({5584+ type: "warning",5585+ title: "Codex is still working",5586+ description: "Wait for the current turn to finish, then reconnect MCP servers.",5587+ }),5588+ );5589+ return;5590+ }5591+ const result = await stopThreadSession({
- apps/web/src/components/chat/ChatComposer.tsx lines 3593 to 3610Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1975,3 +1986,15 @@19751986 }19761987 return;19771988 }1989+ if (item.command === "reconnect-mcp") {1990+ const applied = applyPromptReplacement(1991+ trigger.rangeStart,1992+ trigger.rangeEnd,1993+ "/reconnect-mcp",1994+ { expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd) },1995+ );1996+ if (applied) {1997+ setComposerHighlightedItemId(null);1998+ }1999+ return;2000+ }
- apps/server/src/orchestration/decider.ts line 1113OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1104,3 +1104,10 @@11041104 command,11051105 threadId: command.threadId,11061106 });1107+ if (command.onlyIfIdle === true) {1108+ const sessionIsActive =1109+ thread.session?.status === "starting" || thread.session?.status === "running";1110+ if (1111+ sessionIsActive ||1112+ hasOpenBlockingRequest(thread) ||1113+ threadHasQueuedTurnStart(thread, command.createdAt)
- apps/server/src/orchestration/decider.ts line 1840Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -1104,3 +1104,16 @@11041104 command,11051105 threadId: command.threadId,11061106 });1107+ if (command.onlyIfIdle === true) {1108+ const sessionIsActive =1109+ thread.session?.status === "starting" || thread.session?.status === "running";1110+ if (1111+ sessionIsActive ||1112+ hasOpenBlockingRequest(thread) ||1113+ threadHasQueuedTurnStart(thread, command.createdAt)1114+ ) {1115+ return yield* new OrchestrationCommandInvariantError({1116+ commandType: command.type,1117+ detail: `thread ${command.threadId} is active and its session cannot be restarted`,1118+ });1119+ }
- apps/mobile/src/state/use-thread-composer-state.ts line 396Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -387,3 +393,4 @@387393 const provider = serverConfig?.providers.find(388394 (entry) => entry.instanceId === modelSelection.instanceId,389395 );396+ const reconnectMcpCommand =
- apps/mobile/src/state/use-thread-composer-state.ts lines 417 to 425Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -389,0 +404,21 @@404+ "Send a message before reconnecting its MCP servers.",405+ );406+ return null;407+ }408+ if (thread.session.status === "starting" || thread.session.status === "running") {409+ Alert.alert(410+ "Codex is still working",411+ "Wait for the current turn to finish, then reconnect MCP servers.",412+ );413+ return null;414+ }415+ clearComposerDraftContent(threadKey);416+ const result = await stopThreadSession({417+ environmentId: selectedThreadShell.environmentId,418+ input: { threadId: selectedThreadShell.id, onlyIfIdle: true },419+ });420+ if (result._tag === "Failure") {421+ const currentDraft = getComposerDraftSnapshot(threadKey);422+ if (currentDraft.text.length === 0 && currentDraft.attachments.length === 0) {423+ setComposerDraftText(threadKey, text);424+ }
chrisdeeming(GitHub profile, opens in a new tab) changed the title
- apps/mobile/src/features/threads/use-composer-command-menu.ts line 88OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -85,3 +85,4 @@8585 label: "/default",8686 description: "Switch to default mode",8787 },88+ ...(input.hasThread
- apps/web/src/components/ChatView.tsx line 7443Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -7429,3 +7433,11 @@74297433 terminalContexts: composerTerminalContexts,74307434 elementContextCount: composerPreviewAnnotations.length + composerReviewComments.length,74317435 });7436+ const reconnectMcpCommand =7437+ composerImages.length === 0 &&7438+ composerFiles.length === 0 &&7439+ sendableComposerTerminalContexts.length === 0 &&7440+ composerPreviewAnnotations.length === 0 &&7441+ composerReviewComments.length === 0 &&7442+ isReconnectMcpCommand(trimmed);7443+ if (reconnectMcpCommand) {apps/web/src/components/ChatView.tsx lines 7497 to 7508Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -7431,0 +7460,21 @@7460+ }),7461+ );7462+ return;7463+ }7464+ sendInFlightRef.current = true;7465+ promptRef.current = "";7466+ clearComposerDraftContent(composerDraftTarget);7467+ composerRef.current?.resetCursorState();7468+ const result = await stopThreadSession({7469+ environmentId,7470+ input: { threadId: activeThread.id, onlyIfIdle: true },7471+ }).finally(() => {7472+ sendInFlightRef.current = false;7473+ });7474+ if (result._tag === "Failure") {7475+ if (7476+ promptRef.current.length === 0 &&7477+ composerImagesRef.current.length === 0 &&7478+ composerFilesRef.current.length === 0 &&7479+ composerTerminalContextsRef.current.length === 07480+ ) {apps/web/src/components/ChatView.tsx lines 7500 to 7500Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -7431,0 +7456,21 @@7456+ stackedThreadToast({7457+ type: "warning",7458+ title: "Agent is still working",7459+ description: "Wait for the current turn to finish, then reconnect MCP servers.",7460+ }),7461+ );7462+ return;7463+ }7464+ sendInFlightRef.current = true;7465+ promptRef.current = "";7466+ clearComposerDraftContent(composerDraftTarget);7467+ composerRef.current?.resetCursorState();7468+ const result = await stopThreadSession({7469+ environmentId,7470+ input: { threadId: activeThread.id, onlyIfIdle: true },7471+ }).finally(() => {7472+ sendInFlightRef.current = false;7473+ });7474+ if (result._tag === "Failure") {7475+ if (7476+ promptRef.current.length === 0 &&
juliusmarminge closed this
Sign in to join this conversation.


Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
The change expands
/reconnect-mcpfrom Codex-only handling to all providers. Web and mobile flows require an existing idle session, stop sessions through orchestration, handle failures, and document provider-specific behavior.Changes#
MCP reconnect
apps/web/src/composer-logic.ts,apps/web/src/components/chat/ChatComposer.tsx,apps/mobile/src/features/threads/*,packages/client-runtime/src/state/threadMcpReconnect.ts,packages/client-runtime/src/state/threads.ts,docs/user/providers-*.md/reconnect-mcpfor threads with sessions on any provider. Runtime recognition accepts only the standalone command. Provider documentation describes the reconnect behavior.packages/contracts/src/orchestration.ts,apps/server/src/orchestration/decider.ts,apps/server/src/orchestration/decider.settled.test.ts,apps/server/src/orchestration/Layers/OrchestrationEngine.ts,apps/server/src/orchestration/Layers/OrchestrationEngine.test.tsthread.session.stopacceptsonlyIfIdle. Orchestration rejects active sessions, pending requests, queued turns, and live background work.apps/web/src/components/ChatView.tsx,apps/web/src/components/chat/ChatComposer.tsxonlyIfIdle, restores failed commands, and reports the result.apps/mobile/src/state/use-thread-composer-state.tsPriority: ➖ Normal
Estimated code review effort: 4 (Complex) | ~45 minutes
Change: Feature
Sequence Diagram(s)#
Suggested reviewers:
t3dotggMerge Risk: 🔵 Low · up to
813bfIn a narrow lifecycle window,
/reconnect-mcpcan interrupt an still-running background shell instead of recognizing the thread as busy.🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1
⚔️ Resolve merge conflicts 💡
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.