Skip to content

Commit 014d02a

Browse files
totobusnelloclaude
andcommitted
fix(cli-runner): scope bundle-MCP cleanup to the run's session, not the process-wide loopback server
On run end, runCliAgentInternal handled cleanupBundleMcpOnRunEnd by calling closeMcpLoopbackServer(), which tears down the process-wide MCP loopback HTTP server for the whole gateway. Any concurrent CLI turn or restart-recovered live session that already baked that loopback port into its --mcp-config is left pinned to a dead port ("Unable to connect"), while the gateway still reports the session as recovered. This is the same hazard the embedded-runner (run-loop.ts) and CLI dispatch (cli-backend-dispatch.ts) paths already avoid by retiring only session-scoped MCP runtimes. Retire only this run's session-scoped MCP runtime here too (by session key, with a session-id fallback), leaving the shared loopback server up for other sessions. Every CLI spawn/respawn already re-derives the current loopback port and rewrites mcp.json via prepareCliRunContext, so removing this teardown keeps recovered sessions on a live transport instead of stranding them. Fixes #98435 Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MMPjCgbgHTiB8X3R9XACPW
1 parent 21bfc75 commit 014d02a

2 files changed

Lines changed: 74 additions & 9 deletions

File tree

‎src/agents/cli-runner.before-agent-reply-cron.test.ts‎

