Skip to content

Commit 25b4a5d

Browse files
cliffhallclaude
andcommitted
fix(everything): stop a cancelled long-running operation
trigger-long-running-operation now waits each step on the request's abort signal, in both protocol eras. On cancellation (notifications/cancelled or the connection closing) its timer is cleared and the loop ends without sending further progress, so a cancelled call no longer holds a stdio server's process open. Closes modelcontextprotocol#1124 Closes modelcontextprotocol#4846 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit 25b4a5d

4 files changed

Lines changed: 171 additions & 4 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@modelcontextprotocol/server-everything": patch
3+
---
4+
5+
`trigger-long-running-operation` now honors cancellation in both protocol eras: a cancelled call clears its pending timer and sends no further progress, so it no longer delays stdio shutdown (#1124, #4846).
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
/**
2+
* Cancellation of `trigger-long-running-operation` (#1124, #4846).
3+
*
4+
* The tool waits on a timer per step. Before #4846 it ignored the request's
5+
* cancellation: a cancelled call kept stepping and sending progress, and its
6+
* pending timer held a stdio server's process open after the client went
7+
* away. Each case cancels a call from a real SDK client, in both protocol
8+
* eras.
9+
*
10+
* - Over the stdio transport manager on in-memory pipes, the server's raw
11+
* output is read, since the SDK client silently drops progress for a
12+
* request it has cancelled: no progress may cross the wire after the
13+
* cancel, and the session keeps serving.
14+
* - The step timer is what kept the process alive, and nothing on the wire
15+
* shows whether it is still pending, so `node:timers/promises` is wrapped
16+
* (calling through) to show the tool's wait is abandoned on the cancel.
17+
* That wait clears its own timer when its signal aborts.
18+
*/
19+
import { PassThrough } from "node:stream";
20+
import { afterEach, describe, expect, it, vi } from "vitest";
21+
import { Client } from "@modelcontextprotocol/client";
22+
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
23+
import { connect, connectModern, contentOf, textOf } from "./harness.js";
24+
import type { Session } from "./harness.js";
25+
import { main, type StdioSession } from "../transports/stdio.js";
26+
27+
const timers = vi.hoisted(() => ({
28+
sleeps: [] as Array<{ ms: number | undefined; settled: Promise<unknown> }>,
29+
}));
30+
31+
vi.mock("node:timers/promises", async (importOriginal) => {
32+
const actual = await importOriginal<typeof import("node:timers/promises")>();
33+
return {
34+
...actual,
35+
setTimeout: <T>(
36+
ms?: number,
37+
value?: T,
38+
options?: Parameters<typeof actual.setTimeout>[2],
39+
) => {
40+
const promise = actual.setTimeout(ms, value, options);
41+
timers.sleeps.push({
42+
ms,
43+
settled: promise.then(
44+
() => "elapsed",
45+
(error: unknown) => error,
46+
),
47+
});
48+
return promise;
49+
},
50+
};
51+
});
52+
53+
let session: Session | undefined;
54+
const started: StdioSession[] = [];
55+
56+
afterEach(async () => {
57+
timers.sleeps.length = 0;
58+
await session?.close();
59+
session = undefined;
60+
for (const { shutdown } of started.splice(0)) {
61+
process.off("SIGINT", shutdown);
62+
}
63+
});
64+
65+
const delay = (ms: number) =>
66+
new Promise<void>((resolve) => setTimeout(resolve, ms));
67+
68+
describe.each([
69+
["2025-era", {}],
70+
["2026-07-28", { versionNegotiation: { mode: { pin: "2026-07-28" } } }],
71+
] as const)("over stdio, a cancelled call (%s)", (_era, opts) => {
72+
it("sends no progress after the cancel, and the session keeps serving", async () => {
73+
const toServer = new PassThrough();
74+
const fromServer = new PassThrough();
75+
started.push(await main(toServer, fromServer));
76+
// Every line the server writes, read alongside the client's transport.
77+
let wire = "";
78+
fromServer.on("data", (chunk: Buffer) => {
79+
wire += chunk.toString();
80+
});
81+
const client = new Client({ name: "stdio-test", version: "0.0.0" }, opts);
82+
await client.connect(new StdioServerTransport(fromServer, toServer));
83+
84+
// Four 50 ms steps: uncancelled, the last progress lands at about 200 ms.
85+
const controller = new AbortController();
86+
const call = client.callTool(
87+
{
88+
name: "trigger-long-running-operation",
89+
arguments: { duration: 0.2, steps: 4 },
90+
},
91+
{
92+
signal: controller.signal,
93+
onprogress: () => controller.abort("cancelled by test"),
94+
},
95+
);
96+
await expect(call).rejects.toBeDefined();
97+
await delay(300);
98+
expect(wire.match(/"notifications\/progress"/g)).toHaveLength(1);
99+
100+
const echo = await client.callTool({
101+
name: "echo",
102+
arguments: { message: "after cancel" },
103+
});
104+
expect(echo.content).toEqual([
105+
{ type: "text", text: "Echo: after cancel" },
106+
]);
107+
await client.close();
108+
});
109+
});
110+
111+
describe.each([
112+
["2025-era", () => connect()],
113+
["2026-07-28", () => connectModern()],
114+
])("a cancelled call (%s)", (_era, open) => {
115+
it("abandons its pending step wait, so no timer holds the process open", async () => {
116+
session = await open();
117+
const controller = new AbortController();
118+
const call = session.client.callTool(
119+
{
120+
name: "trigger-long-running-operation",
121+
arguments: { duration: 20, steps: 2 },
122+
},
123+
{ signal: controller.signal },
124+
);
125+
await vi.waitFor(() => expect(timers.sleeps).toHaveLength(1));
126+
controller.abort("cancelled by test");
127+
await expect(call).rejects.toBeDefined();
128+
129+
// The 10 s wait settles at once, rejected by the abort, not elapsed.
130+
expect(timers.sleeps[0]?.ms).toBe(10_000);
131+
const outcome = await timers.sleeps[0]?.settled;
132+
expect(outcome).toMatchObject({ name: "AbortError" });
133+
// The loop stopped: no further step was scheduled.
134+
await delay(20);
135+
expect(timers.sleeps).toHaveLength(1);
136+
137+
const result = await session.client.callTool({
138+
name: "echo",
139+
arguments: { message: "still here" },
140+
});
141+
expect(textOf(contentOf(result)[0])).toBe("Echo: still here");
142+
});
143+
});

‎src/everything/docs/features.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ Each feature below is marked **both**, **2026-07-28** or **2025-era**. Roots, sa
4747
- `trigger-elicitation-request-async` (tools/trigger-elicitation-request-async.ts), **2026-07-28**: Runs as a task whose `input_required` status carries a form elicitation; the client answers with `tasks/update` and the task completes with a summary. Needs a client that declares the tasks extension and form-mode elicitation.
4848
- `trigger-list-changed` (tools/trigger-list-changed.ts), **both**: Sends `notifications/<list>/list_changed` for `tools`, `prompts` or `resources`: on 2026-07-28 to each `subscriptions/listen` stream that asked for that list, on a 2025-era connection unsolicited.
4949
- `trigger-log-messages` (tools/trigger-log-messages.ts), **both**, deprecated: Sends one log message at each level during the call. A 2026-07-28 request gets those at or above the level its `_meta` names (none if it names none); a 2025-era client those at or above its `logging/setLevel` level.
50-
- `trigger-long-running-operation` (tools/trigger-long-running-operation.ts), **both**: Simulates a multi-step operation over a given `duration` and number of `steps`; reports progress via `notifications/progress` when a `progressToken` is provided by the client.
50+
- `trigger-long-running-operation` (tools/trigger-long-running-operation.ts), **both**: Simulates a multi-step operation over a given `duration` and number of `steps`; reports progress via `notifications/progress` when a `progressToken` is provided by the client. Honors cancellation: a cancelled call clears its timer and sends no further progress.
5151
- `trigger-multi-step-elicitation` (tools/trigger-multi-step-elicitation.ts), **both**: Asks for a name, then for a favorite color addressed by that name, carrying the first answer to the second round in `requestState`. The state is HMAC-signed and expires after ten minutes; a tampered or expired one is refused with `-32602`. A blank name or a color that is not a choice is asked again. Needs form-mode elicitation.
5252
- `trigger-resource-update` (tools/trigger-resource-update.ts), **both**: Sends `notifications/resources/updated` for a URI: on 2026-07-28 to each listen stream whose `resourceSubscriptions` name it, on a 2025-era connection once the client has subscribed to it.
5353
- `trigger-sampling-request` (tools/trigger-sampling-request.ts), **both**, deprecated: Asks the client's LLM for a completion with a multi-round-trip request, using the provided `prompt` and `maxTokens`; returns the LLM's response payload. Needs client capability `sampling`.

‎src/everything/tools/trigger-long-running-operation.ts‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { setTimeout as sleep } from "node:timers/promises";
12
import { z } from "zod";
23
import { McpServer, CallToolResult } from "@modelcontextprotocol/server";
34

@@ -36,6 +37,11 @@ const config = {
3637
* At the end of the operation, the tool returns a message indicating the completion of the
3738
* operation, including the total duration and steps.
3839
*
40+
* The operation watches the request's abort signal, which the SDK fires when the client
41+
* sends `notifications/cancelled` or the connection closes, in either protocol era. On
42+
* cancellation it clears its pending timer and stops without sending further progress, so
43+
* a cancelled operation never holds the process open (#1124, #4846).
44+
*
3945
* @param {McpServer} server - The McpServer instance where the tool will be registered.
4046
*/
4147
export const registerTriggerLongRunningOperationTool = (server: McpServer) => {
@@ -47,11 +53,24 @@ export const registerTriggerLongRunningOperationTool = (server: McpServer) => {
4753
const { duration, steps } = validatedArgs;
4854
const stepDuration = duration / steps;
4955
const progressToken = ctx.mcpReq._meta?.progressToken;
56+
const signal = ctx.mcpReq.signal;
5057

5158
for (let i = 1; i < steps + 1; i++) {
52-
await new Promise((resolve) =>
53-
setTimeout(resolve, stepDuration * 1000),
54-
);
59+
try {
60+
// Rejects at once, clearing its timer, when the request is cancelled.
61+
await sleep(stepDuration * 1000, undefined, { signal });
62+
} catch {
63+
// The SDK drops the response to a cancelled request, so this result
64+
// never reaches the client; returning simply ends the handler.
65+
return {
66+
content: [
67+
{
68+
type: "text",
69+
text: `Long running operation cancelled after ${i - 1} of ${steps} steps.`,
70+
},
71+
],
72+
};
73+
}
5574

5675
if (progressToken !== undefined) {
5776
await server.server.notification(

0 commit comments

Comments
 (0)