Skip to content

Commit 78e5462

Browse files
committed
fix(codex): reconnect MCP servers on demand
1 parent 2daff8c commit 78e5462

12 files changed

Lines changed: 281 additions & 5 deletions

File tree

‎apps/mobile/src/features/threads/use-composer-command-menu.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,17 @@ export function useComposerCommandMenu({
9494
label: "/default",
9595
description: "Switch to default mode",
9696
},
97+
...(hasThread && selectedProviderStatus?.driver === "codex"
98+
? [
99+
{
100+
id: "cmd:reconnect-mcp",
101+
type: "slash-command" as const,
102+
command: "reconnect-mcp",
103+
label: "/reconnect-mcp",
104+
description: "Reconnect MCP servers before the next turn",
105+
},
106+
]
107+
: []),
97108
];
98109
const builtIn = allBuiltIn.filter(
99110
(item) =>

‎apps/mobile/src/state/use-thread-composer-state.ts‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
1616
import {
1717
codexFeedbackMessage,
18+
isReconnectMcpCommand,
1819
parseCodexFeedbackCommand,
1920
submitCodexFeedback,
2021
type CodexFeedbackSubmission,
@@ -96,6 +97,9 @@ export function useThreadComposerState() {
9697
const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
9798
reportFailure: false,
9899
});
100+
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, {
101+
reportFailure: false,
102+
});
99103

100104
useEffect(() => {
101105
ensureComposerDraftsLoaded();
@@ -173,8 +177,52 @@ export function useThreadComposerState() {
173177
}
174178

175179
const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
176-
(entry) => entry.instanceId === thread.modelSelection.instanceId,
180+
(entry) => entry.instanceId === (draft.modelSelection ?? thread.modelSelection).instanceId,
177181
);
182+
const reconnectMcpCommand =
183+
attachments.length === 0 &&
184+
(provider?.driver === "codex" || thread.session?.providerName === "codex") &&
185+
isReconnectMcpCommand(text);
186+
if (reconnectMcpCommand) {
187+
if (thread.session === null || thread.session.providerName !== "codex") {
188+
Alert.alert(
189+
"Start a Codex thread first",
190+
"Send a message before reconnecting its MCP servers.",
191+
);
192+
return null;
193+
}
194+
if (thread.session.status === "starting" || thread.session.status === "running") {
195+
Alert.alert(
196+
"Codex is still working",
197+
"Wait for the current turn to finish, then reconnect MCP servers.",
198+
);
199+
return null;
200+
}
201+
clearComposerDraftContent(threadKey);
202+
const result = await stopThreadSession({
203+
environmentId: selectedThreadShell.environmentId,
204+
input: { threadId: selectedThreadShell.id, onlyIfIdle: true },
205+
});
206+
if (result._tag === "Failure") {
207+
const currentDraft = getComposerDraftSnapshot(threadKey);
208+
if (currentDraft.text.length === 0 && currentDraft.attachments.length === 0) {
209+
setComposerDraftText(threadKey, text);
210+
}
211+
if (!isAtomCommandInterrupted(result)) {
212+
const error = Cause.squash(result.cause);
213+
Alert.alert(
214+
"Could not reconnect MCP servers",
215+
error instanceof Error ? error.message : "An error occurred.",
216+
);
217+
}
218+
return null;
219+
}
220+
Alert.alert(
221+
"MCP servers disconnected",
222+
"They will reconnect with fresh tool schemas on your next message.",
223+
);
224+
return null;
225+
}
178226
const feedbackCommand =
179227
attachments.length === 0 &&
180228
(provider?.driver === "codex" || thread.session?.providerName === "codex")
@@ -272,6 +320,7 @@ export function useThreadComposerState() {
272320
selectedEnvironmentRuntime?.serverConfig?.providers,
273321
selectedThreadDetail,
274322
selectedThreadShell,
323+
stopThreadSession,
275324
uploadThreadFeedback,
276325
]);
277326

