Skip to content

Commit 0c98518

Browse files
authored
Merge pull request #5014 from modelcontextprotocol/v2/fix/4986-everything-async-task-tools
fix(everything): keep async task tools within their client task (#4986, #4987)
2 parents 2ffc55c + 8c2cedb commit 0c98518

4 files changed

Lines changed: 94 additions & 23 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+
Fix the async task tools: `trigger-elicitation-request-async` now stops polling before the 10-minute TTL it requests for the client's task runs out, instead of polling past it and failing on a task the client has expired (#4986); and `trigger-sampling-request-async` reports the status message of a client task that is already finished when it is created, instead of "No message" (#4987). `trigger-elicitation-request-async` had the same flaw and gets the same fix.

‎src/everything/__tests__/tasks.test.ts‎

Lines changed: 56 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -422,18 +422,17 @@ describe("trigger-sampling-request-async", () => {
422422
);
423423
});
424424

425-
// KNOWN BUG #4987: trigger-sampling-request-async drops the status message of a task that is already finished when created; the fix changes this assertion.
426-
it("does not poll a client task that is already finished when it is created", async () => {
427-
// Characterization: the status message is only read from polls, so a
428-
// task that fails before it is returned is reported with "No message".
425+
it("reports the status message of a client task that is already finished when it is created", async () => {
426+
// A task that fails before it is returned is never polled, so its status
427+
// message comes from the CreateTaskResult.
429428
const { taskStore } = await connectTaskClient((_m, taskId) => {
430429
void taskStore.updateTaskStatus(taskId!, "failed", "instant failure");
431430
});
432431
const [text] = await callAsync("trigger-sampling-request-async", {
433432
prompt: "p",
434433
});
435434
expect(text).toMatch(
436-
/^\[FAILED\] No message\n\nProgress:\nTask created: \S+$/,
435+
/^\[FAILED\] instant failure\n\nProgress:\nTask created: \S+$/,
437436
);
438437
});
439438

@@ -569,6 +568,20 @@ describe("trigger-elicitation-request-async", () => {
569568
expect(polls).toHaveLength(4);
570569
});
571570

571+
it("reports the status message of a client task that is already finished when it is created", async () => {
572+
// A task that fails before it is returned is never polled, so its status
573+
// message comes from the CreateTaskResult.
574+
const { taskStore } = await connectTaskClient((_m, taskId) => {
575+
void taskStore.updateTaskStatus(taskId!, "failed", "instant failure");
576+
});
577+
const texts = await callAsync("trigger-elicitation-request-async");
578+
expect(texts).toEqual([
579+
expect.stringMatching(
580+
/^\[FAILED\] instant failure\n\nProgress:\nTask created: \S+$/,
581+
),
582+
]);
583+
});
584+
572585
it("reports a failed client task", async () => {
573586
const { taskStore } = await connectTaskClient((_m, taskId) => {
574587
later(() => taskStore.updateTaskStatus(taskId!, "failed"));
@@ -577,25 +590,54 @@ describe("trigger-elicitation-request-async", () => {
577590
expect(texts[0]).toMatch(/^\[FAILED\] No message\n\nProgress:\n/);
578591
});
579592

580-
it("gives up after 600 polls of a task that never finishes", async () => {
593+
/** Also fake `performance`, which the tool's polling deadline is measured with. */
594+
function fakeClock() {
595+
vi.useFakeTimers({
596+
toFake: ["setTimeout", "clearTimeout", "performance"],
597+
});
598+
}
599+
600+
it("gives up 5 seconds before the 10-minute TTL of a task that never finishes", async () => {
601+
fakeClock();
581602
// A client that keeps its task longer than the 10-minute TTL asked for.
582603
await connectTaskClient(() => {}, 60_000);
583604
const texts = await callAsync("trigger-elicitation-request-async");
584605
expect(texts[0]).toMatch(
585-
/^\[TIMEOUT\] Task timed out after 600 poll attempts\n\nProgress:\n/,
606+
/^\[TIMEOUT\] Task timed out after 595 poll attempts, before its 10-minute TTL expired\n\nProgress:\n/,
586607
);
587608
});
588609

589-
// KNOWN BUG #4986: trigger-elicitation-request-async polls for longer than the 10-minute TTL it requests for its task; the fix changes this assertion.
590-
it("fails on the last poll instead when the client honors the 10-minute TTL", async () => {
591-
// Characterization: 600 one-second polls outlast the 600000 ms TTL the
592-
// tool asks for, so a client that expires the task on time answers the
593-
// last tasks/get with "not found" and the call fails before the timeout
594-
// report.
610+
it("times out before a client that honors the 10-minute TTL expires the task", async () => {
611+
fakeClock();
612+
let created = "";
613+
const { taskStore } = await connectTaskClient((_m, taskId) => {
614+
created = taskId!;
615+
});
616+
const texts = await callAsync("trigger-elicitation-request-async");
617+
// The last poll reached the task while the client still held it.
618+
expect(texts).toHaveLength(1);
619+
expect(texts[0]).toMatch(
620+
/^\[TIMEOUT\] Task timed out after 595 poll attempts, before its 10-minute TTL expired\n\nProgress:\nTask created: \S+\nPoll 1: working\n/,
621+
);
622+
expect(texts[0]).toMatch(/\nPoll 595: working$/);
623+
// The client still holds the task when the tool gives up, 5 s before the
624+
// 600000 ms TTL it asked for runs out.
625+
expect((await taskStore.getTask(created))?.ttl).toBe(600000);
626+
});
627+
628+
it("times out without polling when its wait ends past the deadline", async () => {
629+
// A timer that fires late: the first reading sets the deadline, and every
630+
// later one is already past it.
631+
let readings = 0;
632+
vi.spyOn(performance, "now").mockImplementation(() =>
633+
readings++ === 0 ? 0 : 600_000,
634+
);
595635
await connectTaskClient(() => {});
596636
const texts = await callAsync("trigger-elicitation-request-async");
597637
expect(texts).toEqual([
598-
"MCP error -32602: MCP error -32602: Failed to retrieve task: Task not found",
638+
expect.stringMatching(
639+
/^\[TIMEOUT\] Task timed out after 0 poll attempts, before its 10-minute TTL expired\n\nProgress:\nTask created: \S+$/,
640+
),
599641
]);
600642
});
601643

‎src/everything/tools/trigger-elicitation-request-async.ts‎

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,12 @@ const config = {
2222
// Poll interval in milliseconds
2323
const POLL_INTERVAL = 1000;
2424

25-
// Maximum poll attempts before timeout (10 minutes for user input)
26-
const MAX_POLL_ATTEMPTS = 600;
25+
// Time-to-live requested for the client's task (10 minutes for user input)
26+
const TASK_TTL = 600000;
27+
28+
// Stop polling this long before the TTL runs out, so the last tasks/get
29+
// reaches the client while it still holds the task
30+
const TTL_SAFETY_MARGIN = 5000;
2731

2832
/**
2933
* Registers the 'trigger-elicitation-request-async' tool.
@@ -63,13 +67,19 @@ export const registerTriggerElicitationRequestAsyncTool = (
6367
name,
6468
config,
6569
async (args, extra): Promise<CallToolResult> => {
70+
// Polling must end before the client may expire the task. The client
71+
// starts the TTL when it creates the task, after this point, so a
72+
// deadline measured from here is conservative. performance.now() is
73+
// monotonic, so a wall-clock adjustment cannot stretch the deadline.
74+
const pollDeadline = performance.now() + TASK_TTL - TTL_SAFETY_MARGIN;
75+
6676
// Create the elicitation request WITH task metadata
6777
// Using z.any() schema to avoid complex type matching with _meta
6878
const request = {
6979
method: "elicitation/create" as const,
7080
params: {
7181
task: {
72-
ttl: 600000, // 10 minutes (user input may take a while)
82+
ttl: TASK_TTL, // 10 minutes (user input may take a while)
7383
},
7484
message:
7585
"Please provide inputs for the following fields (async task demo):",
@@ -147,16 +157,26 @@ export const registerTriggerElicitationRequestAsyncTool = (
147157
// Poll for task completion
148158
let attempts = 0;
149159
let taskStatus = elicitResponse.task.status;
150-
let taskStatusMessage: string | undefined;
160+
// A task that is already finished when created is never polled, so
161+
// its status message has to come from the CreateTaskResult
162+
let taskStatusMessage = elicitResponse.task.statusMessage;
163+
let timedOut = false;
151164

152165
while (
153166
taskStatus !== "completed" &&
154167
taskStatus !== "failed" &&
155-
taskStatus !== "cancelled" &&
156-
attempts < MAX_POLL_ATTEMPTS
168+
taskStatus !== "cancelled"
157169
) {
158170
// Wait before polling
159171
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL));
172+
173+
// Give up rather than poll past the TTL the task was created with.
174+
// Checked after the wait, so a timer that fires late cannot slip a
175+
// poll in after the deadline.
176+
if (performance.now() > pollDeadline) {
177+
timedOut = true;
178+
break;
179+
}
160180
attempts++;
161181

162182
// Get task status from client
@@ -189,12 +209,14 @@ export const registerTriggerElicitationRequestAsyncTool = (
189209
}
190210

191211
// Check for timeout
192-
if (attempts >= MAX_POLL_ATTEMPTS) {
212+
if (timedOut) {
193213
return {
194214
content: [
195215
{
196216
type: "text",
197-
text: `[TIMEOUT] Task timed out after ${MAX_POLL_ATTEMPTS} poll attempts\n\nProgress:\n${statusMessages.join(
217+
text: `[TIMEOUT] Task timed out after ${attempts} poll attempts, before its ${
218+
TASK_TTL / 60000
219+
}-minute TTL expired\n\nProgress:\n${statusMessages.join(
198220
"\n",
199221
)}`,
200222
},

‎src/everything/tools/trigger-sampling-request-async.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,9 @@ export const registerTriggerSamplingRequestAsyncTool = (server: McpServer) => {
147147
// Poll for task completion
148148
let attempts = 0;
149149
let taskStatus = samplingResponse.task.status;
150-
let taskStatusMessage: string | undefined;
150+
// A task that is already finished when created is never polled, so
151+
// its status message has to come from the CreateTaskResult
152+
let taskStatusMessage = samplingResponse.task.statusMessage;
151153

152154
while (
153155
taskStatus !== "completed" &&

0 commit comments

Comments
 (0)