@casys/mcp-server 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1014 @@
1
+ /**
2
+ * Tasks extension — server-side store (io.modelcontextprotocol/tasks, SEP-2663).
3
+ *
4
+ * Implements the background-task lifecycle defined by the spec 2026-07-28
5
+ * experimental extension: spawning, polling, client-input handshake, and
6
+ * cooperative cancellation.
7
+ *
8
+ * **Pure module** — no framework imports, no HTTP. Everything here is
9
+ * testable by constructing a `TaskStore` directly and calling its methods.
10
+ * The shape mirrors `request-headers.ts`: all spec-derived rules live here,
11
+ * the transport layer only calls `spawn / get / update / cancel`.
12
+ *
13
+ * @module lib/server/tasks/task-store
14
+ */
15
+ import { METHOD_TO_CAPABILITY } from "../mrtr/capability-check.js";
16
+
17
+ // ── Entropy ──────────────────────────────────────────────────────────────────
18
+
19
+ /**
20
+ * Produce a cryptographically-random task ID.
21
+ *
22
+ * 128 bits of entropy (32 lowercase hex chars). Spec §Security Considerations:
23
+ * "Task IDs MUST be generated with sufficient entropy that a third party cannot
24
+ * enumerate or guess them." 128 bits satisfies that at the same level as a
25
+ * UUID v4 but without the version/variant bits that reduce its effective
26
+ * entropy to 122 bits.
27
+ */
28
+ export function generateTaskId(): string {
29
+ const bytes = new Uint8Array(16);
30
+ crypto.getRandomValues(bytes);
31
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
32
+ }
33
+
34
+ // ── Public types ──────────────────────────────────────────────────────────────
35
+
36
+ /**
37
+ * Options a tool handler provides when opting into async-task mode.
38
+ *
39
+ * All fields are optional; `TaskStore` fills defaults from its own options.
40
+ */
41
+ export interface CreateTaskOptions {
42
+ /**
43
+ * TTL in ms from creation. `null` = no expiry (held until maxTasks eviction).
44
+ * Spec is silent on a default — callers omit this to get the store default.
45
+ */
46
+ ttlMs?: number | null;
47
+ /**
48
+ * Hint to the client: how often to call tasks/get (ms).
49
+ * Spec §Task Polling: clients SHOULD respect this.
50
+ * Default chosen as 5 000 ms — practical minimum that avoids hammering the
51
+ * server without causing noticeable delays on human-facing workflows.
52
+ */
53
+ pollIntervalMs?: number;
54
+ /** Human-readable description of the initial working state. */
55
+ statusMessage?: string;
56
+ }
57
+
58
+ /**
59
+ * One outstanding server-to-client request, registered in `inputRequests`.
60
+ *
61
+ * Shape is intentionally minimal: it mirrors the spec's `InputRequest` type
62
+ * (method + params). The protocol is open-ended — concrete method names are
63
+ * defined per-extension (e.g. `sampling/createMessage`).
64
+ */
65
+ export interface InputRequest {
66
+ readonly method: string;
67
+ readonly params: Record<string, unknown>;
68
+ }
69
+
70
+ /**
71
+ * Interface the running task's work function uses to interact with the store.
72
+ *
73
+ * Design rule: `TaskController` is never stored by the framework after the
74
+ * `run()` promise settles. Tool handlers MUST NOT hold it past the promise.
75
+ */
76
+ export interface TaskController {
77
+ /**
78
+ * Block the running work until the client delivers a response for `key`.
79
+ *
80
+ * Registers the request under `key` in `inputRequests` (moves task to
81
+ * `input_required`) and resolves with the client-provided response when
82
+ * `tasks/update` carries that key.
83
+ *
84
+ * Rejects with `DOMException("Task was cancelled", "AbortError")` if the
85
+ * task is cancelled while waiting.
86
+ *
87
+ * Spec §Task Update Requests: "Each inputRequests key MUST be unique over
88
+ * the entire lifetime of a single task. Server MUST NOT reuse a key after
89
+ * a response for that key has been delivered."
90
+ */
91
+ requireInput(
92
+ key: string,
93
+ request: InputRequest,
94
+ ): Promise<Record<string, unknown>>;
95
+
96
+ /** Update the status message visible on the next tasks/get. */
97
+ setStatusMessage(msg: string): void;
98
+
99
+ /**
100
+ * AbortSignal that fires when tasks/cancel is received.
101
+ * Long-running work SHOULD check this to short-circuit early.
102
+ * Spec: cancellation is cooperative — the task may still finish normally.
103
+ */
104
+ readonly signal: AbortSignal;
105
+ }
106
+
107
+ /**
108
+ * Discriminated return value: a tool handler returns this to ask the framework
109
+ * to materialise an async task instead of a synchronous result.
110
+ *
111
+ * Use `createTask()` to construct; do not build this object manually — the
112
+ * `_type` discriminant is what `isAsyncTaskDescriptor()` keys on.
113
+ */
114
+ export interface AsyncTaskDescriptor {
115
+ readonly _type: "async-task";
116
+ readonly options: CreateTaskOptions;
117
+ /**
118
+ * Background work. Return value becomes `CompletedTask.result`.
119
+ *
120
+ * To signal a protocol-level failure (→ `FailedTask`), throw an object with
121
+ * `{ code: number; message: string }`. This mirrors JSON-RPC error shape and
122
+ * is the spec's definition of the `failed` status.
123
+ *
124
+ * A tool-level business error (the ERPNext equivalent of "order not found")
125
+ * MUST NOT throw — it should be returned as part of the normal result, which
126
+ * reaches `completed`. Spec: "The 'failed' status MUST NOT be used for
127
+ * non-JSON-RPC errors. A tool result with isError: true reaches 'completed',
128
+ * not 'failed'."
129
+ */
130
+ readonly run: (ctrl: TaskController) => Promise<unknown>;
131
+ }
132
+
133
+ // ── Task shapes (mirroring spec TypeScript interfaces) ───────────────────────
134
+
135
+ /** Base fields shared by every task shape. */
136
+ export interface Task {
137
+ taskId: string;
138
+ status: "working" | "input_required" | "completed" | "cancelled" | "failed";
139
+ statusMessage?: string;
140
+ createdAt: string; // ISO 8601
141
+ lastUpdatedAt: string; // ISO 8601
142
+ ttlMs: number | null;
143
+ pollIntervalMs?: number;
144
+ }
145
+
146
+ export interface WorkingTask extends Task {
147
+ status: "working";
148
+ }
149
+
150
+ export interface InputRequiredTask extends Task {
151
+ status: "input_required";
152
+ /** All outstanding server-to-client requests, keyed by a unique caller-chosen identifier. */
153
+ inputRequests: Record<string, InputRequest>;
154
+ }
155
+
156
+ export interface CompletedTask extends Task {
157
+ status: "completed";
158
+ result: Record<string, unknown>;
159
+ }
160
+
161
+ export interface FailedTask extends Task {
162
+ status: "failed";
163
+ error: Record<string, unknown>;
164
+ }
165
+
166
+ export interface CancelledTask extends Task {
167
+ status: "cancelled";
168
+ }
169
+
170
+ /** Discriminated union of all possible task states. */
171
+ export type DetailedTask =
172
+ | WorkingTask
173
+ | InputRequiredTask
174
+ | CompletedTask
175
+ | FailedTask
176
+ | CancelledTask;
177
+
178
+ /**
179
+ * Fields returned as the initial result when tools/call spawns a task.
180
+ *
181
+ * `resultType: "task"` is added by the transport layer (NOT by stampResult —
182
+ * stampResult always sets `"complete"`, and CreateTaskResult requires `"task"`.
183
+ * The caller builds the response manually; see integration instructions.)
184
+ */
185
+ export type CreateTaskResultFields = Task;
186
+
187
+ // ── TaskStore options ─────────────────────────────────────────────────────────
188
+
189
+ export interface TaskStoreOptions {
190
+ /**
191
+ * Default TTL for tasks whose handler did not provide one.
192
+ *
193
+ * Spec is silent. 3 600 000 ms (1 h) chosen because it's long enough for
194
+ * realistic ERPNext whole-table scans (stock treemap, revenue aggregations)
195
+ * but short enough to bound memory in a long-running server.
196
+ */
197
+ defaultTtlMs: number;
198
+
199
+ /**
200
+ * Hard cap on stored tasks (terminal + non-terminal combined).
201
+ *
202
+ * Spec is silent. 5 000 chosen as half the session cap (10 000) since each
203
+ * task can carry an arbitrarily large `result` payload, so the per-entry
204
+ * cost is higher than a session entry.
205
+ *
206
+ * Eviction order when the cap is reached: terminal tasks first (by
207
+ * `terminalAt`, oldest first), then oldest non-terminal by `createdAt`.
208
+ * Terminal tasks have already served their purpose; evicting them first is
209
+ * the least-harmful policy.
210
+ */
211
+ maxTasks: number;
212
+
213
+ /**
214
+ * How often to sweep tasks for TTL expiry.
215
+ *
216
+ * Piggybacking on the same 5-minute rhythm as the session cleanup in
217
+ * McpApp keeps operational patterns consistent. Not exposed to callers
218
+ * as a tunable because the appropriate value tracks the session timer.
219
+ */
220
+ cleanupIntervalMs: number;
221
+
222
+ /**
223
+ * Optional callback invoked on every status transition.
224
+ *
225
+ * Intended as the wiring point for Track G (subscriptions/listen): once
226
+ * that lands, the subscription layer registers here and the TaskStore
227
+ * drives notifications without knowing about SSE or HTTP. No-op until
228
+ * Track G ships.
229
+ */
230
+ onNotification?: (task: DetailedTask) => void;
231
+
232
+ /**
233
+ * Runtime hook to unref the sweep timer, so it cannot hold the process open.
234
+ *
235
+ * Injected rather than imported: the store is runtime-agnostic, and Deno and
236
+ * Node expose different mechanisms for this.
237
+ */
238
+ unrefTimer?: (id: ReturnType<typeof setInterval>) => void;
239
+ }
240
+
241
+ // ── Private internal representation ──────────────────────────────────────────
242
+
243
+ /** Terminal statuses — once in one of these, no further transitions occur. */
244
+ const TERMINAL_STATUSES = new Set<string>([
245
+ "completed",
246
+ "cancelled",
247
+ "failed",
248
+ ]);
249
+
250
+ function isTerminal(
251
+ status: "working" | "input_required" | "completed" | "cancelled" | "failed",
252
+ ): boolean {
253
+ return TERMINAL_STATUSES.has(status);
254
+ }
255
+
256
+ /**
257
+ * Internal representation of a running task.
258
+ * Not exported — callers get `DetailedTask` snapshots via `get()`.
259
+ */
260
+ interface InternalTask {
261
+ taskId: string;
262
+ /**
263
+ * Principal that created the task.
264
+ *
265
+ * The spec requires an authorization check on every task-related request. A
266
+ * task id is an unguessable bearer token, but that alone is one line of
267
+ * defence: any caller who learns an id could otherwise read, answer or cancel
268
+ * another caller's task. Comparing the owner closes that.
269
+ */
270
+ owner: string;
271
+ status: "working" | "input_required" | "completed" | "cancelled" | "failed";
272
+ statusMessage?: string;
273
+ createdAt: string;
274
+ lastUpdatedAt: string;
275
+ ttlMs: number | null;
276
+ pollIntervalMs?: number;
277
+
278
+ abortController: AbortController;
279
+ /** Settled when run() completes; attached for drain() / observability. */
280
+ runPromise: Promise<void>;
281
+
282
+ /**
283
+ * Outstanding server-to-client input requests.
284
+ *
285
+ * Present for all statuses so snapshot reads don't need a null-check.
286
+ * Non-empty only when status === "input_required".
287
+ */
288
+ inputRequests: Map<string, InputRequest>;
289
+
290
+ /**
291
+ * Keys that have been answered by the client.
292
+ *
293
+ * Spec §Task Update Requests: "Server MUST NOT reuse a key after a
294
+ * response for that key has been delivered." Enforced in requireInput().
295
+ */
296
+ answeredKeys: Set<string>;
297
+
298
+ /**
299
+ * Pending resolvers waiting for the client's response.
300
+ * Parallel to `inputRequests`: one entry per outstanding requireInput() call.
301
+ */
302
+ pendingResolvers: Map<string, (response: Record<string, unknown>) => void>;
303
+
304
+ /** Set when status === "completed". */
305
+ result?: Record<string, unknown>;
306
+ /** Set when status === "failed". */
307
+ error?: Record<string, unknown>;
308
+ /** Unix timestamp (ms) when the task entered a terminal state. Used for eviction ordering. */
309
+ terminalAt?: number;
310
+ }
311
+
312
+ // ── Helpers ───────────────────────────────────────────────────────────────────
313
+
314
+ /** Narrow a value to a plain object (not null, not array). */
315
+ function isRecord(v: unknown): v is Record<string, unknown> {
316
+ return typeof v === "object" && v !== null && !Array.isArray(v);
317
+ }
318
+
319
+ /**
320
+ * Reduce a task input request to the exact JSON shape the task snapshot will
321
+ * expose, then verify the required InputRequest fields on that shape.
322
+ *
323
+ * Task handlers are TypeScript callers, but a JavaScript handler (or an `any`
324
+ * escape hatch) can pass any value here. Storing it first was unsafe: a non-string
325
+ * key could throw only when a later tasks/get built its snapshot, and `null`
326
+ * requests were emitted as invalid protocol objects. Canonicalising once at the
327
+ * boundary keeps the stored value and the wire value identical.
328
+ */
329
+ function canonicaliseTaskInputRequest(
330
+ key: unknown,
331
+ request: unknown,
332
+ ):
333
+ | { ok: true; key: string; request: InputRequest }
334
+ | { ok: false; message: string } {
335
+ if (typeof key !== "string") {
336
+ return {
337
+ ok: false,
338
+ message: "Invalid task input request key: expected a string.",
339
+ };
340
+ }
341
+
342
+ let canonical: unknown;
343
+ try {
344
+ const serialised = JSON.stringify(request);
345
+ if (serialised === undefined) throw new Error("not JSON-serialisable");
346
+ canonical = JSON.parse(serialised);
347
+ } catch {
348
+ return {
349
+ ok: false,
350
+ message:
351
+ "Invalid task input request: it must be a JSON-serialisable object with a string method and object params.",
352
+ };
353
+ }
354
+
355
+ if (
356
+ !isRecord(canonical) || typeof canonical["method"] !== "string" ||
357
+ !isRecord(canonical["params"])
358
+ ) {
359
+ return {
360
+ ok: false,
361
+ message:
362
+ "Invalid task input request: expected an object with a string method and object params.",
363
+ };
364
+ }
365
+
366
+ // The method must be one a client can actually service. Accepting any string let
367
+ // a task ask for something like `client/request`, for which no client has a
368
+ // handler — so the task STRANDS in `input_required` forever instead of failing.
369
+ // A stranded task is worse than a failed one: it consumes a poll loop and never
370
+ // resolves. Same grammar as MRTR, from the same table, so the two boundaries
371
+ // cannot drift apart.
372
+ if (!Object.hasOwn(METHOD_TO_CAPABILITY, canonical["method"])) {
373
+ return {
374
+ ok: false,
375
+ message: `Invalid task input request: unsupported method "${
376
+ canonical["method"]
377
+ }". Permitted: ${Object.keys(METHOD_TO_CAPABILITY).join(", ")}.`,
378
+ };
379
+ }
380
+
381
+ return {
382
+ ok: true,
383
+ key,
384
+ request: canonical as unknown as InputRequest,
385
+ };
386
+ }
387
+
388
+ /**
389
+ * Determine whether a thrown value looks like a JSON-RPC error.
390
+ *
391
+ * Spec: "The 'failed' status MUST NOT be used for non-JSON-RPC errors."
392
+ * A JSON-RPC error must have `code` (integer) and `message` (string).
393
+ * Tool handlers that want to signal `failed` throw exactly this shape.
394
+ */
395
+ function isJsonRpcError(v: unknown): v is { code: number; message: string } {
396
+ return isRecord(v) && typeof v["code"] === "number" &&
397
+ Number.isInteger(v["code"]) && typeof v["message"] === "string";
398
+ }
399
+
400
+ /**
401
+ * Convert internal task state to the spec's public DetailedTask shape.
402
+ *
403
+ * This is the only place where the internal Map is converted to a Record
404
+ * for the `inputRequests` field — keeping the internal representation as a
405
+ * Map avoids O(n) conversions on every requireInput/update call.
406
+ */
407
+ function toDetailedTask(internal: InternalTask): DetailedTask {
408
+ const base: Task = {
409
+ taskId: internal.taskId,
410
+ status: internal.status,
411
+ createdAt: internal.createdAt,
412
+ lastUpdatedAt: internal.lastUpdatedAt,
413
+ ttlMs: internal.ttlMs,
414
+ ...(internal.statusMessage !== undefined
415
+ ? { statusMessage: internal.statusMessage }
416
+ : {}),
417
+ ...(internal.pollIntervalMs !== undefined
418
+ ? { pollIntervalMs: internal.pollIntervalMs }
419
+ : {}),
420
+ };
421
+
422
+ switch (internal.status) {
423
+ case "working":
424
+ return { ...base, status: "working" };
425
+ case "input_required": {
426
+ // Object.fromEntries creates own data properties even for `__proto__`,
427
+ // `constructor`, and `toString`. Assigning those keys to `{}` can mutate
428
+ // or shadow its prototype instead of faithfully producing the JSON map the
429
+ // client must receive.
430
+ const inputRequests = Object.fromEntries(internal.inputRequests);
431
+ return { ...base, status: "input_required", inputRequests };
432
+ }
433
+ case "completed":
434
+ return { ...base, status: "completed", result: internal.result! };
435
+ case "failed":
436
+ return { ...base, status: "failed", error: internal.error! };
437
+ case "cancelled":
438
+ return { ...base, status: "cancelled" };
439
+ }
440
+ }
441
+
442
+ /**
443
+ * Wrap a run() result in the required `Record<string, unknown>` shape.
444
+ *
445
+ * Tool handlers may return any serialisable value. The spec models
446
+ * `CompletedTask.result` as an object, so a primitive or array is boxed
447
+ * under `"value"` rather than discarded or cast dangerously.
448
+ */
449
+ function normaliseResult(raw: unknown): Record<string, unknown> {
450
+ if (isRecord(raw)) return raw;
451
+ return { value: raw };
452
+ }
453
+
454
+ // ── Public factory / type-guard ────────────────────────────────────────────────
455
+
456
+ /**
457
+ * Factory for tool handlers that want to run asynchronously.
458
+ *
459
+ * Returns an `AsyncTaskDescriptor` the framework detects and routes through
460
+ * the `TaskStore`. The handler never sees the store directly — it only receives
461
+ * the `TaskController` when `run()` is invoked.
462
+ *
463
+ * @example
464
+ * ```typescript
465
+ * // Inside a tool handler:
466
+ * return createTask({ ttlMs: 60_000, pollIntervalMs: 3_000 }, async (ctrl) => {
467
+ * const rows = await scanWholeTable(args, ctrl.signal);
468
+ * return { rows };
469
+ * });
470
+ * ```
471
+ */
472
+ export function createTask(
473
+ options: CreateTaskOptions,
474
+ run: (ctrl: TaskController) => Promise<unknown>,
475
+ ): AsyncTaskDescriptor {
476
+ return { _type: "async-task", options, run };
477
+ }
478
+
479
+ /**
480
+ * Type guard used by the transport to distinguish an `AsyncTaskDescriptor`
481
+ * from an ordinary tool result.
482
+ *
483
+ * Checks the private `_type` discriminant rather than shape-matching public
484
+ * fields, so a tool result that happens to carry similar fields is never
485
+ * misidentified.
486
+ */
487
+ export function isAsyncTaskDescriptor(v: unknown): v is AsyncTaskDescriptor {
488
+ // Two-step cast through `unknown` is intentional: `Record<string, unknown>`
489
+ // and `AsyncTaskDescriptor` have no proven overlap, so TypeScript requires
490
+ // the intermediate step. The runtime check on `_type` and `run` is the
491
+ // actual guard; the cast merely satisfies the type checker.
492
+ return isRecord(v) && v["_type"] === "async-task" &&
493
+ typeof (v as unknown as AsyncTaskDescriptor).run === "function";
494
+ }
495
+
496
+ // ── TaskStore ──────────────────────────────────────────────────────────────────
497
+
498
+ const DEFAULT_OPTIONS: TaskStoreOptions = {
499
+ defaultTtlMs: 3_600_000, // 1 hour — see TaskStoreOptions.defaultTtlMs doc
500
+ maxTasks: 5_000, // see TaskStoreOptions.maxTasks doc
501
+ cleanupIntervalMs: 5 * 60 * 1_000, // 5 minutes, matching session cleanup
502
+ };
503
+
504
+ /**
505
+ * Server-side store for background tasks spawned by the Tasks extension.
506
+ *
507
+ * Responsibilities:
508
+ * - Issue unique, unguessable task IDs.
509
+ * - Store task state and transition it as work progresses.
510
+ * - Route client input (tasks/update) to waiting requireInput() calls.
511
+ * - Enforce TTL expiry and a hard memory cap via eviction.
512
+ * - Surface a notification callback for Track G (subscriptions/listen).
513
+ *
514
+ * All public methods are synchronous (except the background work itself)
515
+ * to ensure the tasks/get → tasks/update → tasks/cancel request flow
516
+ * never blocks on I/O inside the store.
517
+ */
518
+ export class TaskStore {
519
+ private readonly _options: TaskStoreOptions;
520
+ private readonly _tasks = new Map<string, InternalTask>();
521
+ private _cleanupTimer: ReturnType<typeof setInterval> | null = null;
522
+
523
+ constructor(options?: Partial<TaskStoreOptions>) {
524
+ this._options = { ...DEFAULT_OPTIONS, ...options };
525
+
526
+ // Only start a cleanup timer if requested — tests pass cleanupIntervalMs: 0
527
+ // to disable it and drive cleanup manually.
528
+ if (this._options.cleanupIntervalMs > 0) {
529
+ this._cleanupTimer = setInterval(
530
+ () => this._sweep(),
531
+ this._options.cleanupIntervalMs,
532
+ );
533
+ // Unref'd: a housekeeping ticker must never be the reason a process cannot
534
+ // exit. Without this, forgetting dispose() — or failing before ever
535
+ // reaching it — hangs the runtime instead of merely leaking a timer.
536
+ this._options.unrefTimer?.(this._cleanupTimer);
537
+ }
538
+ }
539
+
540
+ /**
541
+ * Spawn a background task from an `AsyncTaskDescriptor`.
542
+ *
543
+ * MUST be called after verifying the client declared the tasks capability.
544
+ *
545
+ * Returns the `CreateTaskResultFields` the transport should send as the
546
+ * result of the triggering tools/call, with `resultType: "task"` added by
547
+ * the caller. (stampResult() sets `"complete"` and must NOT be called here.)
548
+ *
549
+ * Spec §Task Creation: "Server MUST NOT return CreateTaskResult until the
550
+ * task is durably created — a subsequent tasks/get for the returned taskId
551
+ * must resolve immediately." Fulfilled: we insert into `_tasks` before
552
+ * returning.
553
+ */
554
+ spawn(
555
+ descriptor: AsyncTaskDescriptor,
556
+ owner: string,
557
+ formatResult?: (raw: unknown) => Record<string, unknown>,
558
+ ): CreateTaskResultFields {
559
+ // A tool handler can settle after shutdown began — the pipeline is async and
560
+ // abort is cooperative. Spawning then would start un-abortable work in a store
561
+ // nobody will ever drain again, and the task would outlive the server that
562
+ // created it.
563
+ if (this._disposed) {
564
+ throw new Error(
565
+ "[TaskStore] Cannot spawn: the store has been disposed (server is stopping or stopped).",
566
+ );
567
+ }
568
+ const taskId = generateTaskId();
569
+ const now = new Date().toISOString();
570
+
571
+ // Spec is silent on a default; fill from store options when the handler
572
+ // omits ttlMs, and honour `null` explicitly (no expiry).
573
+ const ttlMs = descriptor.options.ttlMs !== undefined
574
+ ? descriptor.options.ttlMs
575
+ : this._options.defaultTtlMs;
576
+
577
+ const abortController = new AbortController();
578
+
579
+ // Allocate internal task. runPromise is assigned below AFTER the
580
+ // controller is built, but before spawn() returns. The controller only
581
+ // reads/writes other fields, so the placeholder is safe for the window
582
+ // between allocation and assignment.
583
+ const internal: InternalTask = {
584
+ taskId,
585
+ owner,
586
+ status: "working",
587
+ createdAt: now,
588
+ lastUpdatedAt: now,
589
+ ttlMs,
590
+ pollIntervalMs: descriptor.options.pollIntervalMs ?? 5_000,
591
+ ...(descriptor.options.statusMessage !== undefined
592
+ ? { statusMessage: descriptor.options.statusMessage }
593
+ : {}),
594
+ abortController,
595
+ runPromise: Promise.resolve(), // replaced below
596
+ inputRequests: new Map(),
597
+ answeredKeys: new Set(),
598
+ pendingResolvers: new Map(),
599
+ };
600
+
601
+ // Build the TaskController. Captures `internal` by reference so every
602
+ // field update inside run() is visible to concurrent get() calls.
603
+ const ctrl: TaskController = {
604
+ signal: abortController.signal,
605
+
606
+ requireInput: (
607
+ key: string,
608
+ request: InputRequest,
609
+ ): Promise<Record<string, unknown>> => {
610
+ const validated = canonicaliseTaskInputRequest(key, request);
611
+ if (!validated.ok) {
612
+ // A malformed server-side request cannot be sent back to the client.
613
+ // Unlike an HTTP request, the correct boundary response is a terminal
614
+ // task: the caller already holds this task's id and can observe the
615
+ // concrete failure through tasks/get. Mark it before rejecting so a
616
+ // handler that catches the rejection cannot accidentally complete the
617
+ // task afterwards.
618
+ if (!isTerminal(internal.status)) {
619
+ internal.status = "failed";
620
+ internal.error = {
621
+ code: -32603,
622
+ message: validated.message,
623
+ };
624
+ internal.lastUpdatedAt = new Date().toISOString();
625
+ internal.terminalAt = Date.now();
626
+ // Reject any earlier outstanding input waits too. Their abort
627
+ // handlers remove the requests, so no stale input can survive this
628
+ // terminal state.
629
+ abortController.abort();
630
+ this._notify(internal);
631
+ }
632
+ return Promise.reject(new Error(validated.message));
633
+ }
634
+ const canonicalKey = validated.key;
635
+
636
+ if (isTerminal(internal.status)) {
637
+ return Promise.reject(
638
+ new Error(
639
+ `Cannot require task input after the task is ${internal.status}.`,
640
+ ),
641
+ );
642
+ }
643
+
644
+ // Spec §Task Update Requests: key uniqueness is lifetime-scoped, not
645
+ // just to currently-outstanding requests. A key used, answered, and
646
+ // re-submitted is a server bug, not a client one.
647
+ if (internal.answeredKeys.has(canonicalKey)) {
648
+ return Promise.reject(
649
+ new Error(
650
+ `Input request key "${canonicalKey}" has already been answered in this task ` +
651
+ `and cannot be reused (spec §Task Update Requests prohibits key reuse ` +
652
+ `after the client has delivered a response).`,
653
+ ),
654
+ );
655
+ }
656
+ if (internal.pendingResolvers.has(canonicalKey)) {
657
+ return Promise.reject(
658
+ new Error(
659
+ `Input request key "${canonicalKey}" is already outstanding in this task.`,
660
+ ),
661
+ );
662
+ }
663
+
664
+ // Register the outstanding request and transition to input_required.
665
+ internal.inputRequests.set(canonicalKey, validated.request);
666
+ internal.lastUpdatedAt = new Date().toISOString();
667
+ if (internal.status === "working") {
668
+ internal.status = "input_required";
669
+ this._notify(internal);
670
+ }
671
+
672
+ return new Promise<Record<string, unknown>>((resolve, reject) => {
673
+ internal.pendingResolvers.set(canonicalKey, resolve);
674
+
675
+ // Fire immediately if the abort already happened (race-free via
676
+ // the AbortSignal contract: addEventListener fires synchronously
677
+ // when the signal is already aborted).
678
+ const onAbort = () => {
679
+ if (!internal.pendingResolvers.has(canonicalKey)) return; // already answered
680
+ internal.pendingResolvers.delete(canonicalKey);
681
+ internal.inputRequests.delete(canonicalKey);
682
+ reject(new DOMException("Task was cancelled", "AbortError"));
683
+ };
684
+
685
+ abortController.signal.addEventListener("abort", onAbort, {
686
+ once: true,
687
+ });
688
+ });
689
+ },
690
+
691
+ setStatusMessage: (msg: string): void => {
692
+ if (isTerminal(internal.status)) return;
693
+ internal.statusMessage = msg;
694
+ internal.lastUpdatedAt = new Date().toISOString();
695
+ },
696
+ };
697
+
698
+ // Start background work. Errors in run() are caught here to drive state
699
+ // transitions — they must not surface as unhandled rejections, which
700
+ // would crash the Deno process.
701
+ const runPromise: Promise<void> = descriptor.run(ctrl).then(
702
+ (rawResult: unknown) => {
703
+ // Guard: a TTL sweep may have already marked this task failed while
704
+ // the run() promise was settling. Honour the first terminal state.
705
+ if (isTerminal(internal.status)) return;
706
+
707
+ // A completed task carries the result the original request would have
708
+ // returned — a CallToolResult for tools/call — not the handler's raw
709
+ // return value. The store stays ignorant of MCP result shapes: the
710
+ // transport injects the conversion it already uses for synchronous
711
+ // calls, so both paths produce identical output for the same handler.
712
+ //
713
+ // The formatter can throw: it serialises arbitrary handler output, and a
714
+ // BigInt or a circular structure is enough. Left unguarded that produced
715
+ // a task marked `completed` with NO result — the one state a client
716
+ // polling for a result cannot make sense of — plus an unhandled
717
+ // rejection. Treat it as what it is: the work finished, the result cannot
718
+ // be represented.
719
+ try {
720
+ internal.result = formatResult
721
+ ? formatResult(rawResult)
722
+ : normaliseResult(rawResult);
723
+ internal.status = "completed";
724
+ } catch (formatError) {
725
+ internal.status = "failed";
726
+ internal.error = {
727
+ code: -32603,
728
+ message: `Task result could not be serialised: ${
729
+ formatError instanceof Error
730
+ ? formatError.message
731
+ : String(formatError)
732
+ }`,
733
+ };
734
+ }
735
+ internal.lastUpdatedAt = new Date().toISOString();
736
+ internal.terminalAt = Date.now();
737
+ this._notify(internal);
738
+ },
739
+ (error: unknown) => {
740
+ if (isTerminal(internal.status)) return; // TTL/eviction won the race
741
+
742
+ const nowStr = new Date().toISOString();
743
+ internal.lastUpdatedAt = nowStr;
744
+ internal.terminalAt = Date.now();
745
+
746
+ // Distinguish abort (→ cancelled) from JSON-RPC error (→ failed)
747
+ // from generic error (→ failed with -32603).
748
+ if (error instanceof DOMException && error.name === "AbortError") {
749
+ internal.status = "cancelled";
750
+ } else if (isJsonRpcError(error)) {
751
+ internal.status = "failed";
752
+ // Preserve any extra fields from the thrown object (e.g. `data`).
753
+ internal.error = { ...error };
754
+ } else {
755
+ // Spec: failed is for protocol-level errors. If a tool throws a
756
+ // plain Error, we treat it as Internal Error (-32603) to stay
757
+ // spec-compliant rather than swallowing it.
758
+ internal.status = "failed";
759
+ internal.error = {
760
+ code: -32603,
761
+ message: error instanceof Error ? error.message : String(error),
762
+ };
763
+ }
764
+ this._notify(internal);
765
+ },
766
+ );
767
+
768
+ internal.runPromise = runPromise;
769
+
770
+ // Evict if over cap BEFORE inserting, so the new task is always stored.
771
+ this._maybeEvict();
772
+ // Register BEFORE returning — spec MUST §Task Creation.
773
+ this._tasks.set(taskId, internal);
774
+
775
+ return toDetailedTask(internal) as CreateTaskResultFields;
776
+ }
777
+
778
+ /**
779
+ * Service a tasks/get request.
780
+ *
781
+ * Returns `null` when the taskId is unknown or has been purged
782
+ * (caller returns -32602).
783
+ *
784
+ * Spec §Task Polling: "If status is 'working', return Task with status
785
+ * 'working'; if 'input_required', return Task with inputRequests containing
786
+ * all outstanding server-to-client requests; if 'completed', return Task
787
+ * with result; if 'cancelled', return Task with status 'cancelled'; if
788
+ * 'failed', return Task with error."
789
+ */
790
+ get(taskId: string, caller: string): DetailedTask | null {
791
+ const internal = this._tasks.get(taskId);
792
+ if (!internal) return null;
793
+ // Indistinguishable from "unknown task" on purpose: telling a caller that a
794
+ // task exists but is not theirs confirms the id, which is exactly what an
795
+ // unguessable handle is meant to withhold.
796
+ if (internal.owner !== caller) return null;
797
+ return toDetailedTask(internal);
798
+ }
799
+
800
+ /**
801
+ * Service a tasks/update request.
802
+ *
803
+ * Delivers client responses to outstanding requireInput() calls.
804
+ *
805
+ * Returns `true` on success, `false` if the taskId is unknown
806
+ * (caller SHOULD return -32602 per spec §Task Update Requests).
807
+ *
808
+ * Spec §Task Update Requests:
809
+ * - "Server SHOULD ignore inputResponses mapped to unknown, already-answered,
810
+ * or superseded keys."
811
+ * - "Server MAY accept a partial set of responses."
812
+ *
813
+ * Silently ignores responses for unknown keys instead of erroring, because
814
+ * a stale retry from an impatient client must not break an otherwise healthy
815
+ * task.
816
+ */
817
+ update(
818
+ taskId: string,
819
+ inputResponses: Record<string, unknown>,
820
+ caller: string,
821
+ ): boolean {
822
+ const internal = this._tasks.get(taskId);
823
+ if (!internal || internal.owner !== caller) return false;
824
+
825
+ for (const [key, rawValue] of Object.entries(inputResponses)) {
826
+ const resolver = internal.pendingResolvers.get(key);
827
+ if (!resolver) continue; // unknown / already-answered key — ignore
828
+
829
+ internal.pendingResolvers.delete(key);
830
+ internal.inputRequests.delete(key);
831
+ internal.answeredKeys.add(key);
832
+ internal.lastUpdatedAt = new Date().toISOString();
833
+
834
+ // Normalise the response to Record — the spec treats the value as an
835
+ // object; a primitive is boxed under "value" rather than dropping it.
836
+ const response: Record<string, unknown> = isRecord(rawValue)
837
+ ? rawValue
838
+ : { value: rawValue };
839
+ resolver(response);
840
+ }
841
+
842
+ // Move back to "working" when all pending resolvers are satisfied.
843
+ // The run() promise may immediately re-enter "input_required" by calling
844
+ // requireInput() again, but that transition happens inside run() before
845
+ // this method returns — which is fine because we check pendingResolvers.size.
846
+ if (
847
+ internal.status === "input_required" &&
848
+ internal.pendingResolvers.size === 0
849
+ ) {
850
+ internal.status = "working";
851
+ internal.lastUpdatedAt = new Date().toISOString();
852
+ this._notify(internal);
853
+ }
854
+
855
+ return true;
856
+ }
857
+
858
+ /**
859
+ * Service a tasks/cancel request.
860
+ *
861
+ * Returns `true` if the task was found (regardless of whether the work
862
+ * actually stops). Returns `false` if unknown (caller SHOULD return -32602).
863
+ *
864
+ * Spec §Task Cancellation: "Cancellation is cooperative: the server is not
865
+ * obligated to actually stop the work; it only acknowledges intent. Eventual
866
+ * transition to 'cancelled' is not guaranteed."
867
+ *
868
+ * `notifications/cancelled` MUST NOT be used for task cancellation — the spec
869
+ * reserves a dedicated `notifications/tasks/statusChanged` notification for
870
+ * Track G instead.
871
+ */
872
+ cancel(taskId: string, caller: string): boolean {
873
+ const internal = this._tasks.get(taskId);
874
+ if (!internal || internal.owner !== caller) return false;
875
+
876
+ if (!isTerminal(internal.status)) {
877
+ // Signal the AbortController so run() can observe ctrl.signal.aborted.
878
+ // We do NOT await runPromise here — the acknowledgement is immediate.
879
+ internal.abortController.abort();
880
+ }
881
+ return true;
882
+ }
883
+
884
+ /**
885
+ * Signal all in-flight AbortControllers.
886
+ *
887
+ * Called by McpApp.stop() before awaiting httpServer.shutdown(), giving
888
+ * background Promises a chance to observe the signal and exit early.
889
+ * Does NOT await completion — best-effort on graceful shutdown.
890
+ */
891
+ drain(): void {
892
+ for (const internal of this._tasks.values()) {
893
+ if (!isTerminal(internal.status)) {
894
+ internal.abortController.abort();
895
+ }
896
+ }
897
+ }
898
+
899
+ /**
900
+ * Clear the cleanup interval.
901
+ *
902
+ * Must be called after drain() in McpApp.stop() to release the timer
903
+ * and let the process exit cleanly.
904
+ */
905
+ /** True once dispose() ran; suppresses any late notification. */
906
+ private _disposed = false;
907
+
908
+ /** Whether this store has been torn down and must not accept new work. */
909
+ get isDisposed(): boolean {
910
+ return this._disposed;
911
+ }
912
+
913
+ /**
914
+ * Emit a status change, unless the store was disposed.
915
+ *
916
+ * A drained task's `run()` promise can still settle after dispose() — abort is
917
+ * cooperative, so work that ignores the signal keeps going. Pushing that
918
+ * transition to a subscriber whose transport is already torn down is at best
919
+ * useless and at worst a write to a closed stream.
920
+ */
921
+ private _notify(internal: InternalTask): void {
922
+ if (this._disposed) return;
923
+ this._options.onNotification?.(toDetailedTask(internal));
924
+ }
925
+
926
+ dispose(): void {
927
+ this._disposed = true;
928
+ if (this._cleanupTimer !== null) {
929
+ clearInterval(this._cleanupTimer);
930
+ this._cleanupTimer = null;
931
+ }
932
+ }
933
+
934
+ // ── Introspection (tests + diagnostics) ─────────────────────────────────────
935
+
936
+ /** Current number of tracked tasks (terminal + non-terminal). */
937
+ get size(): number {
938
+ return this._tasks.size;
939
+ }
940
+
941
+ // ── Private helpers ──────────────────────────────────────────────────────────
942
+
943
+ /**
944
+ * Sweep for TTL-expired tasks and mark them failed.
945
+ *
946
+ * Spec §Task Polling: "Server MAY mark a task as 'failed' at any point
947
+ * after the TTL elapses, and subsequently delete it at any time. Returning
948
+ * -32602 for an expired deleted task is compliant."
949
+ *
950
+ * We mark `failed` immediately on expiry and let maxTasks eviction handle
951
+ * physical deletion — this avoids a second timestamp-based deletion pass.
952
+ */
953
+ private _sweep(): void {
954
+ const now = Date.now();
955
+ for (const internal of this._tasks.values()) {
956
+ if (isTerminal(internal.status)) continue;
957
+ if (internal.ttlMs === null) continue;
958
+
959
+ const createdMs = new Date(internal.createdAt).getTime();
960
+ if (now - createdMs <= internal.ttlMs) continue;
961
+
962
+ // Abort to unblock any pending requireInput() calls.
963
+ internal.abortController.abort();
964
+
965
+ internal.status = "failed";
966
+ internal.error = {
967
+ code: -32603,
968
+ message: `Task TTL of ${internal.ttlMs}ms elapsed without completing.`,
969
+ };
970
+ internal.lastUpdatedAt = new Date().toISOString();
971
+ internal.terminalAt = now;
972
+ this._notify(internal);
973
+ }
974
+ }
975
+
976
+ /**
977
+ * Enforce the maxTasks cap before inserting a new task.
978
+ *
979
+ * Eviction order (spec is silent; justified in TaskStoreOptions.maxTasks):
980
+ * 1. Terminal tasks, oldest-terminalAt first (already served their purpose).
981
+ * 2. Non-terminal tasks, oldest-createdAt first (least likely to be polled
982
+ * soon), with abort signal sent to allow cooperative cleanup.
983
+ */
984
+ private _maybeEvict(): void {
985
+ if (this._tasks.size < this._options.maxTasks) return;
986
+
987
+ // Phase 1: evict terminal tasks by age.
988
+ const terminal = [...this._tasks.values()]
989
+ .filter((t) => isTerminal(t.status))
990
+ .sort((a, b) => (a.terminalAt ?? 0) - (b.terminalAt ?? 0));
991
+
992
+ for (const t of terminal) {
993
+ if (this._tasks.size < this._options.maxTasks) return;
994
+ this._tasks.delete(t.taskId);
995
+ }
996
+
997
+ // Phase 2: evict oldest non-terminal tasks.
998
+ if (this._tasks.size >= this._options.maxTasks) {
999
+ const nonTerminal = [...this._tasks.values()]
1000
+ .filter((t) => !isTerminal(t.status))
1001
+ .sort(
1002
+ (a, b) =>
1003
+ new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
1004
+ );
1005
+
1006
+ for (const t of nonTerminal) {
1007
+ if (this._tasks.size < this._options.maxTasks) return;
1008
+ // Give the task a chance to shut down gracefully.
1009
+ t.abortController.abort();
1010
+ this._tasks.delete(t.taskId);
1011
+ }
1012
+ }
1013
+ }
1014
+ }