Lines changed: 50 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ const {
3535
prepareCliRunContextMock,
3636
closeClaudeLiveSessionForContextMock,
3737
closeMcpLoopbackServerMock,
38+
retireSessionMcpRuntimeForSessionKeyMock,
39+
retireSessionMcpRuntimeMock,
3840
} = vi.hoisted(() => ({
3941
hasHooksMock: vi.fn<(hookName: string) => boolean>(() => false),
4042
runBeforeAgentReplyMock: vi.fn<(event: unknown, ctx: unknown) => Promise<BeforeAgentReplyResult>>(
@@ -46,6 +48,8 @@ const {
4648
prepareCliRunContextMock: vi.fn(),
4749
closeClaudeLiveSessionForContextMock: vi.fn(),
4850
closeMcpLoopbackServerMock: vi.fn(),
51+
retireSessionMcpRuntimeForSessionKeyMock: vi.fn(),
52+
retireSessionMcpRuntimeMock: vi.fn(),
4953
}));
5054

5155
vi.mock("../plugins/hook-runner-global.js", () => ({
@@ -74,6 +78,11 @@ vi.mock("../gateway/mcp-http.js", () => ({
7478
closeMcpLoopbackServer: closeMcpLoopbackServerMock,
7579
}));
7680

81+
vi.mock("./agent-bundle-mcp-tools.js", () => ({
82+
retireSessionMcpRuntimeForSessionKey: retireSessionMcpRuntimeForSessionKeyMock,
83+
retireSessionMcpRuntime: retireSessionMcpRuntimeMock,
84+
}));
85+
7786
const baseRunParams = {
7887
sessionId: "test-session",
7988
sessionKey: "test-session-key",
@@ -143,6 +152,10 @@ beforeEach(() => {
143152
);
144153
closeClaudeLiveSessionForContextMock.mockReset();
145154
closeMcpLoopbackServerMock.mockReset();
155+
retireSessionMcpRuntimeForSessionKeyMock.mockReset();
156+
retireSessionMcpRuntimeForSessionKeyMock.mockResolvedValue(true);
157+
retireSessionMcpRuntimeMock.mockReset();
158+
retireSessionMcpRuntimeMock.mockResolvedValue(true);
146159
});
147160

148161
beforeAll(async () => {
@@ -564,21 +577,46 @@ describe("runCliAgent before_agent_reply seam", () => {
564577
);
565578
});
566579

567-
it("can close temporary bundle MCP loopback resources after a run", async () => {
580+
it("retires only the run's session-scoped MCP runtime, not the process-wide loopback server", async () => {
581+
// Regression guard for #98435: closing the process-wide loopback server on
582+
// a single run's cleanup strands concurrent CLI turns and restart-recovered
583+
// sessions on a dead loopback port.
568584
executePreparedCliRunMock.mockResolvedValue({ text: "real reply" });
569585

570586
await runCliAgent({ ...baseRunParams, cleanupBundleMcpOnRunEnd: true });
571587

572588
expect(executePreparedCliRunMock).toHaveBeenCalledTimes(1);
573-
expect(closeMcpLoopbackServerMock).toHaveBeenCalledTimes(1);
589+
expect(retireSessionMcpRuntimeForSessionKeyMock).toHaveBeenCalledTimes(1);
590+
expect(retireSessionMcpRuntimeForSessionKeyMock).toHaveBeenCalledWith(
591+
expect.objectContaining({ sessionKey: "test-session-key", reason: "cli-run-end" }),
592+
);
593+
expect(closeMcpLoopbackServerMock).not.toHaveBeenCalled();
594+
});
595+
596+
it("falls back to sessionId retirement when the session key does not resolve", async () => {
597+
executePreparedCliRunMock.mockResolvedValue({ text: "real reply" });
598+
retireSessionMcpRuntimeForSessionKeyMock.mockResolvedValue(false);
599+
600+
await runCliAgent({ ...baseRunParams, cleanupBundleMcpOnRunEnd: true });
601+
602+
expect(retireSessionMcpRuntimeMock).toHaveBeenCalledTimes(1);
603+
expect(retireSessionMcpRuntimeMock).toHaveBeenCalledWith(
604+
expect.objectContaining({ sessionId: "test-session", reason: "cli-run-end" }),
605+
);
606+
expect(closeMcpLoopbackServerMock).not.toHaveBeenCalled();
574607
});
575608

576-
it("preserves confirmed delivery when bundle MCP cleanup fails", async () => {
609+
it("preserves confirmed delivery when session MCP retirement fails", async () => {
577610
executePreparedCliRunMock.mockResolvedValue({
578611
text: "",
579612
didSendViaMessagingTool: true,
580613
});
581-
closeMcpLoopbackServerMock.mockRejectedValue(new Error("loopback cleanup failed"));
614+
retireSessionMcpRuntimeForSessionKeyMock.mockImplementation(
615+
async ({ onError }: { onError?: (error: unknown) => void }) => {
616+
onError?.(new Error("session mcp retire failed"));
617+
return false;
618+
},
619+
);
582620

583621
await expect(
584622
runCliAgent({ ...baseRunParams, cleanupBundleMcpOnRunEnd: true }),
@@ -587,12 +625,17 @@ describe("runCliAgent before_agent_reply seam", () => {
587625
});
588626
});
589627

590-
it("surfaces bundle MCP cleanup failures when nothing was delivered", async () => {
628+
it("surfaces session MCP retirement failures when nothing was delivered", async () => {
591629
executePreparedCliRunMock.mockResolvedValue({ text: "real reply" });
592-
closeMcpLoopbackServerMock.mockRejectedValue(new Error("loopback cleanup failed"));
630+
retireSessionMcpRuntimeForSessionKeyMock.mockImplementation(
631+
async ({ onError }: { onError?: (error: unknown) => void }) => {
632+
onError?.(new Error("session mcp retire failed"));
633+
return false;
634+
},
635+
);
593636

594637
await expect(runCliAgent({ ...baseRunParams, cleanupBundleMcpOnRunEnd: true })).rejects.toThrow(
595-
"loopback cleanup failed",
638+
"session mcp retire failed",
596639
);
597640
});
598641
});

‎src/agents/cli-runner.ts‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -572,9 +572,31 @@ async function runCliAgentInternal(
572572
}
573573
}
574574
if (params.cleanupBundleMcpOnRunEnd === true) {
575+
// Retire only this run's session-scoped MCP runtime. Closing the
576+
// process-wide loopback server here would tear the MCP transport out from
577+
// under concurrent CLI turns and restart-recovered live sessions, leaving
578+
// them pinned to a dead loopback port (#98435). The embedded-runner and
579+
// CLI dispatch paths retire session-scoped runtimes for the same reason.
575580
try {
576-
const { closeMcpLoopbackServer } = await import("../gateway/mcp-http.js");
577-
await closeMcpLoopbackServer();
581+
const { retireSessionMcpRuntime, retireSessionMcpRuntimeForSessionKey } =
582+
await import("./agent-bundle-mcp-tools.js");
583+
let retireFailed = false;
584+
const onRetireError = (error: unknown) => {
585+
retireFailed = true;
586+
recordCleanupError(error);
587+
};
588+
const retiredBySessionKey = await retireSessionMcpRuntimeForSessionKey({
589+
sessionKey: params.sessionKey,
590+
reason: "cli-run-end",
591+
onError: onRetireError,
592+
});
593+
if (!retiredBySessionKey && !retireFailed) {
594+
await retireSessionMcpRuntime({
595+
sessionId: params.sessionId,
596+
reason: "cli-run-end",
597+
onError: onRetireError,
598+
});
599+
}
578600
} catch (error) {
579601
recordCleanupError(error);
580602
}

0 commit comments

Comments
 (0)