Skip to content

Commit 3542dc7

Browse files
committed
feat(mcp): enhance MCP client and manager with cancellation support and timeout handling
1 parent 6d0ec9f commit 3542dc7

10 files changed

Lines changed: 386 additions & 57 deletions

File tree

‎packages/cli/src/tests/session-lifecycle.test.ts‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import React from "react";
88
import { SessionManager, type SessionMessage } from "@vegamo/deepcode-core";
99
import App from "../ui/views/App";
1010
import { terminal } from "./terminal-helper";
11+
import { McpClient } from "../../../core/src/mcp/mcp-client";
12+
import { MCP_TEST_SERVER } from "../../../core/src/tests/mcp-test-server";
1113

1214
function deferred() {
1315
let resolve!: () => void;
@@ -27,6 +29,7 @@ async function harness(
2729
fs.mkdirSync(path.join(root, ".deepcode"));
2830
fs.writeFileSync(path.join(root, ".deepcode", "settings.json"), JSON.stringify({ statusline: { enabled: false } }));
2931
const ref: { current?: SessionManager } = {};
32+
const initMcpServers = SessionManager.prototype.initMcpServers;
3033
t.mock.method(SessionManager.prototype, "initMcpServers", async function (this: SessionManager) {
3134
ref.current = this;
3235
Object.assign(this, {
@@ -59,6 +62,7 @@ async function harness(
5962
return {
6063
...h,
6164
manager,
65+
initMcpServers: initMcpServers.bind(manager),
6266
async submit(text: string) {
6367
await h.send(text);
6468
await h.send("\r");
@@ -153,11 +157,132 @@ for (const action of ["/exit", "Ctrl+D twice"] as const) {
153157
assert.equal(requestSignal.aborted, true);
154158
assert.equal(h.manager.isSessionRunning(id), true, "execution still owns the lock during cleanup");
155159
assert.deepEqual(disposedWhileRunning, []);
160+
assert.match(h.frame(), /Exiting…/);
156161
cleanup.resolve();
157162
await h.waitUntilExit();
158163
assert.ok(disposedWhileRunning.length > 0);
159164
assert.ok(disposedWhileRunning.every((running) => !running));
160165
assert.equal(requests, 1, "exiting must not start queued work");
161166
assert.equal(h.manager.getSession(id)?.status, "interrupted");
167+
assert.equal(h.rawMode(), false, "exit must restore terminal input mode");
168+
});
169+
170+
test(`${action} exits promptly during an unresponsive MCP call`, { timeout: 5000 }, async (t) => {
171+
const entered = deferred();
172+
const callTool = McpClient.prototype.callTool;
173+
let requestSignal: AbortSignal | undefined;
174+
t.mock.method(
175+
McpClient.prototype,
176+
"callTool",
177+
function (this: McpClient, ...args: Parameters<McpClient["callTool"]>) {
178+
requestSignal = args[3];
179+
const result = callTool.apply(this, args);
180+
entered.resolve();
181+
return result;
182+
}
183+
);
184+
let requests = 0;
185+
const h = await harness(t, () => {
186+
requests++;
187+
return {
188+
choices: [
189+
{
190+
message: {
191+
content: "",
192+
tool_calls: [{ id: "hang", type: "function", function: { name: "mcp__probe__hang", arguments: "{}" } }],
193+
},
194+
},
195+
],
196+
};
197+
});
198+
await h.initMcpServers({ probe: { command: process.execPath, args: ["-e", MCP_TEST_SERVER] } });
199+
await h.submit("call the MCP tool");
200+
await entered.promise;
201+
const id = h.manager.getActiveSessionId()!;
202+
h.manager.enqueuePrompt(id, { text: "queued input" });
203+
if (action === "/exit") await h.submit("/exit");
204+
else {
205+
await h.send("\x04");
206+
await h.send("\x04");
207+
}
208+
await h.waitUntilExit();
209+
assert.equal(requestSignal?.aborted, true);
210+
assert.equal(h.manager.isSessionRunning(id), false);
211+
assert.equal(h.manager.getSession(id)?.status, "interrupted");
212+
assert.equal(requests, 1);
213+
assert.equal(h.rawMode(), false);
214+
});
215+
216+
test(`${action} exits after five seconds even if execution ignores cancellation`, { timeout: 12000 }, async (t) => {
217+
const entered = deferred();
218+
const cleanup = deferred();
219+
t.after(() => cleanup.resolve());
220+
let requests = 0;
221+
const h = await harness(t, async (_messages, signal) => {
222+
requests++;
223+
entered.resolve();
224+
await cleanup.promise;
225+
signal.throwIfAborted();
226+
});
227+
await h.submit("keep working");
228+
await entered.promise;
229+
const id = h.manager.getActiveSessionId()!;
230+
h.manager.enqueuePrompt(id, { text: "queued input" });
231+
const disposedWhileRunning: boolean[] = [];
232+
const dispose = h.manager.dispose.bind(h.manager);
233+
t.mock.method(h.manager, "dispose", () => {
234+
disposedWhileRunning.push(h.manager.isSessionRunning(id));
235+
dispose();
236+
});
237+
const started = performance.now();
238+
if (action === "/exit") await h.submit("/exit");
239+
else {
240+
await h.send("\x04");
241+
await h.send("\x04");
242+
}
243+
assert.match(h.frame(), /Exiting…/);
244+
assert.deepEqual(disposedWhileRunning, []);
245+
await h.waitUntilExit();
246+
assert.ok(performance.now() - started >= 5_000, "allow five seconds for cleanup");
247+
assert.ok(performance.now() - started < 8_000, "do not wait indefinitely for execution");
248+
assert.equal(disposedWhileRunning[0], true);
249+
assert.equal(requests, 1);
250+
assert.equal(h.rawMode(), false);
162251
});
163252
}
253+
254+
test("exit restores the terminal even if resource cleanup throws", { timeout: 5000 }, async (t) => {
255+
const h = await harness(t, () => ({ choices: [{ message: { content: "done" } }] }));
256+
assert.equal(h.rawMode(), true);
257+
const mocked = t.mock.method(h.manager, "dispose", () => {
258+
throw new Error("cleanup failed");
259+
});
260+
try {
261+
await h.submit("/exit");
262+
await h.waitUntilExit();
263+
assert.equal(h.rawMode(), false);
264+
} finally {
265+
mocked.mock.restore();
266+
}
267+
});
268+
269+
test("exit restores the terminal even if printing the summary throws", { timeout: 5000 }, async (t) => {
270+
const h = await harness(t, () => ({ choices: [{ message: { content: "done" } }] }));
271+
const write = process.stdout.write;
272+
let failed = false;
273+
const mocked = t.mock.method(process.stdout, "write", function (...args: Parameters<typeof write>) {
274+
if (typeof args[0] === "string" && args[0].includes("Goodbye!")) {
275+
failed = true;
276+
throw new Error("output failed");
277+
}
278+
return write.apply(process.stdout, args);
279+
});
280+
try {
281+
await h.submit("/exit");
282+
await h.waitUntilExit();
283+
assert.equal(failed, true);
284+
assert.equal(h.rawMode(), false);
285+
} finally {
286+
mocked.mock.restore();
287+
}
288+
});

‎packages/cli/src/tests/terminal-helper.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,15 @@ import { render } from "ink";
88
export async function terminal(t: TestContext, element: React.ReactElement, columns = 80) {
99
let frame = "";
1010
let rawFrame = "";
11-
const stdin = Object.assign(new PassThrough(), { isTTY: true, setRawMode() {}, ref() {}, unref() {} });
11+
let rawMode = false;
12+
const stdin = Object.assign(new PassThrough(), {
13+
isTTY: true,
14+
setRawMode(value: boolean) {
15+
rawMode = value;
16+
},
17+
ref() {},
18+
unref() {},
19+
});
1220
const stdout = Object.assign(
1321
new Writable({
1422
write(chunk, _encoding, done) {
@@ -43,6 +51,7 @@ export async function terminal(t: TestContext, element: React.ReactElement, colu
4351
return {
4452
frame: () => frame,
4553
rawFrame: () => rawFrame,
54+
rawMode: () => rawMode,
4655
rerender: app.rerender,
4756
waitUntilExit: app.waitUntilExit,
4857
async send(input: string) {

‎packages/cli/src/ui/views/App.tsx‎

Lines changed: 57 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ function App({
126126
} | null>(null);
127127
const [dismissedQuestionIds, setDismissedQuestionIds] = useState<Set<string>>(() => new Set());
128128
const [isExiting, setIsExiting] = useState(false);
129+
const exitingRef = useRef(false);
129130
const [showWelcome, setShowWelcome] = useState(true);
130131
const [welcomeNonce, setWelcomeNonce] = useState(0);
131132
const [resolvedSettings, setResolvedSettings] = useState(() => resolveCurrentSettings(projectRoot, settingsFile));
@@ -401,47 +402,71 @@ function App({
401402
return () => {
402403
compactionControllerRef.current?.abort();
403404
compactionControllerRef.current = null;
404-
sessionManager.dispose();
405+
try {
406+
sessionManager.dispose();
407+
} catch {
408+
// Cleanup errors must not prevent Ink from restoring the terminal.
409+
}
405410
};
406411
}, [sessionManager]);
407412

408413
writeRef.current = write;
409414
const handleExit = useCallback(
410415
async ({ showCommand, showSummary }: { showCommand: boolean; showSummary: boolean }) => {
411-
compactionControllerRef.current?.abort();
412-
compactionControllerRef.current = null;
416+
if (exitingRef.current) return;
417+
exitingRef.current = true;
413418
setIsExiting(true);
414-
const sessionId = sessionManager.getActiveSessionId();
415-
if (sessionId && sessionManager.isSessionRunning(sessionId)) {
416-
sessionManager.interruptSession(sessionId);
417-
await sessionManager.waitForSessionIdle(sessionId).catch(() => {});
419+
let timer: ReturnType<typeof setTimeout> | undefined;
420+
try {
421+
compactionControllerRef.current?.abort();
422+
compactionControllerRef.current = null;
423+
const sessionId = sessionManager.getActiveSessionId();
424+
if (sessionId && sessionManager.isSessionRunning(sessionId)) {
425+
const deadline = new Promise<void>((resolve) => {
426+
timer = setTimeout(resolve, 5_000);
427+
});
428+
sessionManager.interruptSession(sessionId);
429+
await Promise.race([sessionManager.waitForSessionIdle(sessionId), deadline]);
430+
}
431+
} catch {
432+
// Exit even when interruption or session cleanup fails.
433+
} finally {
434+
clearTimeout(timer);
418435
}
419436
setTimeout(() => {
420-
const activeSessionId = sessionManager.getActiveSessionId();
421-
const session = activeSessionId ? sessionManager.getSession(activeSessionId) : null;
422-
const resumeHint = buildResumeHintText(activeSessionId ?? undefined);
423-
const rateLimitHint = buildPluginRateLimitHintText(session);
437+
try {
438+
const activeSessionId = sessionManager.getActiveSessionId();
439+
const session = activeSessionId ? sessionManager.getSession(activeSessionId) : null;
440+
const resumeHint = buildResumeHintText(activeSessionId ?? undefined);
441+
const rateLimitHint = buildPluginRateLimitHintText(session);
424442

425-
writeStdoutLine("\n");
426-
if (showCommand) {
427-
writeStdoutLine(chalk.rgb(34, 154, 195)(" > /exit "));
428-
writeStdoutLine("\n");
429-
}
430-
if (showSummary) {
431-
const summary = buildExitSummaryText({ session, sessionId: activeSessionId ?? undefined });
432-
writeStdoutLine(summary);
433443
writeStdoutLine("\n");
434-
}
435-
if (resumeHint) {
436-
writeStdoutLine(resumeHint);
437-
if (rateLimitHint) {
438-
writeStdoutLine(rateLimitHint);
444+
if (showCommand) {
445+
writeStdoutLine(chalk.rgb(34, 154, 195)(" > /exit "));
446+
writeStdoutLine("\n");
439447
}
440-
writeStdoutLine("\n");
448+
if (showSummary) {
449+
const summary = buildExitSummaryText({ session, sessionId: activeSessionId ?? undefined });
450+
writeStdoutLine(summary);
451+
writeStdoutLine("\n");
452+
}
453+
if (resumeHint) {
454+
writeStdoutLine(resumeHint);
455+
if (rateLimitHint) {
456+
writeStdoutLine(rateLimitHint);
457+
}
458+
writeStdoutLine("\n");
459+
}
460+
} catch {
461+
// Printing the summary is best effort during shutdown.
462+
}
463+
try {
464+
sessionManager.dispose();
465+
} catch {
466+
// Remaining handles are closed when the CLI process exits.
467+
} finally {
468+
exit();
441469
}
442-
443-
sessionManager.dispose();
444-
exit();
445470
}, 0);
446471
},
447472
[exit, sessionManager]
@@ -1312,7 +1337,9 @@ function App({
13121337
<Text color="red">Error: {errorLine}</Text>
13131338
</Box>
13141339
) : null}
1315-
{showProcessStdout ? (
1340+
{isExiting ? (
1341+
<Text dimColor>Exiting…</Text>
1342+
) : showProcessStdout ? (
13161343
<ProcessStdoutView
13171344
key={activeSessionId}
13181345
items={processOutputItems}
@@ -1380,7 +1407,7 @@ function App({
13801407
/>
13811408
) : pendingPlanImplementation && !busy && !editingQueue ? (
13821409
<PlanImplementationPrompt onSelect={handlePlanImplementationChoice} />
1383-
) : isExiting ? null : (
1410+
) : (
13841411
<PromptInput
13851412
key={sessionManager.getActiveSessionId() ?? "new"}
13861413
projectRoot={projectRoot}

‎packages/core/src/common/process-tree.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { spawnSync } from "child_process";
33
type TaskkillSpawnSync = (
44
command: string,
55
args: string[],
6-
options: { stdio: "ignore"; windowsHide: true }
6+
options: { stdio: "ignore"; windowsHide: true; timeout: number; killSignal: "SIGKILL" }
77
) => { status: number | null; error?: Error };
88

99
export type KillProcessTreeDeps = {
@@ -43,6 +43,8 @@ export function runWindowsTaskkill(pid: number, spawnSyncImpl: TaskkillSpawnSync
4343
const result = spawnSyncImpl("taskkill", ["/PID", String(pid), "/T", "/F"], {
4444
stdio: "ignore",
4545
windowsHide: true,
46+
timeout: 1_000,
47+
killSignal: "SIGKILL",
4648
});
4749
return !result.error && result.status === 0;
4850
}

0 commit comments

Comments
 (0)