‎apps/server/src/orchestration/decider.settled.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -684,4 +684,67 @@ it.layer(NodeServices.layer)("settled thread decider", (it) => {
684684
]);
685685
}),
686686
);
687+
688+
it.effect("only allows idle-only session stops after active work finishes", () =>
689+
Effect.gen(function* () {
690+
const stopCommand = {
691+
type: "thread.session.stop",
692+
commandId: CommandId.make("cmd-stop-only-if-idle"),
693+
threadId: ThreadId.make("thread-1"),
694+
createdAt: NOW,
695+
onlyIfIdle: true,
696+
} as const;
697+
698+
const activeError = yield* decideOrchestrationCommand({
699+
command: stopCommand,
700+
readModel: makeReadModel(null, null, makeSession("running")),
701+
}).pipe(Effect.flip);
702+
expect(activeError._tag).toBe("OrchestrationCommandInvariantError");
703+
704+
const blockedError = yield* decideOrchestrationCommand({
705+
command: stopCommand,
706+
readModel: makeReadModel(null, null, makeSession("ready"), [
707+
{
708+
id: EventId.make("activity-reconnect-approval"),
709+
tone: "approval",
710+
kind: "approval.requested",
711+
summary: "Approval requested",
712+
payload: { requestId: "request-reconnect" },
713+
turnId: null,
714+
createdAt: NOW,
715+
},
716+
]),
717+
}).pipe(Effect.flip);
718+
expect(blockedError._tag).toBe("OrchestrationCommandInvariantError");
719+
720+
const queuedError = yield* decideOrchestrationCommand({
721+
command: stopCommand,
722+
readModel: makeReadModel(
723+
null,
724+
null,
725+
makeSession("ready"),
726+
[],
727+
[
728+
{
729+
id: MessageId.make("message-reconnect-queued"),
730+
role: "user",
731+
text: "Continue",
732+
turnId: null,
733+
streaming: false,
734+
createdAt: NOW,
735+
updatedAt: NOW,
736+
},
737+
],
738+
),
739+
}).pipe(Effect.flip);
740+
expect(queuedError._tag).toBe("OrchestrationCommandInvariantError");
741+
742+
const idle = yield* decideOrchestrationCommand({
743+
command: stopCommand,
744+
readModel: makeReadModel(null, null, makeSession("ready")),
745+
});
746+
const idleEvents = Array.isArray(idle) ? idle : [idle];
747+
expect(idleEvents.map((event) => event.type)).toEqual(["thread.session-stop-requested"]);
748+
}),
749+
);
687750
});

‎apps/server/src/orchestration/decider.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1141,6 +1141,20 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
11411141
command,
11421142
threadId: command.threadId,
11431143
});
1144+
if (command.onlyIfIdle === true) {
1145+
const sessionIsActive =
1146+
thread.session?.status === "starting" || thread.session?.status === "running";
1147+
if (
1148+
sessionIsActive ||
1149+
hasOpenBlockingRequest(thread) ||
1150+
threadHasQueuedTurnStart(thread, command.createdAt)
1151+
) {
1152+
return yield* new OrchestrationCommandInvariantError({
1153+
commandType: command.type,
1154+
detail: `thread ${command.threadId} is active and its session cannot be restarted`,
1155+
});
1156+
}
1157+
}
11441158
// Settle-cleanup stops are conditional: between the settle landing and
11451159
// this command, another client may have re-engaged the thread (a turn
11461160
// start unsettles it and brings the session alive). Commands are

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
} from "@t3tools/client-runtime/state/thread-settled";
3838
import {
3939
codexFeedbackMessage,
40+
isReconnectMcpCommand,
4041
parseCodexFeedbackCommand,
4142
submitCodexFeedback,
4243
type CodexFeedbackSubmission,
@@ -1311,6 +1312,9 @@ function ChatViewContent(props: ChatViewProps) {
13111312
reportFailure: false,
13121313
});
13131314
const startThreadTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
1315+
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, {
1316+
reportFailure: false,
1317+
});
13141318
const createAttachmentAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
13151319
reportFailure: false,
13161320
});
@@ -5554,6 +5558,86 @@ function ChatViewContent(props: ChatViewProps) {
55545558
composerPreviewAnnotations.length +
55555559
composerReviewComments.length,
55565560
});
5561+
const reconnectMcpCommand =
5562+
ctxSelectedProvider === "codex" &&
5563+
composerImages.length === 0 &&
5564+
composerFiles.length === 0 &&
5565+
sendableComposerTerminalContexts.length === 0 &&
5566+
composerElementContexts.length === 0 &&
5567+
composerPreviewAnnotations.length === 0 &&
5568+
composerReviewComments.length === 0 &&
5569+
isReconnectMcpCommand(trimmed);
5570+
if (reconnectMcpCommand) {
5571+
if (
5572+
!isServerThread ||
5573+
activeThread.session === null ||
5574+
activeThread.session.providerName !== "codex"
5575+
) {
5576+
toastManager.add(
5577+
stackedThreadToast({
5578+
type: "warning",
5579+
title: "Start a Codex thread first",
5580+
description: "Send a message before reconnecting its MCP servers.",
5581+
}),
5582+
);
5583+
return;
5584+
}
5585+
if (activeThread.session.status === "starting" || activeThread.session.status === "running") {
5586+
toastManager.add(
5587+
stackedThreadToast({
5588+
type: "warning",
5589+
title: "Codex is still working",
5590+
description: "Wait for the current turn to finish, then reconnect MCP servers.",
5591+
}),
5592+
);
5593+
return;
5594+
}
5595+
sendInFlightRef.current = true;
5596+
promptRef.current = "";
5597+
clearComposerDraftContent(composerDraftTarget);
5598+
composerRef.current?.resetCursorState();
5599+
const result = await stopThreadSession({
5600+
environmentId,
5601+
input: { threadId: activeThread.id, onlyIfIdle: true },
5602+
}).finally(() => {
5603+
sendInFlightRef.current = false;
5604+
});
5605+
if (result._tag === "Failure") {
5606+
if (
5607+
promptRef.current.length === 0 &&
5608+
composerImagesRef.current.length === 0 &&
5609+
composerFilesRef.current.length === 0 &&
5610+
composerTerminalContextsRef.current.length === 0 &&
5611+
composerElementContextsRef.current.length === 0
5612+
) {
5613+
promptRef.current = promptForSend;
5614+
setComposerDraftPrompt(composerDraftTarget, promptForSend);
5615+
composerRef.current?.resetCursorState({
5616+
cursor: collapseExpandedComposerCursor(promptForSend, promptForSend.length),
5617+
prompt: promptForSend,
5618+
detectTrigger: true,
5619+
});
5620+
}
5621+
if (!isAtomCommandInterrupted(result)) {
5622+
toastManager.add(
5623+
stackedThreadToast({
5624+
type: "error",
5625+
title: "Could not reconnect MCP servers",
5626+
description: chatActionErrorMessage(squashAtomCommandFailure(result)),
5627+
}),
5628+
);
5629+
}
5630+
return;
5631+
}
5632+
toastManager.add(
5633+
stackedThreadToast({
5634+
type: "success",
5635+
title: "MCP servers disconnected",
5636+
description: "They will reconnect with fresh tool schemas on your next message.",
5637+
}),
5638+
);
5639+
return;
5640+
}
55575641
const feedbackCommand =
55585642
ctxSelectedProvider === "codex" &&
55595643
composerImages.length === 0 &&

