@casys/mcp-server 0.26.0 → 0.27.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.
- package/CHANGELOG.md +1779 -0
- package/LICENSE +21 -0
- package/README.md +19 -5
- package/esm/_dnt.polyfills.d.ts +12 -0
- package/esm/_dnt.polyfills.d.ts.map +1 -0
- package/esm/_dnt.polyfills.js +15 -0
- package/esm/_dnt.shims.d.ts +2 -0
- package/esm/_dnt.shims.d.ts.map +1 -0
- package/esm/_dnt.shims.js +57 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts +33 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.js +48 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts +106 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.js +636 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts +67 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.js +1393 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts +44 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.js +117 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.js +103 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.js +32 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.js +96 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.js +159 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.js +14 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.js +10 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.js +22 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.js +29 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.js +19 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.js +30 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.js +10 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.js +14 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.js +9 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.js +81 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.js +20 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts +32 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.js +6 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts +4 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.js +13 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts +51 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.js +53 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts +79 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.js +91 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts +100 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.js +33 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts +111 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/types.js +104 -0
- package/esm/mod.d.ts +102 -0
- package/esm/mod.d.ts.map +1 -0
- package/esm/mod.js +103 -0
- package/esm/package.json +3 -0
- package/esm/src/auth/as-metadata-proxy.d.ts +112 -0
- package/esm/src/auth/as-metadata-proxy.d.ts.map +1 -0
- package/esm/src/auth/as-metadata-proxy.js +171 -0
- package/esm/src/auth/config.d.ts +117 -0
- package/esm/src/auth/config.d.ts.map +1 -0
- package/esm/src/auth/config.js +219 -0
- package/esm/src/auth/jwt-provider.d.ts +157 -0
- package/esm/src/auth/jwt-provider.d.ts.map +1 -0
- package/esm/src/auth/jwt-provider.js +187 -0
- package/esm/src/auth/middleware.d.ts +61 -0
- package/esm/src/auth/middleware.d.ts.map +1 -0
- package/esm/src/auth/middleware.js +209 -0
- package/esm/src/auth/mod.d.ts +23 -0
- package/esm/src/auth/mod.d.ts.map +1 -0
- package/esm/src/auth/mod.js +27 -0
- package/esm/src/auth/multi-tenant-middleware.d.ts +131 -0
- package/esm/src/auth/multi-tenant-middleware.d.ts.map +1 -0
- package/esm/src/auth/multi-tenant-middleware.js +128 -0
- package/esm/src/auth/presets.d.ts +231 -0
- package/esm/src/auth/presets.d.ts.map +1 -0
- package/esm/src/auth/presets.js +223 -0
- package/{src/auth/provider.ts → esm/src/auth/provider.d.ts} +13 -15
- package/esm/src/auth/provider.d.ts.map +1 -0
- package/esm/src/auth/provider.js +34 -0
- package/esm/src/auth/scope-middleware.d.ts +30 -0
- package/esm/src/auth/scope-middleware.d.ts.map +1 -0
- package/esm/src/auth/scope-middleware.js +48 -0
- package/esm/src/auth/static-token-provider.d.ts +155 -0
- package/esm/src/auth/static-token-provider.d.ts.map +1 -0
- package/esm/src/auth/static-token-provider.js +256 -0
- package/esm/src/auth/types.d.ts +151 -0
- package/esm/src/auth/types.d.ts.map +1 -0
- package/esm/src/auth/types.js +64 -0
- package/esm/src/client-auth/callback-server.d.ts +34 -0
- package/esm/src/client-auth/callback-server.d.ts.map +1 -0
- package/esm/src/client-auth/callback-server.js +141 -0
- package/esm/src/client-auth/client-id-metadata.d.ts +29 -0
- package/esm/src/client-auth/client-id-metadata.d.ts.map +1 -0
- package/esm/src/client-auth/client-id-metadata.js +149 -0
- package/esm/src/client-auth/connect.d.ts +32 -0
- package/esm/src/client-auth/connect.d.ts.map +1 -0
- package/esm/src/client-auth/connect.js +47 -0
- package/esm/src/client-auth/mod.d.ts +19 -0
- package/esm/src/client-auth/mod.d.ts.map +1 -0
- package/{src/client-auth/mod.ts → esm/src/client-auth/mod.js} +1 -26
- package/esm/src/client-auth/provider.d.ts +78 -0
- package/esm/src/client-auth/provider.d.ts.map +1 -0
- package/esm/src/client-auth/provider.js +246 -0
- package/esm/src/client-auth/token-store/file-store.d.ts +20 -0
- package/esm/src/client-auth/token-store/file-store.d.ts.map +1 -0
- package/esm/src/client-auth/token-store/file-store.js +62 -0
- package/esm/src/client-auth/token-store/memory-store.d.ts +14 -0
- package/esm/src/client-auth/token-store/memory-store.d.ts.map +1 -0
- package/esm/src/client-auth/token-store/memory-store.js +25 -0
- package/esm/src/client-auth/types.d.ts +89 -0
- package/esm/src/client-auth/types.d.ts.map +1 -0
- package/esm/src/client-auth/types.js +10 -0
- package/esm/src/concurrency/rate-limiter.d.ts +87 -0
- package/esm/src/concurrency/rate-limiter.d.ts.map +1 -0
- package/esm/src/concurrency/rate-limiter.js +165 -0
- package/esm/src/concurrency/request-queue.d.ts +71 -0
- package/esm/src/concurrency/request-queue.d.ts.map +1 -0
- package/esm/src/concurrency/request-queue.js +128 -0
- package/esm/src/http/body.d.ts +20 -0
- package/esm/src/http/body.d.ts.map +1 -0
- package/esm/src/http/body.js +63 -0
- package/esm/src/http/request-guards.d.ts +54 -0
- package/esm/src/http/request-guards.d.ts.map +1 -0
- package/esm/src/http/request-guards.js +114 -0
- package/esm/src/http/wire.d.ts +26 -0
- package/esm/src/http/wire.d.ts.map +1 -0
- package/{src/http/wire.ts → esm/src/http/wire.js} +13 -19
- package/esm/src/inspector/launcher.d.ts +48 -0
- package/esm/src/inspector/launcher.d.ts.map +1 -0
- package/esm/src/inspector/launcher.js +100 -0
- package/esm/src/mcp-app.d.ts +728 -0
- package/esm/src/mcp-app.d.ts.map +1 -0
- package/esm/src/mcp-app.js +3530 -0
- package/{src/middleware/backpressure.ts → esm/src/middleware/backpressure.d.ts} +2 -14
- package/esm/src/middleware/backpressure.d.ts.map +1 -0
- package/esm/src/middleware/backpressure.js +31 -0
- package/esm/src/middleware/mod.d.ts +11 -0
- package/esm/src/middleware/mod.d.ts.map +1 -0
- package/{src/middleware/mod.ts → esm/src/middleware/mod.js} +0 -10
- package/{src/middleware/rate-limit.ts → esm/src/middleware/rate-limit.d.ts} +2 -25
- package/esm/src/middleware/rate-limit.d.ts.map +1 -0
- package/esm/src/middleware/rate-limit.js +33 -0
- package/esm/src/middleware/runner.d.ts +32 -0
- package/esm/src/middleware/runner.d.ts.map +1 -0
- package/esm/src/middleware/runner.js +49 -0
- package/esm/src/middleware/types.d.ts +76 -0
- package/esm/src/middleware/types.d.ts.map +1 -0
- package/esm/src/middleware/types.js +9 -0
- package/esm/src/middleware/validation.d.ts +24 -0
- package/esm/src/middleware/validation.d.ts.map +1 -0
- package/esm/src/middleware/validation.js +30 -0
- package/esm/src/mrtr/capability-check.d.ts +75 -0
- package/esm/src/mrtr/capability-check.d.ts.map +1 -0
- package/esm/src/mrtr/capability-check.js +233 -0
- package/esm/src/mrtr/mod.d.ts +18 -0
- package/esm/src/mrtr/mod.d.ts.map +1 -0
- package/esm/src/mrtr/mod.js +12 -0
- package/esm/src/mrtr/replay-store.d.ts +50 -0
- package/esm/src/mrtr/replay-store.d.ts.map +1 -0
- package/esm/src/mrtr/replay-store.js +61 -0
- package/esm/src/mrtr/request-state.d.ts +181 -0
- package/esm/src/mrtr/request-state.d.ts.map +1 -0
- package/esm/src/mrtr/request-state.js +313 -0
- package/esm/src/mrtr/retry-guard.d.ts +61 -0
- package/esm/src/mrtr/retry-guard.d.ts.map +1 -0
- package/esm/src/mrtr/retry-guard.js +53 -0
- package/esm/src/mrtr/types.d.ts +99 -0
- package/esm/src/mrtr/types.d.ts.map +1 -0
- package/esm/src/mrtr/types.js +14 -0
- package/esm/src/observability/metrics.d.ts +104 -0
- package/esm/src/observability/metrics.d.ts.map +1 -0
- package/esm/src/observability/metrics.js +207 -0
- package/{src/observability/mod.ts → esm/src/observability/mod.d.ts} +2 -11
- package/esm/src/observability/mod.d.ts.map +1 -0
- package/esm/src/observability/mod.js +11 -0
- package/esm/src/observability/otel.d.ts +73 -0
- package/esm/src/observability/otel.d.ts.map +1 -0
- package/esm/src/observability/otel.js +260 -0
- package/esm/src/runtime/runtime.d.ts +10 -0
- package/esm/src/runtime/runtime.d.ts.map +1 -0
- package/esm/src/runtime/runtime.deno.d.ts +50 -0
- package/esm/src/runtime/runtime.deno.d.ts.map +1 -0
- package/esm/src/runtime/runtime.deno.js +120 -0
- package/{src/runtime/runtime.ts → esm/src/runtime/runtime.js} +5 -14
- package/esm/src/runtime/runtime.node.d.ts +51 -0
- package/esm/src/runtime/runtime.node.d.ts.map +1 -0
- package/esm/src/runtime/runtime.node.js +268 -0
- package/{src/runtime/types.ts → esm/src/runtime/types.d.ts} +28 -51
- package/esm/src/runtime/types.d.ts.map +1 -0
- package/esm/src/runtime/types.js +12 -0
- package/esm/src/security/channel-hmac.d.ts +43 -0
- package/esm/src/security/channel-hmac.d.ts.map +1 -0
- package/{src/security/channel-hmac.ts → esm/src/security/channel-hmac.js} +12 -17
- package/esm/src/security/csp.d.ts +50 -0
- package/esm/src/security/csp.d.ts.map +1 -0
- package/esm/src/security/csp.js +63 -0
- package/esm/src/security/message-signer.d.ts +88 -0
- package/esm/src/security/message-signer.d.ts.map +1 -0
- package/esm/src/security/message-signer.js +166 -0
- package/esm/src/subscriptions/subscription-registry.d.ts +256 -0
- package/esm/src/subscriptions/subscription-registry.d.ts.map +1 -0
- package/esm/src/subscriptions/subscription-registry.js +406 -0
- package/{src/tasks/mod.ts → esm/src/tasks/mod.d.ts} +3 -23
- package/esm/src/tasks/mod.d.ts.map +1 -0
- package/esm/src/tasks/mod.js +11 -0
- package/esm/src/tasks/task-store.d.ts +342 -0
- package/esm/src/tasks/task-store.d.ts.map +1 -0
- package/esm/src/tasks/task-store.js +649 -0
- package/esm/src/transport/request-headers.d.ts +145 -0
- package/esm/src/transport/request-headers.d.ts.map +1 -0
- package/esm/src/transport/request-headers.js +525 -0
- package/esm/src/types.d.ts +776 -0
- package/esm/src/types.d.ts.map +1 -0
- package/esm/src/types.js +92 -0
- package/esm/src/ui/viewer-utils.d.ts +45 -0
- package/esm/src/ui/viewer-utils.d.ts.map +1 -0
- package/esm/src/ui/viewer-utils.js +97 -0
- package/esm/src/validation/schema-validator.d.ts +115 -0
- package/esm/src/validation/schema-validator.d.ts.map +1 -0
- package/esm/src/validation/schema-validator.js +249 -0
- package/package.json +35 -23
- package/mod.ts +0 -302
- package/src/auth/as-metadata-proxy.ts +0 -288
- package/src/auth/config.ts +0 -368
- package/src/auth/jwt-provider.ts +0 -327
- package/src/auth/middleware.ts +0 -257
- package/src/auth/mod.ts +0 -89
- package/src/auth/multi-tenant-middleware.ts +0 -236
- package/src/auth/presets.ts +0 -351
- package/src/auth/scope-middleware.ts +0 -59
- package/src/auth/static-token-provider.ts +0 -197
- package/src/auth/types.ts +0 -207
- package/src/client-auth/callback-server.ts +0 -166
- package/src/client-auth/client-id-metadata.ts +0 -260
- package/src/client-auth/connect.ts +0 -72
- package/src/client-auth/provider.ts +0 -300
- package/src/client-auth/token-store/file-store.ts +0 -73
- package/src/client-auth/token-store/memory-store.ts +0 -32
- package/src/client-auth/types.ts +0 -95
- package/src/concurrency/rate-limiter.ts +0 -190
- package/src/concurrency/request-queue.ts +0 -140
- package/src/http/body.ts +0 -72
- package/src/http/request-guards.ts +0 -137
- package/src/inspector/launcher.ts +0 -131
- package/src/mcp-app.ts +0 -4426
- package/src/middleware/runner.ts +0 -63
- package/src/middleware/types.ts +0 -104
- package/src/middleware/validation.ts +0 -28
- package/src/mrtr/capability-check.ts +0 -303
- package/src/mrtr/mod.ts +0 -46
- package/src/mrtr/replay-store.ts +0 -103
- package/src/mrtr/request-state.ts +0 -435
- package/src/mrtr/types.ts +0 -107
- package/src/observability/metrics.ts +0 -336
- package/src/observability/otel.ts +0 -330
- package/src/runtime/runtime.deno.ts +0 -149
- package/src/runtime/runtime.node.ts +0 -324
- package/src/security/csp.ts +0 -89
- package/src/security/message-signer.ts +0 -223
- package/src/subscriptions/subscription-registry.ts +0 -558
- package/src/tasks/task-store.ts +0 -1014
- package/src/testdata/stdio-e2e-server.ts +0 -110
- package/src/transport/request-headers.ts +0 -661
- package/src/types.ts +0 -907
- package/src/ui/viewer-utils.ts +0 -117
- package/src/validation/schema-validator.ts +0 -307
|
@@ -0,0 +1,649 @@
|
|
|
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
|
+
// ── Entropy ──────────────────────────────────────────────────────────────────
|
|
17
|
+
/**
|
|
18
|
+
* Produce a cryptographically-random task ID.
|
|
19
|
+
*
|
|
20
|
+
* 128 bits of entropy (32 lowercase hex chars). Spec §Security Considerations:
|
|
21
|
+
* "Task IDs MUST be generated with sufficient entropy that a third party cannot
|
|
22
|
+
* enumerate or guess them." 128 bits satisfies that at the same level as a
|
|
23
|
+
* UUID v4 but without the version/variant bits that reduce its effective
|
|
24
|
+
* entropy to 122 bits.
|
|
25
|
+
*/
|
|
26
|
+
export function generateTaskId() {
|
|
27
|
+
const bytes = new Uint8Array(16);
|
|
28
|
+
crypto.getRandomValues(bytes);
|
|
29
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
30
|
+
}
|
|
31
|
+
// ── Private internal representation ──────────────────────────────────────────
|
|
32
|
+
/** Terminal statuses — once in one of these, no further transitions occur. */
|
|
33
|
+
const TERMINAL_STATUSES = new Set([
|
|
34
|
+
"completed",
|
|
35
|
+
"cancelled",
|
|
36
|
+
"failed",
|
|
37
|
+
]);
|
|
38
|
+
function isTerminal(status) {
|
|
39
|
+
return TERMINAL_STATUSES.has(status);
|
|
40
|
+
}
|
|
41
|
+
// ── Helpers ───────────────────────────────────────────────────────────────────
|
|
42
|
+
/** Narrow a value to a plain object (not null, not array). */
|
|
43
|
+
function isRecord(v) {
|
|
44
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Reduce a task input request to the exact JSON shape the task snapshot will
|
|
48
|
+
* expose, then verify the required InputRequest fields on that shape.
|
|
49
|
+
*
|
|
50
|
+
* Task handlers are TypeScript callers, but a JavaScript handler (or an `any`
|
|
51
|
+
* escape hatch) can pass any value here. Storing it first was unsafe: a non-string
|
|
52
|
+
* key could throw only when a later tasks/get built its snapshot, and `null`
|
|
53
|
+
* requests were emitted as invalid protocol objects. Canonicalising once at the
|
|
54
|
+
* boundary keeps the stored value and the wire value identical.
|
|
55
|
+
*/
|
|
56
|
+
function canonicaliseTaskInputRequest(key, request) {
|
|
57
|
+
if (typeof key !== "string") {
|
|
58
|
+
return {
|
|
59
|
+
ok: false,
|
|
60
|
+
message: "Invalid task input request key: expected a string.",
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
let canonical;
|
|
64
|
+
try {
|
|
65
|
+
const serialised = JSON.stringify(request);
|
|
66
|
+
if (serialised === undefined)
|
|
67
|
+
throw new Error("not JSON-serialisable");
|
|
68
|
+
canonical = JSON.parse(serialised);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return {
|
|
72
|
+
ok: false,
|
|
73
|
+
message: "Invalid task input request: it must be a JSON-serialisable object with a string method and object params.",
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
if (!isRecord(canonical) || typeof canonical["method"] !== "string" ||
|
|
77
|
+
!isRecord(canonical["params"])) {
|
|
78
|
+
return {
|
|
79
|
+
ok: false,
|
|
80
|
+
message: "Invalid task input request: expected an object with a string method and object params.",
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
// The method must be one a client can actually service. Accepting any string let
|
|
84
|
+
// a task ask for something like `client/request`, for which no client has a
|
|
85
|
+
// handler — so the task STRANDS in `input_required` forever instead of failing.
|
|
86
|
+
// A stranded task is worse than a failed one: it consumes a poll loop and never
|
|
87
|
+
// resolves. Same grammar as MRTR, from the same table, so the two boundaries
|
|
88
|
+
// cannot drift apart.
|
|
89
|
+
if (!Object.hasOwn(METHOD_TO_CAPABILITY, canonical["method"])) {
|
|
90
|
+
return {
|
|
91
|
+
ok: false,
|
|
92
|
+
message: `Invalid task input request: unsupported method "${canonical["method"]}". Permitted: ${Object.keys(METHOD_TO_CAPABILITY).join(", ")}.`,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
ok: true,
|
|
97
|
+
key,
|
|
98
|
+
request: canonical,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Determine whether a thrown value looks like a JSON-RPC error.
|
|
103
|
+
*
|
|
104
|
+
* Spec: "The 'failed' status MUST NOT be used for non-JSON-RPC errors."
|
|
105
|
+
* A JSON-RPC error must have `code` (integer) and `message` (string).
|
|
106
|
+
* Tool handlers that want to signal `failed` throw exactly this shape.
|
|
107
|
+
*/
|
|
108
|
+
function isJsonRpcError(v) {
|
|
109
|
+
return isRecord(v) && typeof v["code"] === "number" &&
|
|
110
|
+
Number.isInteger(v["code"]) && typeof v["message"] === "string";
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Convert internal task state to the spec's public DetailedTask shape.
|
|
114
|
+
*
|
|
115
|
+
* This is the only place where the internal Map is converted to a Record
|
|
116
|
+
* for the `inputRequests` field — keeping the internal representation as a
|
|
117
|
+
* Map avoids O(n) conversions on every requireInput/update call.
|
|
118
|
+
*/
|
|
119
|
+
function toDetailedTask(internal) {
|
|
120
|
+
const base = {
|
|
121
|
+
taskId: internal.taskId,
|
|
122
|
+
status: internal.status,
|
|
123
|
+
createdAt: internal.createdAt,
|
|
124
|
+
lastUpdatedAt: internal.lastUpdatedAt,
|
|
125
|
+
ttlMs: internal.ttlMs,
|
|
126
|
+
...(internal.statusMessage !== undefined
|
|
127
|
+
? { statusMessage: internal.statusMessage }
|
|
128
|
+
: {}),
|
|
129
|
+
...(internal.pollIntervalMs !== undefined
|
|
130
|
+
? { pollIntervalMs: internal.pollIntervalMs }
|
|
131
|
+
: {}),
|
|
132
|
+
};
|
|
133
|
+
switch (internal.status) {
|
|
134
|
+
case "working":
|
|
135
|
+
return { ...base, status: "working" };
|
|
136
|
+
case "input_required": {
|
|
137
|
+
// Object.fromEntries creates own data properties even for `__proto__`,
|
|
138
|
+
// `constructor`, and `toString`. Assigning those keys to `{}` can mutate
|
|
139
|
+
// or shadow its prototype instead of faithfully producing the JSON map the
|
|
140
|
+
// client must receive.
|
|
141
|
+
const inputRequests = Object.fromEntries(internal.inputRequests);
|
|
142
|
+
return { ...base, status: "input_required", inputRequests };
|
|
143
|
+
}
|
|
144
|
+
case "completed":
|
|
145
|
+
return { ...base, status: "completed", result: internal.result };
|
|
146
|
+
case "failed":
|
|
147
|
+
return { ...base, status: "failed", error: internal.error };
|
|
148
|
+
case "cancelled":
|
|
149
|
+
return { ...base, status: "cancelled" };
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Wrap a run() result in the required `Record<string, unknown>` shape.
|
|
154
|
+
*
|
|
155
|
+
* Tool handlers may return any serialisable value. The spec models
|
|
156
|
+
* `CompletedTask.result` as an object, so a primitive or array is boxed
|
|
157
|
+
* under `"value"` rather than discarded or cast dangerously.
|
|
158
|
+
*/
|
|
159
|
+
function normaliseResult(raw) {
|
|
160
|
+
if (isRecord(raw))
|
|
161
|
+
return raw;
|
|
162
|
+
return { value: raw };
|
|
163
|
+
}
|
|
164
|
+
// ── Public factory / type-guard ────────────────────────────────────────────────
|
|
165
|
+
/**
|
|
166
|
+
* Factory for tool handlers that want to run asynchronously.
|
|
167
|
+
*
|
|
168
|
+
* Returns an `AsyncTaskDescriptor` the framework detects and routes through
|
|
169
|
+
* the `TaskStore`. The handler never sees the store directly — it only receives
|
|
170
|
+
* the `TaskController` when `run()` is invoked.
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* ```typescript
|
|
174
|
+
* // Inside a tool handler:
|
|
175
|
+
* return createTask({ ttlMs: 60_000, pollIntervalMs: 3_000 }, async (ctrl) => {
|
|
176
|
+
* const rows = await scanWholeTable(args, ctrl.signal);
|
|
177
|
+
* return { rows };
|
|
178
|
+
* });
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
export function createTask(options, run) {
|
|
182
|
+
return { _type: "async-task", options, run };
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Type guard used by the transport to distinguish an `AsyncTaskDescriptor`
|
|
186
|
+
* from an ordinary tool result.
|
|
187
|
+
*
|
|
188
|
+
* Checks the private `_type` discriminant rather than shape-matching public
|
|
189
|
+
* fields, so a tool result that happens to carry similar fields is never
|
|
190
|
+
* misidentified.
|
|
191
|
+
*/
|
|
192
|
+
export function isAsyncTaskDescriptor(v) {
|
|
193
|
+
// Two-step cast through `unknown` is intentional: `Record<string, unknown>`
|
|
194
|
+
// and `AsyncTaskDescriptor` have no proven overlap, so TypeScript requires
|
|
195
|
+
// the intermediate step. The runtime check on `_type` and `run` is the
|
|
196
|
+
// actual guard; the cast merely satisfies the type checker.
|
|
197
|
+
return isRecord(v) && v["_type"] === "async-task" &&
|
|
198
|
+
typeof v.run === "function";
|
|
199
|
+
}
|
|
200
|
+
// ── TaskStore ──────────────────────────────────────────────────────────────────
|
|
201
|
+
const DEFAULT_OPTIONS = {
|
|
202
|
+
defaultTtlMs: 3_600_000, // 1 hour — see TaskStoreOptions.defaultTtlMs doc
|
|
203
|
+
maxTasks: 5_000, // see TaskStoreOptions.maxTasks doc
|
|
204
|
+
cleanupIntervalMs: 5 * 60 * 1_000, // 5 minutes, matching session cleanup
|
|
205
|
+
};
|
|
206
|
+
/**
|
|
207
|
+
* Server-side store for background tasks spawned by the Tasks extension.
|
|
208
|
+
*
|
|
209
|
+
* Responsibilities:
|
|
210
|
+
* - Issue unique, unguessable task IDs.
|
|
211
|
+
* - Store task state and transition it as work progresses.
|
|
212
|
+
* - Route client input (tasks/update) to waiting requireInput() calls.
|
|
213
|
+
* - Enforce TTL expiry and a hard memory cap via eviction.
|
|
214
|
+
* - Surface a notification callback for Track G (subscriptions/listen).
|
|
215
|
+
*
|
|
216
|
+
* All public methods are synchronous (except the background work itself)
|
|
217
|
+
* to ensure the tasks/get → tasks/update → tasks/cancel request flow
|
|
218
|
+
* never blocks on I/O inside the store.
|
|
219
|
+
*/
|
|
220
|
+
export class TaskStore {
|
|
221
|
+
_options;
|
|
222
|
+
_tasks = new Map();
|
|
223
|
+
_cleanupTimer = null;
|
|
224
|
+
constructor(options) {
|
|
225
|
+
this._options = { ...DEFAULT_OPTIONS, ...options };
|
|
226
|
+
// Only start a cleanup timer if requested — tests pass cleanupIntervalMs: 0
|
|
227
|
+
// to disable it and drive cleanup manually.
|
|
228
|
+
if (this._options.cleanupIntervalMs > 0) {
|
|
229
|
+
this._cleanupTimer = setInterval(() => this._sweep(), this._options.cleanupIntervalMs);
|
|
230
|
+
// Unref'd: a housekeeping ticker must never be the reason a process cannot
|
|
231
|
+
// exit. Without this, forgetting dispose() — or failing before ever
|
|
232
|
+
// reaching it — hangs the runtime instead of merely leaking a timer.
|
|
233
|
+
this._options.unrefTimer?.(this._cleanupTimer);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Spawn a background task from an `AsyncTaskDescriptor`.
|
|
238
|
+
*
|
|
239
|
+
* MUST be called after verifying the client declared the tasks capability.
|
|
240
|
+
*
|
|
241
|
+
* Returns the `CreateTaskResultFields` the transport should send as the
|
|
242
|
+
* result of the triggering tools/call, with `resultType: "task"` added by
|
|
243
|
+
* the caller. (stampResult() sets `"complete"` and must NOT be called here.)
|
|
244
|
+
*
|
|
245
|
+
* Spec §Task Creation: "Server MUST NOT return CreateTaskResult until the
|
|
246
|
+
* task is durably created — a subsequent tasks/get for the returned taskId
|
|
247
|
+
* must resolve immediately." Fulfilled: we insert into `_tasks` before
|
|
248
|
+
* returning.
|
|
249
|
+
*/
|
|
250
|
+
spawn(descriptor, owner, formatResult) {
|
|
251
|
+
// A tool handler can settle after shutdown began — the pipeline is async and
|
|
252
|
+
// abort is cooperative. Spawning then would start un-abortable work in a store
|
|
253
|
+
// nobody will ever drain again, and the task would outlive the server that
|
|
254
|
+
// created it.
|
|
255
|
+
if (this._disposed) {
|
|
256
|
+
throw new Error("[TaskStore] Cannot spawn: the store has been disposed (server is stopping or stopped).");
|
|
257
|
+
}
|
|
258
|
+
const taskId = generateTaskId();
|
|
259
|
+
const now = new Date().toISOString();
|
|
260
|
+
// Spec is silent on a default; fill from store options when the handler
|
|
261
|
+
// omits ttlMs, and honour `null` explicitly (no expiry).
|
|
262
|
+
const ttlMs = descriptor.options.ttlMs !== undefined
|
|
263
|
+
? descriptor.options.ttlMs
|
|
264
|
+
: this._options.defaultTtlMs;
|
|
265
|
+
const abortController = new AbortController();
|
|
266
|
+
// Allocate internal task. runPromise is assigned below AFTER the
|
|
267
|
+
// controller is built, but before spawn() returns. The controller only
|
|
268
|
+
// reads/writes other fields, so the placeholder is safe for the window
|
|
269
|
+
// between allocation and assignment.
|
|
270
|
+
const internal = {
|
|
271
|
+
taskId,
|
|
272
|
+
owner,
|
|
273
|
+
status: "working",
|
|
274
|
+
createdAt: now,
|
|
275
|
+
lastUpdatedAt: now,
|
|
276
|
+
ttlMs,
|
|
277
|
+
pollIntervalMs: descriptor.options.pollIntervalMs ?? 5_000,
|
|
278
|
+
...(descriptor.options.statusMessage !== undefined
|
|
279
|
+
? { statusMessage: descriptor.options.statusMessage }
|
|
280
|
+
: {}),
|
|
281
|
+
abortController,
|
|
282
|
+
runPromise: Promise.resolve(), // replaced below
|
|
283
|
+
inputRequests: new Map(),
|
|
284
|
+
answeredKeys: new Set(),
|
|
285
|
+
pendingResolvers: new Map(),
|
|
286
|
+
};
|
|
287
|
+
// Build the TaskController. Captures `internal` by reference so every
|
|
288
|
+
// field update inside run() is visible to concurrent get() calls.
|
|
289
|
+
const ctrl = {
|
|
290
|
+
signal: abortController.signal,
|
|
291
|
+
requireInput: (key, request) => {
|
|
292
|
+
const validated = canonicaliseTaskInputRequest(key, request);
|
|
293
|
+
if (!validated.ok) {
|
|
294
|
+
// A malformed server-side request cannot be sent back to the client.
|
|
295
|
+
// Unlike an HTTP request, the correct boundary response is a terminal
|
|
296
|
+
// task: the caller already holds this task's id and can observe the
|
|
297
|
+
// concrete failure through tasks/get. Mark it before rejecting so a
|
|
298
|
+
// handler that catches the rejection cannot accidentally complete the
|
|
299
|
+
// task afterwards.
|
|
300
|
+
if (!isTerminal(internal.status)) {
|
|
301
|
+
internal.status = "failed";
|
|
302
|
+
internal.error = {
|
|
303
|
+
code: -32603,
|
|
304
|
+
message: validated.message,
|
|
305
|
+
};
|
|
306
|
+
internal.lastUpdatedAt = new Date().toISOString();
|
|
307
|
+
internal.terminalAt = Date.now();
|
|
308
|
+
// Reject any earlier outstanding input waits too. Their abort
|
|
309
|
+
// handlers remove the requests, so no stale input can survive this
|
|
310
|
+
// terminal state.
|
|
311
|
+
abortController.abort();
|
|
312
|
+
this._notify(internal);
|
|
313
|
+
}
|
|
314
|
+
return Promise.reject(new Error(validated.message));
|
|
315
|
+
}
|
|
316
|
+
const canonicalKey = validated.key;
|
|
317
|
+
if (isTerminal(internal.status)) {
|
|
318
|
+
return Promise.reject(new Error(`Cannot require task input after the task is ${internal.status}.`));
|
|
319
|
+
}
|
|
320
|
+
// Spec §Task Update Requests: key uniqueness is lifetime-scoped, not
|
|
321
|
+
// just to currently-outstanding requests. A key used, answered, and
|
|
322
|
+
// re-submitted is a server bug, not a client one.
|
|
323
|
+
if (internal.answeredKeys.has(canonicalKey)) {
|
|
324
|
+
return Promise.reject(new Error(`Input request key "${canonicalKey}" has already been answered in this task ` +
|
|
325
|
+
`and cannot be reused (spec §Task Update Requests prohibits key reuse ` +
|
|
326
|
+
`after the client has delivered a response).`));
|
|
327
|
+
}
|
|
328
|
+
if (internal.pendingResolvers.has(canonicalKey)) {
|
|
329
|
+
return Promise.reject(new Error(`Input request key "${canonicalKey}" is already outstanding in this task.`));
|
|
330
|
+
}
|
|
331
|
+
// Register the outstanding request and transition to input_required.
|
|
332
|
+
internal.inputRequests.set(canonicalKey, validated.request);
|
|
333
|
+
internal.lastUpdatedAt = new Date().toISOString();
|
|
334
|
+
if (internal.status === "working") {
|
|
335
|
+
internal.status = "input_required";
|
|
336
|
+
this._notify(internal);
|
|
337
|
+
}
|
|
338
|
+
return new Promise((resolve, reject) => {
|
|
339
|
+
internal.pendingResolvers.set(canonicalKey, resolve);
|
|
340
|
+
// Fire immediately if the abort already happened (race-free via
|
|
341
|
+
// the AbortSignal contract: addEventListener fires synchronously
|
|
342
|
+
// when the signal is already aborted).
|
|
343
|
+
const onAbort = () => {
|
|
344
|
+
if (!internal.pendingResolvers.has(canonicalKey))
|
|
345
|
+
return; // already answered
|
|
346
|
+
internal.pendingResolvers.delete(canonicalKey);
|
|
347
|
+
internal.inputRequests.delete(canonicalKey);
|
|
348
|
+
reject(new DOMException("Task was cancelled", "AbortError"));
|
|
349
|
+
};
|
|
350
|
+
abortController.signal.addEventListener("abort", onAbort, {
|
|
351
|
+
once: true,
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
},
|
|
355
|
+
setStatusMessage: (msg) => {
|
|
356
|
+
if (isTerminal(internal.status))
|
|
357
|
+
return;
|
|
358
|
+
internal.statusMessage = msg;
|
|
359
|
+
internal.lastUpdatedAt = new Date().toISOString();
|
|
360
|
+
},
|
|
361
|
+
};
|
|
362
|
+
// Start background work. Errors in run() are caught here to drive state
|
|
363
|
+
// transitions — they must not surface as unhandled rejections, which
|
|
364
|
+
// would crash the Deno process.
|
|
365
|
+
const runPromise = descriptor.run(ctrl).then((rawResult) => {
|
|
366
|
+
// Guard: a TTL sweep may have already marked this task failed while
|
|
367
|
+
// the run() promise was settling. Honour the first terminal state.
|
|
368
|
+
if (isTerminal(internal.status))
|
|
369
|
+
return;
|
|
370
|
+
// A completed task carries the result the original request would have
|
|
371
|
+
// returned — a CallToolResult for tools/call — not the handler's raw
|
|
372
|
+
// return value. The store stays ignorant of MCP result shapes: the
|
|
373
|
+
// transport injects the conversion it already uses for synchronous
|
|
374
|
+
// calls, so both paths produce identical output for the same handler.
|
|
375
|
+
//
|
|
376
|
+
// The formatter can throw: it serialises arbitrary handler output, and a
|
|
377
|
+
// BigInt or a circular structure is enough. Left unguarded that produced
|
|
378
|
+
// a task marked `completed` with NO result — the one state a client
|
|
379
|
+
// polling for a result cannot make sense of — plus an unhandled
|
|
380
|
+
// rejection. Treat it as what it is: the work finished, the result cannot
|
|
381
|
+
// be represented.
|
|
382
|
+
try {
|
|
383
|
+
internal.result = formatResult
|
|
384
|
+
? formatResult(rawResult)
|
|
385
|
+
: normaliseResult(rawResult);
|
|
386
|
+
internal.status = "completed";
|
|
387
|
+
}
|
|
388
|
+
catch (formatError) {
|
|
389
|
+
internal.status = "failed";
|
|
390
|
+
internal.error = {
|
|
391
|
+
code: -32603,
|
|
392
|
+
message: `Task result could not be serialised: ${formatError instanceof Error
|
|
393
|
+
? formatError.message
|
|
394
|
+
: String(formatError)}`,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
internal.lastUpdatedAt = new Date().toISOString();
|
|
398
|
+
internal.terminalAt = Date.now();
|
|
399
|
+
this._notify(internal);
|
|
400
|
+
}, (error) => {
|
|
401
|
+
if (isTerminal(internal.status))
|
|
402
|
+
return; // TTL/eviction won the race
|
|
403
|
+
const nowStr = new Date().toISOString();
|
|
404
|
+
internal.lastUpdatedAt = nowStr;
|
|
405
|
+
internal.terminalAt = Date.now();
|
|
406
|
+
// Distinguish abort (→ cancelled) from JSON-RPC error (→ failed)
|
|
407
|
+
// from generic error (→ failed with -32603).
|
|
408
|
+
if (error instanceof DOMException && error.name === "AbortError") {
|
|
409
|
+
internal.status = "cancelled";
|
|
410
|
+
}
|
|
411
|
+
else if (isJsonRpcError(error)) {
|
|
412
|
+
internal.status = "failed";
|
|
413
|
+
// Preserve any extra fields from the thrown object (e.g. `data`).
|
|
414
|
+
internal.error = { ...error };
|
|
415
|
+
}
|
|
416
|
+
else {
|
|
417
|
+
// Spec: failed is for protocol-level errors. If a tool throws a
|
|
418
|
+
// plain Error, we treat it as Internal Error (-32603) to stay
|
|
419
|
+
// spec-compliant rather than swallowing it.
|
|
420
|
+
internal.status = "failed";
|
|
421
|
+
internal.error = {
|
|
422
|
+
code: -32603,
|
|
423
|
+
message: error instanceof Error ? error.message : String(error),
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
this._notify(internal);
|
|
427
|
+
});
|
|
428
|
+
internal.runPromise = runPromise;
|
|
429
|
+
// Evict if over cap BEFORE inserting, so the new task is always stored.
|
|
430
|
+
this._maybeEvict();
|
|
431
|
+
// Register BEFORE returning — spec MUST §Task Creation.
|
|
432
|
+
this._tasks.set(taskId, internal);
|
|
433
|
+
return toDetailedTask(internal);
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Service a tasks/get request.
|
|
437
|
+
*
|
|
438
|
+
* Returns `null` when the taskId is unknown or has been purged
|
|
439
|
+
* (caller returns -32602).
|
|
440
|
+
*
|
|
441
|
+
* Spec §Task Polling: "If status is 'working', return Task with status
|
|
442
|
+
* 'working'; if 'input_required', return Task with inputRequests containing
|
|
443
|
+
* all outstanding server-to-client requests; if 'completed', return Task
|
|
444
|
+
* with result; if 'cancelled', return Task with status 'cancelled'; if
|
|
445
|
+
* 'failed', return Task with error."
|
|
446
|
+
*/
|
|
447
|
+
get(taskId, caller) {
|
|
448
|
+
const internal = this._tasks.get(taskId);
|
|
449
|
+
if (!internal)
|
|
450
|
+
return null;
|
|
451
|
+
// Indistinguishable from "unknown task" on purpose: telling a caller that a
|
|
452
|
+
// task exists but is not theirs confirms the id, which is exactly what an
|
|
453
|
+
// unguessable handle is meant to withhold.
|
|
454
|
+
if (internal.owner !== caller)
|
|
455
|
+
return null;
|
|
456
|
+
return toDetailedTask(internal);
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Service a tasks/update request.
|
|
460
|
+
*
|
|
461
|
+
* Delivers client responses to outstanding requireInput() calls.
|
|
462
|
+
*
|
|
463
|
+
* Returns `true` on success, `false` if the taskId is unknown
|
|
464
|
+
* (caller SHOULD return -32602 per spec §Task Update Requests).
|
|
465
|
+
*
|
|
466
|
+
* Spec §Task Update Requests:
|
|
467
|
+
* - "Server SHOULD ignore inputResponses mapped to unknown, already-answered,
|
|
468
|
+
* or superseded keys."
|
|
469
|
+
* - "Server MAY accept a partial set of responses."
|
|
470
|
+
*
|
|
471
|
+
* Silently ignores responses for unknown keys instead of erroring, because
|
|
472
|
+
* a stale retry from an impatient client must not break an otherwise healthy
|
|
473
|
+
* task.
|
|
474
|
+
*/
|
|
475
|
+
update(taskId, inputResponses, caller) {
|
|
476
|
+
const internal = this._tasks.get(taskId);
|
|
477
|
+
if (!internal || internal.owner !== caller)
|
|
478
|
+
return false;
|
|
479
|
+
for (const [key, rawValue] of Object.entries(inputResponses)) {
|
|
480
|
+
const resolver = internal.pendingResolvers.get(key);
|
|
481
|
+
if (!resolver)
|
|
482
|
+
continue; // unknown / already-answered key — ignore
|
|
483
|
+
internal.pendingResolvers.delete(key);
|
|
484
|
+
internal.inputRequests.delete(key);
|
|
485
|
+
internal.answeredKeys.add(key);
|
|
486
|
+
internal.lastUpdatedAt = new Date().toISOString();
|
|
487
|
+
// Normalise the response to Record — the spec treats the value as an
|
|
488
|
+
// object; a primitive is boxed under "value" rather than dropping it.
|
|
489
|
+
const response = isRecord(rawValue)
|
|
490
|
+
? rawValue
|
|
491
|
+
: { value: rawValue };
|
|
492
|
+
resolver(response);
|
|
493
|
+
}
|
|
494
|
+
// Move back to "working" when all pending resolvers are satisfied.
|
|
495
|
+
// The run() promise may immediately re-enter "input_required" by calling
|
|
496
|
+
// requireInput() again, but that transition happens inside run() before
|
|
497
|
+
// this method returns — which is fine because we check pendingResolvers.size.
|
|
498
|
+
if (internal.status === "input_required" &&
|
|
499
|
+
internal.pendingResolvers.size === 0) {
|
|
500
|
+
internal.status = "working";
|
|
501
|
+
internal.lastUpdatedAt = new Date().toISOString();
|
|
502
|
+
this._notify(internal);
|
|
503
|
+
}
|
|
504
|
+
return true;
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* Service a tasks/cancel request.
|
|
508
|
+
*
|
|
509
|
+
* Returns `true` if the task was found (regardless of whether the work
|
|
510
|
+
* actually stops). Returns `false` if unknown (caller SHOULD return -32602).
|
|
511
|
+
*
|
|
512
|
+
* Spec §Task Cancellation: "Cancellation is cooperative: the server is not
|
|
513
|
+
* obligated to actually stop the work; it only acknowledges intent. Eventual
|
|
514
|
+
* transition to 'cancelled' is not guaranteed."
|
|
515
|
+
*
|
|
516
|
+
* `notifications/cancelled` MUST NOT be used for task cancellation — the spec
|
|
517
|
+
* reserves a dedicated `notifications/tasks/statusChanged` notification for
|
|
518
|
+
* Track G instead.
|
|
519
|
+
*/
|
|
520
|
+
cancel(taskId, caller) {
|
|
521
|
+
const internal = this._tasks.get(taskId);
|
|
522
|
+
if (!internal || internal.owner !== caller)
|
|
523
|
+
return false;
|
|
524
|
+
if (!isTerminal(internal.status)) {
|
|
525
|
+
// Signal the AbortController so run() can observe ctrl.signal.aborted.
|
|
526
|
+
// We do NOT await runPromise here — the acknowledgement is immediate.
|
|
527
|
+
internal.abortController.abort();
|
|
528
|
+
}
|
|
529
|
+
return true;
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Signal all in-flight AbortControllers.
|
|
533
|
+
*
|
|
534
|
+
* Called by McpApp.stop() before awaiting httpServer.shutdown(), giving
|
|
535
|
+
* background Promises a chance to observe the signal and exit early.
|
|
536
|
+
* Does NOT await completion — best-effort on graceful shutdown.
|
|
537
|
+
*/
|
|
538
|
+
drain() {
|
|
539
|
+
for (const internal of this._tasks.values()) {
|
|
540
|
+
if (!isTerminal(internal.status)) {
|
|
541
|
+
internal.abortController.abort();
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Clear the cleanup interval.
|
|
547
|
+
*
|
|
548
|
+
* Must be called after drain() in McpApp.stop() to release the timer
|
|
549
|
+
* and let the process exit cleanly.
|
|
550
|
+
*/
|
|
551
|
+
/** True once dispose() ran; suppresses any late notification. */
|
|
552
|
+
_disposed = false;
|
|
553
|
+
/** Whether this store has been torn down and must not accept new work. */
|
|
554
|
+
get isDisposed() {
|
|
555
|
+
return this._disposed;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Emit a status change, unless the store was disposed.
|
|
559
|
+
*
|
|
560
|
+
* A drained task's `run()` promise can still settle after dispose() — abort is
|
|
561
|
+
* cooperative, so work that ignores the signal keeps going. Pushing that
|
|
562
|
+
* transition to a subscriber whose transport is already torn down is at best
|
|
563
|
+
* useless and at worst a write to a closed stream.
|
|
564
|
+
*/
|
|
565
|
+
_notify(internal) {
|
|
566
|
+
if (this._disposed)
|
|
567
|
+
return;
|
|
568
|
+
this._options.onNotification?.(toDetailedTask(internal));
|
|
569
|
+
}
|
|
570
|
+
dispose() {
|
|
571
|
+
this._disposed = true;
|
|
572
|
+
if (this._cleanupTimer !== null) {
|
|
573
|
+
clearInterval(this._cleanupTimer);
|
|
574
|
+
this._cleanupTimer = null;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
// ── Introspection (tests + diagnostics) ─────────────────────────────────────
|
|
578
|
+
/** Current number of tracked tasks (terminal + non-terminal). */
|
|
579
|
+
get size() {
|
|
580
|
+
return this._tasks.size;
|
|
581
|
+
}
|
|
582
|
+
// ── Private helpers ──────────────────────────────────────────────────────────
|
|
583
|
+
/**
|
|
584
|
+
* Sweep for TTL-expired tasks and mark them failed.
|
|
585
|
+
*
|
|
586
|
+
* Spec §Task Polling: "Server MAY mark a task as 'failed' at any point
|
|
587
|
+
* after the TTL elapses, and subsequently delete it at any time. Returning
|
|
588
|
+
* -32602 for an expired deleted task is compliant."
|
|
589
|
+
*
|
|
590
|
+
* We mark `failed` immediately on expiry and let maxTasks eviction handle
|
|
591
|
+
* physical deletion — this avoids a second timestamp-based deletion pass.
|
|
592
|
+
*/
|
|
593
|
+
_sweep() {
|
|
594
|
+
const now = Date.now();
|
|
595
|
+
for (const internal of this._tasks.values()) {
|
|
596
|
+
if (isTerminal(internal.status))
|
|
597
|
+
continue;
|
|
598
|
+
if (internal.ttlMs === null)
|
|
599
|
+
continue;
|
|
600
|
+
const createdMs = new Date(internal.createdAt).getTime();
|
|
601
|
+
if (now - createdMs <= internal.ttlMs)
|
|
602
|
+
continue;
|
|
603
|
+
// Abort to unblock any pending requireInput() calls.
|
|
604
|
+
internal.abortController.abort();
|
|
605
|
+
internal.status = "failed";
|
|
606
|
+
internal.error = {
|
|
607
|
+
code: -32603,
|
|
608
|
+
message: `Task TTL of ${internal.ttlMs}ms elapsed without completing.`,
|
|
609
|
+
};
|
|
610
|
+
internal.lastUpdatedAt = new Date().toISOString();
|
|
611
|
+
internal.terminalAt = now;
|
|
612
|
+
this._notify(internal);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Enforce the maxTasks cap before inserting a new task.
|
|
617
|
+
*
|
|
618
|
+
* Eviction order (spec is silent; justified in TaskStoreOptions.maxTasks):
|
|
619
|
+
* 1. Terminal tasks, oldest-terminalAt first (already served their purpose).
|
|
620
|
+
* 2. Non-terminal tasks, oldest-createdAt first (least likely to be polled
|
|
621
|
+
* soon), with abort signal sent to allow cooperative cleanup.
|
|
622
|
+
*/
|
|
623
|
+
_maybeEvict() {
|
|
624
|
+
if (this._tasks.size < this._options.maxTasks)
|
|
625
|
+
return;
|
|
626
|
+
// Phase 1: evict terminal tasks by age.
|
|
627
|
+
const terminal = [...this._tasks.values()]
|
|
628
|
+
.filter((t) => isTerminal(t.status))
|
|
629
|
+
.sort((a, b) => (a.terminalAt ?? 0) - (b.terminalAt ?? 0));
|
|
630
|
+
for (const t of terminal) {
|
|
631
|
+
if (this._tasks.size < this._options.maxTasks)
|
|
632
|
+
return;
|
|
633
|
+
this._tasks.delete(t.taskId);
|
|
634
|
+
}
|
|
635
|
+
// Phase 2: evict oldest non-terminal tasks.
|
|
636
|
+
if (this._tasks.size >= this._options.maxTasks) {
|
|
637
|
+
const nonTerminal = [...this._tasks.values()]
|
|
638
|
+
.filter((t) => !isTerminal(t.status))
|
|
639
|
+
.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
|
640
|
+
for (const t of nonTerminal) {
|
|
641
|
+
if (this._tasks.size < this._options.maxTasks)
|
|
642
|
+
return;
|
|
643
|
+
// Give the task a chance to shut down gracefully.
|
|
644
|
+
t.abortController.abort();
|
|
645
|
+
this._tasks.delete(t.taskId);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
}
|