Skip to content

Commit 7f3b522

Browse files
cliffhallclaude
andcommitted
fix: task timestamps, task capability gates, async form validation, stdio exit status
Copilot round 1 on #5131: - tasks: lastUpdatedAt is when the task entered its status (a stage reached, an answer or a cancel), not when a poll noticed it. - simulate-research-query asks for a clarification only from a form-capable client; trigger-elicitation-request-async needs form-mode elicitation and trigger-sampling-request-async needs sampling, since the SDK does not check the requests a task carries in its status. - trigger-elicitation-request-async validates an accepted answer against its form, and keeps waiting on one that does not fit. - All four stdio entry points set exit code 1 when the transport fails, since serveStdio reports a start failure through onerror, not a rejection. Part of #4852 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
1 parent 4735ab3 commit 7f3b522

13 files changed

Lines changed: 287 additions & 61 deletions

File tree

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ describe("stdio transport", () => {
103103
for (const listener of added) process.off("SIGINT", listener);
104104
});
105105

106-
it("reports a transport that cannot start on stderr", async () => {
106+
it("reports a transport that cannot start on stderr and in the exit status", async () => {
107107
const error = vi.spyOn(console, "error").mockImplementation(() => {});
108108
const broken = new PassThrough();
109109
broken.on = () => {
@@ -117,6 +117,9 @@ describe("stdio transport", () => {
117117
expect.objectContaining({ message: "stdin unavailable" }),
118118
),
119119
);
120+
// The failure is in the exit status too; reset it so the run is not failed.
121+
expect(process.exitCode).toBe(1);
122+
process.exitCode = undefined;
120123
for (const listener of process.listeners("SIGINT").slice(before)) {
121124
process.off("SIGINT", listener);
122125
}

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

Lines changed: 102 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,40 @@ describe("simulate-research-query", () => {
128128
expect(resultText(done)).toContain("Stage 4: Generating report ✓");
129129
});
130130

131+
it("reports when each status began, not when a poll noticed it", async () => {
132+
peer = await rawClient(TASKS);
133+
const created = await peer.call("simulate-research-query", { topic: "t" });
134+
const start = Date.now();
135+
// Polled long after it finished: the timestamp is the completion's.
136+
advance(STAGE_DURATION * STAGES.length * 3);
137+
const done = await peer.get(created.taskId as string);
138+
expect(done.status).toBe("completed");
139+
expect(done.lastUpdatedAt).toBe(
140+
new Date(start + STAGE_DURATION * STAGES.length).toISOString(),
141+
);
142+
});
143+
144+
it("reports the moment of a cancellation as the last update", async () => {
145+
peer = await rawClient(TASKS);
146+
const created = await peer.call("simulate-research-query", { topic: "t" });
147+
const taskId = created.taskId as string;
148+
advance(500);
149+
const cancelledAt = new Date(Date.now()).toISOString();
150+
await peer.result("tasks/cancel", { taskId });
151+
advance(STAGE_DURATION * 10);
152+
expect((await peer.get(taskId)).lastUpdatedAt).toBe(cancelledAt);
153+
});
154+
155+
it("does not ask a client that supports only URL-mode elicitation", async () => {
156+
peer = await rawClient({ ...TASKS, elicitation: { url: {} } });
157+
const created = await peer.call("simulate-research-query", {
158+
topic: "t",
159+
ambiguous: true,
160+
});
161+
advance(STAGE_DURATION * STAGES.length);
162+
expect((await peer.get(created.taskId as string)).status).toBe("completed");
163+
});
164+
131165
it("is a tool error for a client that does not declare the extension", async () => {
132166
peer = await rawClient({});
133167
const result = await peer.call("simulate-research-query", { topic: "t" });
@@ -373,6 +407,21 @@ describe("trigger-sampling-request-async", () => {
373407
expect(resultText(done)).toContain('"text": "hi"');
374408
});
375409

410+
it("is a tool error for a client that does not declare sampling", async () => {
411+
peer = await rawClient(TASKS);
412+
const result = await peer.call("trigger-sampling-request-async", {
413+
prompt: "p",
414+
});
415+
expect(result).toMatchObject({
416+
isError: true,
417+
content: [
418+
{
419+
text: "trigger-sampling-request-async asks the client for input, so it needs a client that declares the sampling capability.",
420+
},
421+
],
422+
});
423+
});
424+
376425
it("keeps waiting after an answer of the wrong kind", async () => {
377426
peer = await rawClient({ ...TASKS, sampling: {} });
378427
const created = await peer.call("trigger-sampling-request-async", {
@@ -432,9 +481,59 @@ describe("trigger-elicitation-request-async", () => {
432481
);
433482
});
434483

435-
it("summarizes an accepted answer with no fields", async () => {
436-
const done = await answer({ action: "accept", content: {} });
437-
expect(resultText(done)).toBe("Elicitation accept.");
484+
it("summarizes an accepted answer with only the required name", async () => {
485+
const done = await answer({ action: "accept", content: { name: "Ada" } });
486+
expect(resultText(done)).toBe("Elicitation accept.\nName: Ada");
487+
});
488+
489+
it("reports when the answer arrived as the last update", async () => {
490+
peer = await rawClient(WITH_ELICITATION);
491+
const created = await peer.call("trigger-elicitation-request-async");
492+
advance(1500);
493+
const answeredAt = new Date(Date.now()).toISOString();
494+
await peer.result("tasks/update", {
495+
taskId: created.taskId,
496+
inputResponses: { form: { action: "decline" } },
497+
});
498+
advance(60_000);
499+
expect((await peer.get(created.taskId as string)).lastUpdatedAt).toBe(
500+
answeredAt,
501+
);
502+
});
503+
504+
it.each([
505+
["no name", {}],
506+
["a blank name", { name: "" }],
507+
["a color that is not a choice", { name: "Ada", favoriteColor: "mauve" }],
508+
])(
509+
"keeps waiting after an accepted answer with %s",
510+
async (_label, content) => {
511+
peer = await rawClient(WITH_ELICITATION);
512+
const created = await peer.call("trigger-elicitation-request-async");
513+
await peer.result("tasks/update", {
514+
taskId: created.taskId,
515+
inputResponses: { form: { action: "accept", content } },
516+
});
517+
expect((await peer.get(created.taskId as string)).status).toBe(
518+
"input_required",
519+
);
520+
},
521+
);
522+
523+
it.each([
524+
["only the tasks extension", TASKS],
525+
["URL-mode elicitation only", { ...TASKS, elicitation: { url: {} } }],
526+
])("is a tool error for a client with %s", async (_label, capabilities) => {
527+
peer = await rawClient(capabilities);
528+
const result = await peer.call("trigger-elicitation-request-async");
529+
expect(result).toMatchObject({
530+
isError: true,
531+
content: [
532+
{
533+
text: "trigger-elicitation-request-async asks the client for input, so it needs a client that declares the elicitation (form mode) capability.",
534+
},
535+
],
536+
});
438537
});
439538

440539
it.each(["decline", "cancel"])("reports a %s", async (action) => {

‎src/everything/server/tasks.ts‎

Lines changed: 64 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,21 @@ export type TaskInputResponses = NonNullable<
5252
>;
5353

5454
/** What a task kind decides about its task at one moment. */
55-
export type TaskState =
55+
export type TaskState = (
5656
| { status: "working"; statusMessage: string }
5757
| {
5858
status: "input_required";
5959
statusMessage: string;
6060
inputRequests: InputRequests;
6161
}
62-
| { status: "completed"; statusMessage?: string; result: CallToolResult };
62+
| { status: "completed"; statusMessage?: string; result: CallToolResult }
63+
) & {
64+
/**
65+
* When the task entered this state (epoch milliseconds), reported as its
66+
* `lastUpdatedAt`: the moment it changed, not the moment a poll noticed.
67+
*/
68+
since: number;
69+
};
6370

6471
/**
6572
* One kind of task: how its status follows from the clock, and what it does
@@ -76,14 +83,11 @@ export type TaskBehavior = {
7683
type StoredTask = {
7784
taskId: string;
7885
createdAt: number;
79-
lastUpdatedAt: number;
8086
ttlMs: number;
8187
pollIntervalMs: number;
8288
behavior: TaskBehavior;
83-
/** Set once the client cancels; a cancelled task stays cancelled. */
84-
cancelled: boolean;
85-
/** The status last reported, so a change moves `lastUpdatedAt`. */
86-
lastStatus?: string;
89+
/** When the client cancelled it; a cancelled task stays cancelled. */
90+
cancelledAt?: number;
8791
};
8892

8993
/** Every live task, by id, across every server instance in the process. */
@@ -111,28 +115,34 @@ function find(taskId: string, now: number): StoredTask {
111115

112116
/** The task's state now, honoring a cancellation. */
113117
function stateOf(task: StoredTask, now: number): TaskState | CancelledState {
114-
return task.cancelled
115-
? { status: "cancelled", statusMessage: "Cancelled by the client" }
118+
return task.cancelledAt !== undefined
119+
? {
120+
status: "cancelled",
121+
statusMessage: "Cancelled by the client",
122+
since: task.cancelledAt,
123+
}
116124
: task.behavior.stateAt(now);
117125
}
118126

119-
type CancelledState = { status: "cancelled"; statusMessage: string };
127+
type CancelledState = {
128+
status: "cancelled";
129+
statusMessage: string;
130+
since: number;
131+
};
120132

121133
/** The wire form of a task (the `DetailedTask` of the extension's schema). */
122134
function describe(task: StoredTask, now: number): Record<string, unknown> {
123135
const state = stateOf(task, now);
124-
if (state.status !== task.lastStatus) {
125-
task.lastStatus = state.status;
126-
task.lastUpdatedAt = now;
127-
}
128136
return {
129137
taskId: task.taskId,
130138
status: state.status,
131139
...(state.statusMessage !== undefined && {
132140
statusMessage: state.statusMessage,
133141
}),
134142
createdAt: new Date(task.createdAt).toISOString(),
135-
lastUpdatedAt: new Date(task.lastUpdatedAt).toISOString(),
143+
lastUpdatedAt: new Date(
144+
Math.max(task.createdAt, state.since),
145+
).toISOString(),
136146
ttlMs: task.ttlMs,
137147
pollIntervalMs: task.pollIntervalMs,
138148
...(state.status === "input_required" && {
@@ -158,10 +168,8 @@ export function createTask(
158168
const task: StoredTask = {
159169
taskId: randomUUID(),
160170
createdAt: now,
161-
lastUpdatedAt: now,
162171
...options,
163172
behavior,
164-
cancelled: false,
165173
};
166174
tasks.set(task.taskId, task);
167175
// The SDK passes a tool result's `resultType` through to the wire on
@@ -185,6 +193,44 @@ export function clientCapabilitiesOf(
185193
return isObject(capabilities) ? capabilities : undefined;
186194
}
187195

196+
/**
197+
* Whether the client that sent this request supports form-mode elicitation:
198+
* `elicitation.form`, or an `elicitation` object with neither mode, which the
199+
* spec reads as form mode (#4985).
200+
*/
201+
export function clientSupportsFormElicitation(ctx: ServerContext): boolean {
202+
const elicitation = clientCapabilitiesOf(ctx)?.elicitation;
203+
return (
204+
isObject(elicitation) &&
205+
(elicitation.form !== undefined || elicitation.url === undefined)
206+
);
207+
}
208+
209+
/** Whether the client that sent this request supports sampling. */
210+
export function clientSupportsSampling(ctx: ServerContext): boolean {
211+
return clientCapabilitiesOf(ctx)?.sampling !== undefined;
212+
}
213+
214+
/**
215+
* The result for a task tool whose task would ask the client for input it
216+
* did not declare it can give. The SDK checks a tool's own input requests,
217+
* but not the ones a task carries in its status, so the tool checks here.
218+
*/
219+
export function capabilityRequired(
220+
name: string,
221+
capability: string,
222+
): CallToolResult {
223+
return {
224+
content: [
225+
{
226+
type: "text",
227+
text: `${name} asks the client for input, so it needs a client that declares the ${capability} capability.`,
228+
},
229+
],
230+
isError: true,
231+
};
232+
}
233+
188234
/**
189235
* Whether the client that sent this request declared the tasks extension, so
190236
* it can follow a task handle. A tool may answer with a task only then.
@@ -286,7 +332,7 @@ export function registerTasksExtension(server: McpServer): void {
286332
`Task ${taskId} is already ${status}`,
287333
);
288334
}
289-
task.cancelled = true;
335+
task.cancelledAt = now;
290336
return {};
291337
},
292338
);

‎src/everything/tools/simulate-research-query.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import {
2323
} from "@modelcontextprotocol/server";
2424
import { z } from "zod";
2525
import {
26-
clientCapabilitiesOf,
26+
clientSupportsFormElicitation,
2727
clientSupportsTasks,
2828
createTask,
2929
tasksRequired,
@@ -189,7 +189,8 @@ export const registerSimulateResearchQueryTool = (server: McpServer) => {
189189
async (args, ctx): Promise<CallToolResult> => {
190190
if (!clientSupportsTasks(ctx)) return tasksRequired(name);
191191
const { topic, ambiguous } = SimulateResearchQuerySchema.parse(args);
192-
const canAsk = clientCapabilitiesOf(ctx)?.elicitation !== undefined;
192+
// The clarification is a form, so only a form-capable client is asked.
193+
const canAsk = clientSupportsFormElicitation(ctx);
193194

194195
// The clock time the stages started counting from, and the stage they
195196
// started at: an ambiguous query restarts the count once it is answered.
@@ -204,8 +205,12 @@ export const registerSimulateResearchQueryTool = (server: McpServer) => {
204205
stateAt: (now): TaskState => {
205206
const stage =
206207
startStage + Math.floor((now - startedAt) / STAGE_DURATION);
208+
// When the clock reached `stage`, the moment the task entered it.
209+
const reached = (at: number) =>
210+
startedAt + (at - startStage) * STAGE_DURATION;
207211
if (needsClarification() && stage >= CLARIFY_AT) {
208212
return {
213+
since: reached(CLARIFY_AT),
209214
status: "input_required",
210215
statusMessage: `Found multiple interpretations for "${topic}". Requesting clarification...`,
211216
inputRequests: {
@@ -230,12 +235,14 @@ export const registerSimulateResearchQueryTool = (server: McpServer) => {
230235
}
231236
if (stage >= STAGES.length) {
232237
return {
238+
since: reached(STAGES.length),
233239
status: "completed",
234240
statusMessage: "Research complete",
235241
result: generateResearchReport(topic, clarification),
236242
};
237243
}
238244
return {
245+
since: reached(stage),
239246
status: "working",
240247
statusMessage:
241248
clarification !== undefined && stage === CLARIFY_AT

0 commit comments

Comments
 (0)