‎apps/web/src/components/chat/ChatComposer.tsx‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1263,6 +1263,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
12631263
label: "/model",
12641264
description: "Switch response model for this thread",
12651265
},
1266+
...(selectedProvider === "codex"
1267+
? ([
1268+
{
1269+
id: "slash:reconnect-mcp",
1270+
type: "slash-command",
1271+
command: "reconnect-mcp",
1272+
label: "/reconnect-mcp",
1273+
description: "Reconnect this thread's MCP servers before the next turn",
1274+
},
1275+
] as const)
1276+
: []),
12661277
...(planModeUiEnabled
12671278
? ([
12681279
{
@@ -1975,6 +1986,24 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
19751986
}
19761987
return;
19771988
}
1989+
if (item.command === "reconnect-mcp") {
1990+
const replacement = "/reconnect-mcp ";
1991+
const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
1992+
snapshot.value,
1993+
trigger.rangeEnd,
1994+
replacement,
1995+
);
1996+
const applied = applyPromptReplacement(
1997+
trigger.rangeStart,
1998+
replacementRangeEnd,
1999+
replacement,
2000+
{ expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
2001+
);
2002+
if (applied) {
2003+
setComposerHighlightedItemId(null);
2004+
}
2005+
return;
2006+
}
19782007
void handleInteractionModeChange(item.command === "plan" ? "plan" : "default");
19792008
const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
19802009
expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),

‎apps/web/src/composer-logic.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
22
import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
33

44
export type ComposerTriggerKind = "path" | "slash-command" | "skill";
5-
export type ComposerSlashCommand = "model" | "plan" | "default";
5+
export type ComposerSlashCommand = "model" | "plan" | "default" | "reconnect-mcp";
66
export type ComposerSubmissionIntent = "foreground" | "background";
77

88
export interface ComposerTrigger {
@@ -268,9 +268,7 @@ export function detectComposerTrigger(text: string, cursorInput: number): Compos
268268
};
269269
}
270270

271-
export function parseStandaloneComposerSlashCommand(
272-
text: string,
273-
): Exclude<ComposerSlashCommand, "model"> | null {
271+
export function parseStandaloneComposerSlashCommand(text: string): "plan" | "default" | null {
274272
const match = /^\/(plan|default)\s*$/i.exec(text.trim());
275273
if (!match) {
276274
return null;

‎docs/user/providers-codex.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,13 @@ In an existing Codex thread, send `/feedback` or `/feedback` followed by a descr
3434
issue. T3 Code uploads the thread and Codex logs to OpenAI and shows a thread ID that you can copy
3535
and share with OpenAI employees.
3636

37+
## Reconnect MCP servers
38+
39+
In an idle Codex thread, send `/reconnect-mcp` to disconnect that thread's MCP servers. They
40+
restart with fresh tool definitions when you send the next message. The command preserves the
41+
conversation and workspace, but it reconnects every MCP server used by that thread. Wait for an
42+
active turn to finish before running it.
43+
3744
## Sub-agent models
3845

3946
The web and desktop Agents panel shows each sub-agent's model and reasoning effort when Codex
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { isReconnectMcpCommand } from "./threadMcpReconnect.ts";
4+
5+
describe("isReconnectMcpCommand", () => {
6+
it("recognizes a standalone reconnect command", () => {
7+
expect(isReconnectMcpCommand(" /RECONNECT-MCP ")).toBe(true);
8+
});
9+
10+
it("does not consume prompts that merely start with the command", () => {
11+
expect(isReconnectMcpCommand("/reconnect-mcp after this turn")).toBe(false);
12+
});
13+
});
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export function isReconnectMcpCommand(text: string): boolean {
2+
return /^\/reconnect-mcp\s*$/i.test(text.trim());
3+
}

0 commit comments

Comments
 (0)