@casys/mcp-server 0.22.0 → 0.23.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/src/mcp-app.ts CHANGED
@@ -34,6 +34,7 @@ import { createRateLimitMiddleware } from "./middleware/rate-limit.js";
34
34
  import { createValidationMiddleware } from "./middleware/validation.js";
35
35
  import { createBackpressureMiddleware } from "./middleware/backpressure.js";
36
36
  import type {
37
+ McpLogLevel,
37
38
  Middleware,
38
39
  MiddlewareContext,
39
40
  MiddlewareResult,
@@ -71,8 +72,34 @@ import {
71
72
  MCP_APP_URI_SCHEME,
72
73
  } from "./types.js";
73
74
  import { discoverViewers, resolveViewerDistPath } from "./ui/viewer-utils.js";
74
- import type { DirEntry, DiscoverViewersFS } from "./ui/viewer-utils.js";
75
+ import type { DiscoverViewersFS } from "./ui/viewer-utils.js";
75
76
  import { buildCspHeader, injectCspMetaTag } from "./security/csp.js";
77
+ import {
78
+ collectMirroredParams,
79
+ type MirroredParam,
80
+ validateRequestHeaders,
81
+ } from "./transport/request-headers.js";
82
+ import {
83
+ type DetailedTask,
84
+ isAsyncTaskDescriptor,
85
+ TaskStore,
86
+ } from "./tasks/mod.js";
87
+ import {
88
+ checkInputRequestCapabilities,
89
+ importStateKey,
90
+ type InputRequestEntry,
91
+ type InputRequiredSignal,
92
+ paramsDigest,
93
+ sealRequestState,
94
+ verifyRequestState,
95
+ } from "./mrtr/mod.js";
96
+ import {
97
+ buildAcknowledgedMessage,
98
+ encodeSSEEvent,
99
+ type SubscriptionFilter,
100
+ SubscriptionRegistry,
101
+ type SubscriptionSink,
102
+ } from "./subscriptions/subscription-registry.js";
76
103
  import { ServerMetrics } from "./observability/metrics.js";
77
104
  import { endToolCallSpan, startToolCallSpan } from "./observability/otel.js";
78
105
 
@@ -188,15 +215,235 @@ const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
188
215
  "2025-11-25",
189
216
  ];
190
217
 
218
+ /** Namespaced serverInfo key in a result's _meta (spec 2026-07-28, SHOULD) */
219
+ const STATELESS_SERVER_INFO_KEY = "io.modelcontextprotocol/serverInfo";
220
+
221
+ /**
222
+ * Namespaced per-request log level in params._meta (spec 2026-07-28).
223
+ * Replaces the removed `logging/setLevel` RPC: the level is now scoped to the
224
+ * request that asked for it, so there is no server-side level to mutate.
225
+ */
226
+ const STATELESS_LOG_LEVEL_KEY = "io.modelcontextprotocol/logLevel";
227
+
228
+ /** Protocol version whose wire format this server implements natively */
229
+ const SPEC_2026_07_28 = "2026-07-28";
230
+
231
+ /**
232
+ * Tasks extension identifier (SEP-2663).
233
+ *
234
+ * Declaring it in `McpAppOptions.extensions` is what switches the extension on.
235
+ * The spec forbids returning a task handle to a client that did not declare
236
+ * support, and forbids advertising an extension we do not implement — so the
237
+ * declaration gates both directions.
238
+ */
239
+ const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
240
+
191
241
  /** Version echoed in MCP-Protocol-Version header on error responses (server's stable baseline) */
192
242
  const STATELESS_FALLBACK_VERSION = "2025-06-18";
193
243
 
194
244
  const JSONRPC_INVALID_PARAMS = ErrorCode.InvalidParams;
195
- const MCP_UNSUPPORTED_PROTOCOL_VERSION = -32004;
245
+
246
+ // ── Error codes (spec 2026-07-28, allocation policy) ────────────────────────
247
+ //
248
+ // The final spec partitions the JSON-RPC server-error range:
249
+ // -32000..-32019 implementation-defined (existing SDK usage grandfathered)
250
+ // -32020..-32099 reserved for the MCP specification
251
+ //
252
+ // The codes below were renumbered between the May 2026 Release Candidate — which
253
+ // 0.21.0 shipped against — and the final revision. Do not "restore" the RC
254
+ // values: -32001 and -32004 no longer carry these MCP-defined meanings.
255
+ //
256
+ // Note the policy is stricter than "the low range is grandfathered": the spec
257
+ // says new implementations SHOULD NOT use -32000..-32019 at all, and MUST NOT
258
+ // emit -32002 (which 2025-11-25 used for resource-not-found). Our auth and
259
+ // session errors therefore live outside the reserved range entirely — see
260
+ // auth/middleware.ts.
261
+
262
+ /** Headers disagree with the request body, or a required header is missing. */
263
+ const MCP_HEADER_MISMATCH = -32020;
264
+
265
+ /**
266
+ * Client did not declare a capability the request requires.
267
+ *
268
+ * Emitted by the Tasks extension guard. `data.requiredCapabilities` must list
269
+ * the missing capabilities alongside it.
270
+ */
271
+ const MCP_MISSING_REQUIRED_CLIENT_CAPABILITY = -32021;
272
+
273
+ /** Requested protocol version is not one this server implements. */
274
+ const MCP_UNSUPPORTED_PROTOCOL_VERSION = -32022;
196
275
 
197
276
  interface StatelessClientMeta {
198
277
  readonly clientInfo?: Implementation;
199
278
  readonly clientCapabilities?: ClientCapabilities;
279
+ readonly logLevel?: McpLogLevel;
280
+ }
281
+
282
+ /** Valid `io.modelcontextprotocol/logLevel` values (RFC 5424 severities). */
283
+ const MCP_LOG_LEVELS: readonly McpLogLevel[] = [
284
+ "debug",
285
+ "info",
286
+ "notice",
287
+ "warning",
288
+ "error",
289
+ "critical",
290
+ "alert",
291
+ "emergency",
292
+ ];
293
+
294
+ /**
295
+ * Read the per-request log level out of `params._meta`.
296
+ *
297
+ * An unrecognized value is dropped rather than rejected: the level is an
298
+ * optional hint, and failing a whole tool call because a client sent
299
+ * `"verbose"` would be a worse outcome than emitting nothing.
300
+ */
301
+ function readLogLevel(meta: Record<string, unknown>): McpLogLevel | undefined {
302
+ const raw = meta[STATELESS_LOG_LEVEL_KEY];
303
+ return typeof raw === "string" && MCP_LOG_LEVELS.includes(raw as McpLogLevel)
304
+ ? raw as McpLogLevel
305
+ : undefined;
306
+ }
307
+
308
+ /**
309
+ * Sentinel used when there is no authentication at all.
310
+ *
311
+ * Deliberately not a plausible subject value: the NUL prefix cannot appear in a
312
+ * JWT `sub`, so it can never collide with a real principal.
313
+ */
314
+ const MRTR_NO_AUTH_PRINCIPAL = "\u0000unauthenticated";
315
+
316
+ /**
317
+ * Principal to bind a `requestState` to.
318
+ *
319
+ * Three cases, only two of which are acceptable:
320
+ *
321
+ * 1. **No auth configured** — every caller shares one authority by definition, so
322
+ * there is no boundary to enforce and the sentinel above is honest about it.
323
+ * The method and argument bindings still apply.
324
+ * 2. **Authenticated with a subject** — the binding separates callers, which is
325
+ * the case it exists for.
326
+ * 3. **Authenticated without a usable subject** — `AuthInfo.subject` falls back to
327
+ * `"unknown"` for a valid token carrying no `sub` claim. Sealing against that
328
+ * would put every such caller under one identity: a token minted for one could
329
+ * be spent by another, while the code reads as though the binding were
330
+ * enforced. That is worse than no auth, because it is invisible. Throws.
331
+ */
332
+ function callerPrincipal(authInfo: AuthInfo | undefined): string | null {
333
+ if (authInfo === undefined) return MRTR_NO_AUTH_PRINCIPAL;
334
+ const subject = authInfo.subject;
335
+ if (subject === undefined || subject === "" || subject === "unknown") {
336
+ // `null`, not a throw: the task handlers call this outside any try/catch, so
337
+ // a throw would surface through the POST-level catch as -32700 "Parse error"
338
+ // — a diagnosis pointing nowhere near a misconfigured auth provider. The
339
+ // caller turns this into an explicit error instead.
340
+ return null;
341
+ }
342
+ return subject;
343
+ }
344
+
345
+ /**
346
+ * Authorization key for a task-related request.
347
+ *
348
+ * Defaults to the authenticated principal. A consumer whose authorization depends
349
+ * on more than identity — a tenant, an organisation, a workspace — supplies
350
+ * `taskOwnerKey` so that dimension becomes part of the key. Without it, binding to
351
+ * the subject alone leaves a task created under one tenant reachable from another
352
+ * by the same user.
353
+ */
354
+ async function taskOwnerKeyFor(
355
+ options: McpAppOptions,
356
+ authInfo: AuthInfo | undefined,
357
+ request: Request | undefined,
358
+ principal: string,
359
+ ): Promise<string | null> {
360
+ if (options.taskOwnerKey === undefined || request === undefined) {
361
+ return principal;
362
+ }
363
+ let key: unknown;
364
+ try {
365
+ key = await options.taskOwnerKey(authInfo, request);
366
+ } catch {
367
+ // A throwing hook is a consumer bug, but it must fail closed and legibly —
368
+ // not escape to the POST-level catch and be reported as -32700 Parse error.
369
+ return null;
370
+ }
371
+ // An empty or non-string key would put every caller under one owner, undoing
372
+ // the isolation the hook exists to provide — and `""` is exactly what the
373
+ // obvious implementation yields when a header is missing. Refuse it rather
374
+ // than silently sharing tasks between callers.
375
+ if (typeof key !== "string" || key.length === 0) return null;
376
+ return key;
377
+ }
378
+
379
+ /** The error to return when `taskOwnerKey` produced an unusable value. */
380
+ function noOwnerKeyError(id: unknown, version: string): Response {
381
+ return jsonRpcResponse(
382
+ {
383
+ jsonrpc: "2.0",
384
+ id,
385
+ error: {
386
+ code: ErrorCode.InternalError,
387
+ message:
388
+ "taskOwnerKey returned an empty or non-string value, which would place every caller under one owner.",
389
+ data: {
390
+ problem: "invalid_task_owner_key",
391
+ recovery:
392
+ 'Return a non-empty string. If the value it derives from can be absent, decide explicitly what an anonymous caller\'s key is rather than letting it fall to "".',
393
+ },
394
+ },
395
+ },
396
+ 500,
397
+ { "MCP-Protocol-Version": version },
398
+ );
399
+ }
400
+
401
+ /** The error to return when no caller boundary can be established. */
402
+ function noPrincipalError(id: unknown, version: string): Response {
403
+ return jsonRpcResponse(
404
+ {
405
+ jsonrpc: "2.0",
406
+ id,
407
+ error: {
408
+ code: ErrorCode.InternalError,
409
+ message:
410
+ "Server cannot establish a caller identity: the auth provider returned no usable subject for an authenticated request.",
411
+ data: {
412
+ problem: "no_caller_principal",
413
+ recovery:
414
+ "Configure the auth provider to supply a subject claim, or disable auth if all callers genuinely share one authority.",
415
+ },
416
+ },
417
+ },
418
+ 500,
419
+ { "MCP-Protocol-Version": version },
420
+ );
421
+ }
422
+
423
+ /** Lowercase hex encoding, for the requestState nonce. */
424
+ function bytesToHexLocal(bytes: Uint8Array): string {
425
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
426
+ }
427
+
428
+ /**
429
+ * Build a JSON-RPC response with an explicit HTTP status.
430
+ *
431
+ * Module-scoped rather than nested in `startHttp`: request-validation helpers on
432
+ * the class need it too, and duplicating the header defaults is how a response
433
+ * ends up missing its Content-Type.
434
+ */
435
+ function jsonRpcResponse(
436
+ payload: Record<string, unknown>,
437
+ status: number,
438
+ headers?: Record<string, string>,
439
+ ): Response {
440
+ return new Response(JSON.stringify(payload), {
441
+ status,
442
+ headers: {
443
+ "Content-Type": "application/json",
444
+ ...(headers ?? {}),
445
+ },
446
+ });
200
447
  }
201
448
 
202
449
  /**
@@ -207,6 +454,111 @@ function isRecord(v: unknown): v is Record<string, unknown> {
207
454
  return typeof v === "object" && v !== null && !Array.isArray(v);
208
455
  }
209
456
 
457
+ /**
458
+ * Validate the client-owned subscriptions/listen filter before it reaches the
459
+ * registry. The registry deliberately works with a typed SubscriptionFilter;
460
+ * casting untrusted JSON into it made truthy values subscribe to list changes
461
+ * and let invalid URI entries reach the SSE acknowledgement.
462
+ */
463
+ function validateSubscriptionFilter(
464
+ filter: Record<string, unknown>,
465
+ ):
466
+ | { ok: true; filter: SubscriptionFilter }
467
+ | {
468
+ ok: false;
469
+ message: string;
470
+ bodyField: string;
471
+ recovery: string;
472
+ } {
473
+ for (
474
+ const field of [
475
+ "toolsListChanged",
476
+ "promptsListChanged",
477
+ "resourcesListChanged",
478
+ ] as const
479
+ ) {
480
+ if (filter[field] !== undefined && typeof filter[field] !== "boolean") {
481
+ return {
482
+ ok: false,
483
+ message: `${field} must be a boolean when present`,
484
+ bodyField: `params.notifications.${field}`,
485
+ recovery:
486
+ `Send ${field} as true or false, or omit it when that notification type is not requested.`,
487
+ };
488
+ }
489
+ }
490
+
491
+ for (const field of ["resourceSubscriptions", "taskIds"] as const) {
492
+ const value = filter[field];
493
+ if (value === undefined) continue;
494
+ if (!Array.isArray(value)) {
495
+ return {
496
+ ok: false,
497
+ message: `${field} must be an array of strings when present`,
498
+ bodyField: `params.notifications.${field}`,
499
+ recovery:
500
+ `Send ${field} as an array of strings, or omit it when no identifiers are requested.`,
501
+ };
502
+ }
503
+ const malformedIndex = value.findIndex((entry) =>
504
+ typeof entry !== "string"
505
+ );
506
+ if (malformedIndex !== -1) {
507
+ return {
508
+ ok: false,
509
+ message: `${field} entries must be strings`,
510
+ bodyField: `params.notifications.${field}[${malformedIndex}]`,
511
+ recovery:
512
+ `Send only string entries in ${field}; remove or replace the malformed entry.`,
513
+ };
514
+ }
515
+ }
516
+
517
+ return { ok: true, filter: filter as SubscriptionFilter };
518
+ }
519
+
520
+ /**
521
+ * Stamp a result with the spec-2026-07-28 envelope: the required `resultType`
522
+ * (SEP-2322) and the server's identity under `_meta` (SEP-2575, SHOULD).
523
+ *
524
+ * `_meta` is merged, never replaced — tool results carry their own `_meta` (MCP
525
+ * Apps UI hints, for instance) and losing it would break the viewers.
526
+ *
527
+ * Pure by design so the envelope can be asserted directly in tests without
528
+ * standing up a server; the caller decides whether the envelope applies.
529
+ */
530
+ function completeResult(
531
+ result: Record<string, unknown>,
532
+ serverInfo: Implementation,
533
+ ): Record<string, unknown> {
534
+ const existingMeta = isRecord(result["_meta"]) ? result["_meta"] : undefined;
535
+ return {
536
+ ...result,
537
+ resultType: "complete",
538
+ _meta: { ...existingMeta, [STATELESS_SERVER_INFO_KEY]: serverInfo },
539
+ };
540
+ }
541
+
542
+ /**
543
+ * Reduce a handler-built result to the exact JSON object that will cross the
544
+ * transport boundary. Preformatted proxy results bypass the normal text
545
+ * serialisation path, so without this gate a BigInt or cycle could be stored as
546
+ * a completed task and only explode on a later tasks/get response.
547
+ */
548
+ function canonicaliseWireResult(
549
+ result: Record<string, unknown>,
550
+ ): Record<string, unknown> {
551
+ const serialised = JSON.stringify(result);
552
+ if (serialised === undefined) {
553
+ throw new Error("Tool result is not JSON-serialisable");
554
+ }
555
+ const canonical = JSON.parse(serialised);
556
+ if (!isRecord(canonical)) {
557
+ throw new Error("Tool result must serialise to an object");
558
+ }
559
+ return canonical;
560
+ }
561
+
210
562
  // ─────────────────────────────────────────────────────────────────────────────
211
563
 
212
564
  /**
@@ -250,6 +602,73 @@ export class McpApp {
250
602
  private schemaValidator: SchemaValidator | null = null;
251
603
  private samplingBridge: SamplingBridge | null = null;
252
604
  private tools = new Map<string, ToolWithHandler>();
605
+
606
+ /**
607
+ * Tool name → parameters the tool asked clients to mirror into
608
+ * `Mcp-Param-{Name}` headers (spec 2026-07-28, `x-mcp-header`).
609
+ *
610
+ * Populated at registration so the per-request path is a map lookup rather
611
+ * than a schema walk. Tools without annotations are simply absent.
612
+ */
613
+ private mirroredParams = new Map<string, MirroredParam[]>();
614
+
615
+ /**
616
+ * Task store for the Tasks extension, or `null` when the consumer did not
617
+ * declare it.
618
+ *
619
+ * Created only on declaration: a server not using Tasks should not pay for a
620
+ * sweep timer, and a `tasks/*` call against it must read as the unimplemented
621
+ * method it is (404 + -32601) rather than hitting an empty store.
622
+ */
623
+ private taskStore: TaskStore | null;
624
+
625
+ /**
626
+ * Set synchronously at the top of `stop()`.
627
+ *
628
+ * Checked before spawning a task, because the pipeline is async: a handler that
629
+ * settles during shutdown would otherwise start work in a store already drained,
630
+ * producing a task that outlives its server. A synchronous flag is what makes
631
+ * the check reliable — anything awaited leaves the same window open.
632
+ */
633
+ private stopping = false;
634
+
635
+ /**
636
+ * Live `subscriptions/listen` streams, or `null` outside stateless mode.
637
+ *
638
+ * Core protocol rather than an extension, so it is unconditional on the
639
+ * stateless path. The stateful transport keeps its own session-keyed SSE
640
+ * machinery, which this replaces once that path is retired.
641
+ */
642
+ private subscriptions: SubscriptionRegistry | null = null;
643
+
644
+ /**
645
+ * Imported HMAC key for sealing `requestState`, or `null` when the deployment
646
+ * configured none.
647
+ *
648
+ * Resolved lazily on first use rather than in the constructor, because
649
+ * `importStateKey` is async and a constructor cannot await.
650
+ */
651
+ /**
652
+ * In-flight or resolved key import.
653
+ *
654
+ * A Promise, not a value plus a loaded flag: the flag was set before the await,
655
+ * so a second request arriving during the import saw "loaded" with the key
656
+ * still null, received an UNSIGNED requestState, and could then submit raw
657
+ * inputResponses past the verification guard. Memoising the Promise makes every
658
+ * caller await the same import.
659
+ */
660
+ private mrtrKeyPromise: Promise<CryptoKey | null> | null = null;
661
+
662
+ /**
663
+ * Validated `ttlMs`. The spec requires servers to provide a value `>= 0`, and
664
+ * an integer — clients are told to ignore a negative one, which would make a
665
+ * misconfiguration silently do nothing instead of failing.
666
+ *
667
+ * Resolved once at construction: a per-response check would pay for the same
668
+ * validation on every list call, and a bad value is a deployment error that
669
+ * should surface at startup (AX: fast fail early).
670
+ */
671
+ private readonly cacheTtlMs: number;
253
672
  private resources = new Map<string, RegisteredResourceInfo>();
254
673
  private options: McpAppOptions;
255
674
  private started = false;
@@ -289,6 +708,37 @@ export class McpApp {
289
708
  this.options = options;
290
709
  this.name = options.name;
291
710
 
711
+ const ttlMs = options.cache?.ttlMs ?? 0;
712
+ if (!Number.isInteger(ttlMs) || ttlMs < 0) {
713
+ throw new Error(
714
+ `[McpApp] cache.ttlMs must be a non-negative integer (got ${ttlMs}). ` +
715
+ "The spec requires servers to provide ttlMs >= 0, and clients are told " +
716
+ "to ignore a negative value — so a bad one would silently disable " +
717
+ "caching instead of failing.",
718
+ );
719
+ }
720
+ this.cacheTtlMs = ttlMs;
721
+
722
+ this.taskStore = options.extensions?.[TASKS_EXTENSION_ID] !== undefined
723
+ ? new TaskStore({
724
+ onNotification: (task) => this.onTaskChanged(task),
725
+ unrefTimer: (id) => unrefTimer(id as unknown as number),
726
+ })
727
+ : null;
728
+
729
+ // Validate the shape of the MRTR key here rather than on first use. The
730
+ // import itself is async so it stays lazy, but a typo in a 64-hex-character
731
+ // secret should surface at boot, not on the first request that needs it —
732
+ // by which point it is a runtime failure in production traffic.
733
+ const mrtrKey = options.mrtr?.signingKey;
734
+ if (mrtrKey !== undefined && !/^[0-9a-f]{64}$/.test(mrtrKey)) {
735
+ throw new Error(
736
+ "[McpApp] mrtr.signingKey must be 64 lowercase hex characters (32 bytes). " +
737
+ "Generate one with: crypto.getRandomValues(new Uint8Array(32)) rendered as hex, " +
738
+ "or the exported generateStateKey() + exportStateKey() helpers.",
739
+ );
740
+ }
741
+
292
742
  // Create SDK MCP server
293
743
  this.mcpServer = new McpServer(
294
744
  {
@@ -328,6 +778,19 @@ export class McpApp {
328
778
  this.log(
329
779
  "[DEPRECATED] Sampling is deprecated (MCP 2026-07-28) and will be removed after 2027-07-28.",
330
780
  );
781
+ if (options.transport === "stateless") {
782
+ // Stronger than deprecation: the bridge sends a server-initiated
783
+ // request, which 2026-07-28 removed outright. There is no channel for it
784
+ // on this transport, so it cannot work — MRTR is the only legal path.
785
+ // Said plainly here because the failure would otherwise appear as a
786
+ // request that simply never gets answered.
787
+ this.log(
788
+ "[WARN] enableSampling has no effect on the stateless transport: " +
789
+ "spec 2026-07-28 removed server-initiated requests. Return an " +
790
+ "InputRequiredResult with a sampling/createMessage inputRequest " +
791
+ "(MRTR) instead.",
792
+ );
793
+ }
331
794
  this.samplingBridge = new SamplingBridge(options.samplingClient);
332
795
  }
333
796
 
@@ -355,7 +818,7 @@ export class McpApp {
355
818
  server.registerCapabilities({ resources: {} });
356
819
 
357
820
  // resources/list — returns currently registered resources
358
- server.setRequestHandler(ListResourcesRequestSchema, async () => {
821
+ server.setRequestHandler(ListResourcesRequestSchema, () => {
359
822
  return {
360
823
  resources: Array.from(this.resources.values()).map((r) => ({
361
824
  uri: r.resource.uri,
@@ -454,6 +917,13 @@ export class McpApp {
454
917
  throw new Error(`No handler provided for tool: ${tool.name}`);
455
918
  }
456
919
 
920
+ // Validate annotations BEFORE inserting: a throw must not leave the tool
921
+ // half-registered. Registration is the right place to fail — a conforming
922
+ // client drops the whole tool from `tools/list` over a malformed
923
+ // annotation, so a typo would otherwise surface as a tool that silently
924
+ // does not exist (AX: fast fail early).
925
+ this.indexMirroredParams(tool);
926
+
457
927
  this.tools.set(tool.name, {
458
928
  ...tool,
459
929
  handler,
@@ -474,6 +944,35 @@ export class McpApp {
474
944
  * @param tool - Tool definition
475
945
  * @param handler - Tool handler function
476
946
  */
947
+ /**
948
+ * Validate and index a tool's `x-mcp-header` annotations (spec 2026-07-28).
949
+ *
950
+ * Every registration path must go through here. Wiring it into `registerTools`
951
+ * alone was a real bypass: a tool registered via `registerTool` or
952
+ * `registerToolLive` carried annotations that clients would mirror into
953
+ * `Mcp-Param-*` headers, while the server never required or checked them.
954
+ *
955
+ * Throws *before* the caller inserts the tool, so a rejected definition cannot
956
+ * leave a half-registered tool behind.
957
+ */
958
+ private indexMirroredParams(tool: MCPTool): void {
959
+ const invalid: string[] = [];
960
+ const mirrored = collectMirroredParams(
961
+ tool.inputSchema,
962
+ (reason) => invalid.push(reason),
963
+ );
964
+ if (invalid.length > 0) {
965
+ throw new Error(
966
+ `[McpApp] Tool "${tool.name}" has invalid x-mcp-header annotations:\n` +
967
+ invalid.map((r) => ` - ${r}`).join("\n"),
968
+ );
969
+ }
970
+ // Replace wholesale: re-registering a tool without annotations must clear
971
+ // whatever a previous definition left behind.
972
+ if (mirrored.length > 0) this.mirroredParams.set(tool.name, mirrored);
973
+ else this.mirroredParams.delete(tool.name);
974
+ }
975
+
477
976
  registerTool(tool: MCPTool, handler: ToolHandler): void {
478
977
  if (this.started) {
479
978
  throw new Error(
@@ -481,6 +980,7 @@ export class McpApp {
481
980
  "Call registerTool() before start() or startHttp().",
482
981
  );
483
982
  }
983
+ this.indexMirroredParams(tool);
484
984
  this.tools.set(tool.name, {
485
985
  ...tool,
486
986
  handler,
@@ -507,6 +1007,7 @@ export class McpApp {
507
1007
  * @param handler - Tool handler function
508
1008
  */
509
1009
  registerToolLive(tool: MCPTool, handler: ToolHandler): void {
1010
+ this.indexMirroredParams(tool);
510
1011
  this.tools.set(tool.name, {
511
1012
  ...tool,
512
1013
  handler,
@@ -554,6 +1055,9 @@ export class McpApp {
554
1055
  */
555
1056
  unregisterTool(toolName: string): boolean {
556
1057
  const deleted = this.tools.delete(toolName);
1058
+ // Stale mirror metadata would make the server demand `Mcp-Param-*` headers
1059
+ // for a tool that no longer exists.
1060
+ this.mirroredParams.delete(toolName);
557
1061
  if (deleted) {
558
1062
  this.log(
559
1063
  `Unregistered tool: ${toolName} (remaining: ${this.tools.size})`,
@@ -658,6 +1162,13 @@ export class McpApp {
658
1162
  ...(ctx.clientCapabilities !== undefined
659
1163
  ? { clientCapabilities: ctx.clientCapabilities }
660
1164
  : {}),
1165
+ ...(ctx.logLevel !== undefined ? { logLevel: ctx.logLevel } : {}),
1166
+ ...(ctx.inputResponses !== undefined
1167
+ ? { inputResponses: ctx.inputResponses }
1168
+ : {}),
1169
+ ...(ctx.retryVerified !== undefined
1170
+ ? { retryVerified: ctx.retryVerified }
1171
+ : {}),
661
1172
  }));
662
1173
  });
663
1174
  }
@@ -679,6 +1190,10 @@ export class McpApp {
679
1190
  sessionId?: string,
680
1191
  preVerifiedAuthInfo?: AuthInfo,
681
1192
  clientMeta?: StatelessClientMeta,
1193
+ mrtr?: {
1194
+ inputResponses?: Record<string, unknown>;
1195
+ retryVerified?: boolean;
1196
+ },
682
1197
  ): Promise<MiddlewareResult> {
683
1198
  if (!this.middlewareRunner) {
684
1199
  throw new Error(
@@ -701,6 +1216,15 @@ export class McpApp {
701
1216
  ...(clientMeta?.clientCapabilities !== undefined
702
1217
  ? { clientCapabilities: clientMeta.clientCapabilities }
703
1218
  : {}),
1219
+ ...(clientMeta?.logLevel !== undefined
1220
+ ? { logLevel: clientMeta.logLevel }
1221
+ : {}),
1222
+ ...(mrtr?.inputResponses !== undefined
1223
+ ? { inputResponses: mrtr.inputResponses }
1224
+ : {}),
1225
+ ...(mrtr?.retryVerified !== undefined
1226
+ ? { retryVerified: mrtr.retryVerified }
1227
+ : {}),
704
1228
  };
705
1229
 
706
1230
  // OTel span + metrics
@@ -985,10 +1509,19 @@ export class McpApp {
985
1509
  * Start the MCP server with stdio transport
986
1510
  */
987
1511
  async start(): Promise<void> {
1512
+ // Guard FIRST. Resetting before the guard meant a concurrent start() during
1513
+ // stop() cleared `stopping` and rebuilt the store on its way to failing with
1514
+ // "already started" — after which a held request produced a live task on a
1515
+ // stopped server. `startHttp()` had the order right; this did not.
988
1516
  if (this.started) {
989
1517
  throw new Error("Server already started");
990
1518
  }
991
1519
 
1520
+ // Same reset as the HTTP path. Without it a stdio server that had been stopped
1521
+ // kept `stopping` set and its store disposed, so it refused every task for the
1522
+ // rest of its life — with nothing to say why.
1523
+ this.prepareForStart();
1524
+
992
1525
  // Build middleware pipeline before connecting transport
993
1526
  this.buildPipeline();
994
1527
 
@@ -1050,7 +1583,51 @@ export class McpApp {
1050
1583
  /**
1051
1584
  * Stop the server gracefully
1052
1585
  */
1586
+ /**
1587
+ * Restore the invariants a running server relies on.
1588
+ *
1589
+ * Called by both transports' start paths. `stop()` disposes the task store and
1590
+ * leaves it disposed — rebuilding it mid-teardown is what let an in-flight call
1591
+ * spawn into a store nobody would drain — so coming back up is where a live one
1592
+ * is created.
1593
+ */
1594
+ private prepareForStart(): void {
1595
+ this.stopping = false;
1596
+ if (
1597
+ this.options.extensions?.[TASKS_EXTENSION_ID] !== undefined &&
1598
+ (this.taskStore === null || this.taskStore.isDisposed)
1599
+ ) {
1600
+ this.taskStore = new TaskStore({
1601
+ onNotification: (task) => this.onTaskChanged(task),
1602
+ unrefTimer: (timerId) => unrefTimer(timerId as unknown as number),
1603
+ });
1604
+ }
1605
+ }
1606
+
1053
1607
  async stop(): Promise<void> {
1608
+ // Synchronous, before any await: a handler settling during shutdown must see
1609
+ // this immediately or it can still spawn a task.
1610
+ this.stopping = true;
1611
+
1612
+ // Release the subsystems whose timers exist from construction, BEFORE the
1613
+ // `started` guard: they are created in the constructor, so a server that
1614
+ // failed during startup still has them armed, and returning early left them
1615
+ // running with no way to reach them again.
1616
+ //
1617
+ // Disposed and left disposed — NOT replaced. Replacing here opened a window
1618
+ // where an in-flight call could spawn into a fresh store while the server was
1619
+ // stopping, producing a task that outlived its server. `startHttp()` builds a
1620
+ // new store instead, which keeps "a started server has a live store" true
1621
+ // without inventing one mid-teardown.
1622
+ if (this.taskStore) {
1623
+ this.taskStore.drain();
1624
+ this.taskStore.dispose();
1625
+ }
1626
+ if (this.subscriptions) {
1627
+ this.subscriptions.shutdown();
1628
+ this.subscriptions = null;
1629
+ }
1630
+
1054
1631
  if (!this.started) {
1055
1632
  return;
1056
1633
  }
@@ -1160,6 +1737,22 @@ export class McpApp {
1160
1737
  this.buildPipeline();
1161
1738
 
1162
1739
  const hostname = options.hostname ?? "0.0.0.0";
1740
+ this.prepareForStart();
1741
+
1742
+ if (this.options.transport === "stateless" && this.subscriptions === null) {
1743
+ this.subscriptions = new SubscriptionRegistry({
1744
+ serverInfo: { name: this.options.name, version: this.options.version },
1745
+ });
1746
+ // Unref'd: a keep-alive ticker must not by itself hold the process open.
1747
+ // The cast matches the existing session-timer call sites — `UnrefTimerFn`
1748
+ // is typed for Deno's numeric handle, while Node's `setInterval` returns a
1749
+ // Timeout object.
1750
+ this.subscriptions.startKeepAlive(
1751
+ setInterval,
1752
+ (id) => unrefTimer(id as unknown as number),
1753
+ );
1754
+ }
1755
+
1163
1756
  const enableCors = options.cors ?? true;
1164
1757
  const corsOrigins = options.corsOrigins ?? "*";
1165
1758
  const maxBodyBytes = options.maxBodyBytes === null
@@ -1199,6 +1792,22 @@ export class McpApp {
1199
1792
  "mcp-session-id",
1200
1793
  "mcp-protocol-version",
1201
1794
  "last-event-id",
1795
+ // Spec 2026-07-28 request-metadata headers. Omitting them broke
1796
+ // browser clients outright: the preflight rejects the actual request
1797
+ // before the server ever sees it, so a conforming client could not
1798
+ // send the headers the server now requires.
1799
+ "mcp-method",
1800
+ "mcp-name",
1801
+ // `Mcp-Param-*` names are defined by the tools themselves, so the
1802
+ // allowlist is derived from the registered annotations rather than
1803
+ // opened to `*` — which would also widen it for every other header.
1804
+ //
1805
+ // Known limitation: a tool registered via `registerToolLive` AFTER
1806
+ // startHttp() is not reflected here. Register annotated tools before
1807
+ // starting, or widen `corsOrigins`/headers deliberately.
1808
+ ...[...this.mirroredParams.values()]
1809
+ .flat()
1810
+ .map((param) => `mcp-param-${param.headerName.toLowerCase()}`),
1202
1811
  ],
1203
1812
  exposeHeaders: [
1204
1813
  "Content-Length",
@@ -1335,20 +1944,6 @@ export class McpApp {
1335
1944
  return { allowed: true, retryAfterMs: 0 };
1336
1945
  };
1337
1946
 
1338
- const jsonRpcResponse = (
1339
- payload: Record<string, unknown>,
1340
- status: number,
1341
- headers?: Record<string, string>,
1342
- ): Response => {
1343
- return new Response(JSON.stringify(payload), {
1344
- status,
1345
- headers: {
1346
- "Content-Type": "application/json",
1347
- ...(headers ?? {}),
1348
- },
1349
- });
1350
- };
1351
-
1352
1947
  // Custom routes (registered before MCP catch-all)
1353
1948
  if (options.customRoutes) {
1354
1949
  for (const route of options.customRoutes) {
@@ -1565,6 +2160,20 @@ export class McpApp {
1565
2160
  ? params["_meta"][STATELESS_PROTO_KEY]
1566
2161
  : undefined;
1567
2162
 
2163
+ // `clientCapabilities` is a REQUIRED per-request `_meta` field in the
2164
+ // final spec (`clientInfo` is not — it is only SHOULD). A request
2165
+ // missing a required field is malformed: -32602 + HTTP 400.
2166
+ //
2167
+ // Checked after the version so a client on an older revision, which
2168
+ // never had this field, still gets the clearer version error first.
2169
+ // Must be an OBJECT, not merely present. `!== undefined` accepted
2170
+ // `null`, a scalar or an array, which then reached the handler as a
2171
+ // supposed ClientCapabilities and failed later as -32603 — an internal
2172
+ // error for what is plainly a malformed request.
2173
+ const capabilitiesValid = isRecord(params) &&
2174
+ isRecord(params["_meta"]) &&
2175
+ isRecord(params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY]);
2176
+
1568
2177
  if (typeof clientVersion !== "string") {
1569
2178
  // Header uses fallback version — no negotiated version available yet
1570
2179
  return jsonRpcResponse(
@@ -1601,11 +2210,7 @@ export class McpApp {
1601
2210
  );
1602
2211
  }
1603
2212
 
1604
- const headerVersion = c.req.header("MCP-Protocol-Version");
1605
- if (
1606
- headerVersion !== undefined &&
1607
- headerVersion !== clientVersion
1608
- ) {
2213
+ if (clientVersion === SPEC_2026_07_28 && !capabilitiesValid) {
1609
2214
  return jsonRpcResponse(
1610
2215
  {
1611
2216
  jsonrpc: "2.0",
@@ -1613,7 +2218,14 @@ export class McpApp {
1613
2218
  error: {
1614
2219
  code: JSONRPC_INVALID_PARAMS,
1615
2220
  message:
1616
- `MCP-Protocol-Version header "${headerVersion}" does not match _meta protocolVersion "${clientVersion}"`,
2221
+ `Missing or malformed field '${STATELESS_CLIENT_CAPABILITIES_KEY}' in params._meta: expected an object`,
2222
+ data: {
2223
+ problem: "missing_field",
2224
+ bodyField:
2225
+ `params._meta['${STATELESS_CLIENT_CAPABILITIES_KEY}']`,
2226
+ recovery:
2227
+ "Send a ClientCapabilities object; `{}` is valid and means no capabilities declared.",
2228
+ },
1617
2229
  },
1618
2230
  },
1619
2231
  400,
@@ -1621,6 +2233,111 @@ export class McpApp {
1621
2233
  );
1622
2234
  }
1623
2235
 
2236
+ // Track C: request-metadata headers (SEP-2243).
2237
+ //
2238
+ // Enforced only for peers that negotiated 2026-07-28 — `Mcp-Method`
2239
+ // and `Mcp-Name` do not exist in earlier revisions, so demanding them
2240
+ // from a 2025-11-25 client would reject a conforming request.
2241
+ //
2242
+ // Notifications are exempt: the revision explicitly leaves header
2243
+ // requirements for notification POSTs undefined, so a missing
2244
+ // `Mcp-Method` there is not a violation to invent.
2245
+ if (clientVersion === SPEC_2026_07_28 && id !== undefined) {
2246
+ const validation = validateRequestHeaders({
2247
+ getHeader: (name) => c.req.header(name),
2248
+ method: typeof method === "string" ? method : "",
2249
+ params: isRecord(params) ? params : undefined,
2250
+ bodyProtocolVersion: clientVersion,
2251
+ mirroredParams: typeof params?.name === "string"
2252
+ ? this.mirroredParams.get(params.name)
2253
+ : undefined,
2254
+ });
2255
+ if (!validation.ok) {
2256
+ return jsonRpcResponse(
2257
+ {
2258
+ jsonrpc: "2.0",
2259
+ id,
2260
+ error: {
2261
+ code: MCP_HEADER_MISMATCH,
2262
+ message: validation.message,
2263
+ // AX: the caller has to fix the request, so what to fix
2264
+ // travels as data. `problem` is an enum to switch on,
2265
+ // `recovery` is one concrete action — neither requires
2266
+ // parsing the English message.
2267
+ data: validation.detail,
2268
+ },
2269
+ },
2270
+ 400,
2271
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2272
+ );
2273
+ }
2274
+ } else if (id !== undefined) {
2275
+ // Pre-2026 peer: `Mcp-Method` / `Mcp-Name` did not exist yet, so they
2276
+ // are not demanded. `MCP-Protocol-Version` DID — it was introduced in
2277
+ // 2025-06-18, and the spec grants the omit-the-header grace only to
2278
+ // clients older than that, which this server does not support
2279
+ // (STATELESS_SUPPORTED_VERSIONS starts at 2025-06-18). So it stays
2280
+ // required here, and must agree with the body when present.
2281
+ //
2282
+ // Notifications fall through untouched: the revision states outright
2283
+ // that header requirements for notification POSTs are undefined, so
2284
+ // there is no rule here to enforce and none to invent. Their `_meta`
2285
+ // protocolVersion was already validated above.
2286
+ const headerVersion = c.req.header("MCP-Protocol-Version");
2287
+ if (headerVersion === undefined) {
2288
+ return jsonRpcResponse(
2289
+ {
2290
+ jsonrpc: "2.0",
2291
+ id,
2292
+ error: {
2293
+ code: MCP_HEADER_MISMATCH,
2294
+ message:
2295
+ "Missing required header 'MCP-Protocol-Version' (required since protocol version 2025-06-18)",
2296
+ data: {
2297
+ problem: "missing_header",
2298
+ header: "MCP-Protocol-Version",
2299
+ expected: clientVersion,
2300
+ bodyField:
2301
+ "params._meta['io.modelcontextprotocol/protocolVersion']",
2302
+ recovery:
2303
+ `Send the header 'MCP-Protocol-Version: ${clientVersion}' on every POST.`,
2304
+ },
2305
+ },
2306
+ },
2307
+ 400,
2308
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2309
+ );
2310
+ }
2311
+ if (headerVersion !== clientVersion) {
2312
+ return jsonRpcResponse(
2313
+ {
2314
+ jsonrpc: "2.0",
2315
+ id,
2316
+ error: {
2317
+ // A header disagreeing with the body is HeaderMismatch, not
2318
+ // InvalidParams: intermediaries routing on the header need
2319
+ // to know the divergence was detected.
2320
+ code: MCP_HEADER_MISMATCH,
2321
+ message:
2322
+ `MCP-Protocol-Version header "${headerVersion}" does not match _meta protocolVersion "${clientVersion}"`,
2323
+ data: {
2324
+ problem: "header_body_mismatch",
2325
+ header: "MCP-Protocol-Version",
2326
+ expected: clientVersion,
2327
+ received: headerVersion,
2328
+ bodyField:
2329
+ "params._meta['io.modelcontextprotocol/protocolVersion']",
2330
+ recovery:
2331
+ `Set the header to "${clientVersion}", or change the body's _meta to "${headerVersion}". They must agree.`,
2332
+ },
2333
+ },
2334
+ },
2335
+ 400,
2336
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2337
+ );
2338
+ }
2339
+ }
2340
+
1624
2341
  statelessVersion = clientVersion;
1625
2342
  // Spec 2026-07-28: echo negotiated version in every response header.
1626
2343
  // c.header() accumulates headers — all subsequent c.json() calls inherit it.
@@ -1634,20 +2351,20 @@ export class McpApp {
1634
2351
  return c.json({
1635
2352
  jsonrpc: "2.0",
1636
2353
  id,
1637
- result: {
1638
- supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
1639
- capabilities: {
1640
- tools: {},
1641
- resources: this.resources.size > 0 ? {} : undefined,
1642
- },
1643
- serverInfo: {
1644
- name: this.options.name,
1645
- version: this.options.version,
1646
- },
1647
- ...(this.options.instructions
1648
- ? { instructions: this.options.instructions }
1649
- : {}),
1650
- },
2354
+ result: this.stampResult(
2355
+ this.withCacheHints({
2356
+ supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
2357
+ capabilities: this.buildServerCapabilities(),
2358
+ serverInfo: {
2359
+ name: this.options.name,
2360
+ version: this.options.version,
2361
+ },
2362
+ ...(this.options.instructions
2363
+ ? { instructions: this.options.instructions }
2364
+ : {}),
2365
+ }, statelessVersion),
2366
+ statelessVersion,
2367
+ ),
1651
2368
  });
1652
2369
  }
1653
2370
 
@@ -1659,12 +2376,9 @@ export class McpApp {
1659
2376
  return c.json({
1660
2377
  jsonrpc: "2.0",
1661
2378
  id,
1662
- result: {
2379
+ result: this.stampResult({
1663
2380
  protocolVersion: statelessVersion as string,
1664
- capabilities: {
1665
- tools: {},
1666
- resources: this.resources.size > 0 ? {} : undefined,
1667
- },
2381
+ capabilities: this.buildServerCapabilities(),
1668
2382
  serverInfo: {
1669
2383
  name: this.options.name,
1670
2384
  version: this.options.version,
@@ -1672,7 +2386,7 @@ export class McpApp {
1672
2386
  ...(this.options.instructions
1673
2387
  ? { instructions: this.options.instructions }
1674
2388
  : {}),
1675
- },
2389
+ }, statelessVersion),
1676
2390
  });
1677
2391
  // Note: c.json() inherits MCP-Protocol-Version header set above.
1678
2392
  // No Mcp-Session-Id header emitted — stateless by design.
@@ -1745,7 +2459,13 @@ export class McpApp {
1745
2459
  return c.json({
1746
2460
  jsonrpc: "2.0",
1747
2461
  id,
1748
- error: { code: -32001, message: "Session not found or expired" },
2462
+ error: {
2463
+ // Stateful path only (sessions do not exist in 2026-07-28), but
2464
+ // -32001 is in the sub-range new implementations SHOULD NOT use,
2465
+ // so it moves out alongside the auth codes.
2466
+ code: -31404,
2467
+ message: "Session not found or expired",
2468
+ },
1749
2469
  }, 404);
1750
2470
  }
1751
2471
  // Update last activity to prevent premature cleanup
@@ -1753,9 +2473,33 @@ export class McpApp {
1753
2473
  }
1754
2474
 
1755
2475
  // Tools call (delegates to middleware pipeline, which handles auth internally)
1756
- if (method === "tools/call" && params?.name) {
1757
- const toolName = params.name as string;
1758
- const args = (params.arguments as Record<string, unknown>) || {};
2476
+ if (method === "tools/call") {
2477
+ // Dispatch by method rather than the truthiness of `name`. An empty
2478
+ // string can be represented faithfully by Mcp-Name, but it is not a
2479
+ // usable tool name and must be InvalidParams rather than an apparent
2480
+ // method that this server does not implement.
2481
+ const toolParams = isRecord(params) ? params : undefined;
2482
+ if (
2483
+ toolParams === undefined ||
2484
+ typeof toolParams["name"] !== "string" ||
2485
+ toolParams["name"].length === 0
2486
+ ) {
2487
+ return jsonRpcResponse(
2488
+ {
2489
+ jsonrpc: "2.0",
2490
+ id,
2491
+ error: {
2492
+ code: JSONRPC_INVALID_PARAMS,
2493
+ message:
2494
+ "tools/call requires a non-empty string 'name' parameter",
2495
+ },
2496
+ },
2497
+ 400,
2498
+ );
2499
+ }
2500
+ const toolName = toolParams["name"];
2501
+ const args = (toolParams["arguments"] as Record<string, unknown>) ||
2502
+ {};
1759
2503
  const statelessClientMeta:
1760
2504
  | StatelessClientMeta
1761
2505
  | undefined = this.options.transport === "stateless" &&
@@ -1768,23 +2512,367 @@ export class McpApp {
1768
2512
  clientCapabilities: params["_meta"][
1769
2513
  STATELESS_CLIENT_CAPABILITIES_KEY
1770
2514
  ] as ClientCapabilities | undefined,
2515
+ logLevel: readLogLevel(params["_meta"]),
1771
2516
  }
1772
2517
  : undefined;
1773
2518
 
1774
- try {
1775
- const result = await this.executeToolCall(
1776
- toolName,
1777
- args,
1778
- c.req.raw,
1779
- reqSessionId,
1780
- httpAuthInfo,
1781
- statelessClientMeta,
2519
+ // MRTR retry fields live in `params` directly — siblings of `_meta`,
2520
+ // not members of it, unlike every other per-request field. Reading them
2521
+ // from `_meta` yields a silent undefined even when the client sent them.
2522
+ //
2523
+ // Confined to a negotiated 2026-07-28: MRTR replaces the
2524
+ // server-initiated request pattern that earlier revisions still use, so
2525
+ // it has no meaning on the legacy path — and the client capabilities it
2526
+ // needs only arrive per-request there.
2527
+ const mrtrEnabled = statelessVersion === SPEC_2026_07_28;
2528
+
2529
+ // Digest of the arguments AS RECEIVED, taken before the middleware
2530
+ // pipeline runs. Re-deriving it at seal time would hash whatever the
2531
+ // pipeline left in `args` — validation coercion, defaults, redaction —
2532
+ // so a client replaying the request byte-for-byte would fail
2533
+ // `wrong_params` through no fault of its own.
2534
+ const ingressDigest = mrtrEnabled
2535
+ ? await paramsDigest({ arguments: args, name: toolName })
2536
+ : "";
2537
+ // A scalar or array `inputResponses` was silently dropped, so a client
2538
+ // sending the wrong shape saw its answers ignored and the same
2539
+ // InputRequiredResult come back, with nothing to indicate why.
2540
+ const rawResponses = mrtrEnabled && isRecord(params)
2541
+ ? params["inputResponses"]
2542
+ : undefined;
2543
+ if (rawResponses !== undefined && !isRecord(rawResponses)) {
2544
+ return jsonRpcResponse(
2545
+ {
2546
+ jsonrpc: "2.0",
2547
+ id,
2548
+ error: {
2549
+ code: JSONRPC_INVALID_PARAMS,
2550
+ message:
2551
+ "inputResponses must be an object keyed by the ids from inputRequests",
2552
+ data: {
2553
+ problem: "malformed_field",
2554
+ bodyField: "params.inputResponses",
2555
+ recovery:
2556
+ "Send an object whose keys match the inputRequests keys the server issued.",
2557
+ },
2558
+ },
2559
+ },
2560
+ 400,
2561
+ {
2562
+ "MCP-Protocol-Version": statelessVersion ??
2563
+ STATELESS_FALLBACK_VERSION,
2564
+ },
1782
2565
  );
1783
- return c.json({
1784
- jsonrpc: "2.0",
2566
+ }
2567
+ const echoedResponses = isRecord(rawResponses)
2568
+ ? rawResponses
2569
+ : undefined;
2570
+ const echoedState = mrtrEnabled && isRecord(params) &&
2571
+ typeof params["requestState"] === "string"
2572
+ ? params["requestState"]
2573
+ : undefined;
2574
+
2575
+ let retryVerified: boolean | undefined;
2576
+
2577
+ // A retry carrying answers but no token cannot be verified, and the
2578
+ // server always issues a token when it has a key. So this combination
2579
+ // is either a confused client or an attempt to inject answers past the
2580
+ // verification gate — refuse it rather than forwarding unverified
2581
+ // responses to the handler.
2582
+ // Resolved only when MRTR is actually in play. Resolving on every 2026
2583
+ // tools/call meant a transient key-import failure also broke ordinary
2584
+ // tools that never touch MRTR.
2585
+ const needsKey = mrtrEnabled &&
2586
+ (echoedResponses !== undefined || echoedState !== undefined);
2587
+ const guardKey = needsKey
2588
+ ? await this.getMrtrKeySafe(
1785
2589
  id,
1786
- result: this.buildToolCallResult(toolName, result),
1787
- });
2590
+ statelessVersion ?? STATELESS_FALLBACK_VERSION,
2591
+ )
2592
+ : { key: null as CryptoKey | null };
2593
+ if ("error" in guardKey) return guardKey.error;
2594
+ if (
2595
+ echoedResponses !== undefined && echoedState === undefined &&
2596
+ guardKey.key !== null
2597
+ ) {
2598
+ return jsonRpcResponse(
2599
+ {
2600
+ jsonrpc: "2.0",
2601
+ id,
2602
+ error: {
2603
+ code: JSONRPC_INVALID_PARAMS,
2604
+ message:
2605
+ "inputResponses supplied without the requestState issued with them",
2606
+ data: {
2607
+ problem: "missing_request_state",
2608
+ recovery:
2609
+ "Echo back the exact requestState string from the InputRequiredResult alongside inputResponses.",
2610
+ },
2611
+ },
2612
+ },
2613
+ 400,
2614
+ {
2615
+ "MCP-Protocol-Version": statelessVersion ??
2616
+ STATELESS_FALLBACK_VERSION,
2617
+ },
2618
+ );
2619
+ }
2620
+
2621
+ if (echoedState !== undefined) {
2622
+ const key = guardKey.key;
2623
+ if (key === null) {
2624
+ // Unprotected mode: nothing to verify, and the handler is told so
2625
+ // rather than being handed a false assurance.
2626
+ retryVerified = false;
2627
+ } else {
2628
+ // On an authenticated server this binds the token to one user, so
2629
+ // a token minted for A cannot be spent by B. On an UNAUTHENTICATED
2630
+ // server every caller is "anonymous", and the binding protects
2631
+ // nothing — correctly so: without auth there is no user boundary to
2632
+ // cross, and any caller could invoke the tool directly anyway. The
2633
+ // method and argument bindings still apply in both cases.
2634
+ const principal = callerPrincipal(httpAuthInfo);
2635
+ if (principal === null) {
2636
+ return noPrincipalError(
2637
+ id,
2638
+ statelessVersion ?? STATELESS_FALLBACK_VERSION,
2639
+ );
2640
+ }
2641
+ const verdict = await verifyRequestState(echoedState, key, {
2642
+ principal,
2643
+ method: "tools/call",
2644
+ paramsDigest: ingressDigest,
2645
+ });
2646
+ if (!verdict.ok) {
2647
+ // Attacker-controlled input that failed its integrity or binding
2648
+ // checks. Rejected before the handler runs, and the reason is
2649
+ // returned so a legitimate client can recover (e.g. re-elicit
2650
+ // after an expiry) rather than guessing.
2651
+ return jsonRpcResponse(
2652
+ {
2653
+ jsonrpc: "2.0",
2654
+ id,
2655
+ error: {
2656
+ code: JSONRPC_INVALID_PARAMS,
2657
+ message: `Invalid requestState: ${verdict.reason}`,
2658
+ data: { reason: verdict.reason },
2659
+ },
2660
+ },
2661
+ 400,
2662
+ );
2663
+ }
2664
+ retryVerified = true;
2665
+ }
2666
+ }
2667
+
2668
+ try {
2669
+ const result = await this.executeToolCall(
2670
+ toolName,
2671
+ args,
2672
+ c.req.raw,
2673
+ reqSessionId,
2674
+ httpAuthInfo,
2675
+ statelessClientMeta,
2676
+ {
2677
+ ...(echoedResponses !== undefined
2678
+ ? { inputResponses: echoedResponses }
2679
+ : {}),
2680
+ ...(retryVerified !== undefined ? { retryVerified } : {}),
2681
+ },
2682
+ );
2683
+ // MRTR: the handler is asking the client for input rather than
2684
+ // returning a result. Checked BEFORE the task branch and before
2685
+ // stampResult, which would overwrite resultType with "complete".
2686
+ if (
2687
+ mrtrEnabled && isRecord(result) &&
2688
+ result["resultType"] === "input_required"
2689
+ ) {
2690
+ const sealPrincipal = callerPrincipal(httpAuthInfo);
2691
+ if (sealPrincipal === null) {
2692
+ return noPrincipalError(
2693
+ id,
2694
+ statelessVersion ?? STATELESS_FALLBACK_VERSION,
2695
+ );
2696
+ }
2697
+ const built = await this.buildInputRequiredResult(
2698
+ result as unknown as InputRequiredSignal,
2699
+ {
2700
+ clientCapabilities: statelessClientMeta?.clientCapabilities,
2701
+ principal: sealPrincipal,
2702
+ method: "tools/call",
2703
+ paramsDigest: ingressDigest,
2704
+ },
2705
+ );
2706
+ if (!built.ok) {
2707
+ return jsonRpcResponse(
2708
+ {
2709
+ jsonrpc: "2.0",
2710
+ id,
2711
+ error: {
2712
+ code: built.code,
2713
+ message: built.message,
2714
+ ...(built.data !== undefined ? { data: built.data } : {}),
2715
+ },
2716
+ },
2717
+ // Status follows the code: an InternalError is a server fault
2718
+ // (500), a capability or shape problem is the caller's (400).
2719
+ // Flattening both to 400 told a client to fix a request that a
2720
+ // misconfigured signing key had broken — and the sibling ingress
2721
+ // path already answered 500 for exactly that.
2722
+ built.code === ErrorCode.InternalError ? 500 : 400,
2723
+ {
2724
+ "MCP-Protocol-Version": statelessVersion ??
2725
+ STATELESS_FALLBACK_VERSION,
2726
+ },
2727
+ );
2728
+ }
2729
+ return c.json({ jsonrpc: "2.0", id, result: built.result });
2730
+ }
2731
+
2732
+ // Tasks extension: the handler asked for a task handle instead of
2733
+ // a synchronous result.
2734
+ if (isAsyncTaskDescriptor(result)) {
2735
+ if (statelessVersion !== SPEC_2026_07_28) {
2736
+ // The handler asked for a task, but this peer cannot be handed
2737
+ // one. Surfacing the server-side misconfiguration is better than
2738
+ // silently degrading to a synchronous call whose duration is the
2739
+ // reason the handler wanted a task in the first place.
2740
+ return jsonRpcResponse(
2741
+ {
2742
+ jsonrpc: "2.0",
2743
+ id,
2744
+ error: {
2745
+ code: ErrorCode.InternalError,
2746
+ message:
2747
+ `Tool "${toolName}" returned a task, but the client negotiated ${
2748
+ statelessVersion ?? "a pre-2026 revision"
2749
+ }; the Tasks extension requires 2026-07-28.`,
2750
+ },
2751
+ },
2752
+ 400,
2753
+ );
2754
+ }
2755
+ const guard = this.requireTasksCapability(
2756
+ statelessClientMeta?.clientCapabilities,
2757
+ id,
2758
+ );
2759
+ if (guard) return guard;
2760
+
2761
+ // Owner binding: the spec requires an authorization check on every
2762
+ // task-related request, and a task id alone is only one line of
2763
+ // defence.
2764
+ if (this.stopping || this.taskStore === null) {
2765
+ return jsonRpcResponse(
2766
+ {
2767
+ jsonrpc: "2.0",
2768
+ id,
2769
+ error: {
2770
+ code: ErrorCode.InternalError,
2771
+ message:
2772
+ "Server is shutting down; no new tasks are accepted.",
2773
+ data: {
2774
+ problem: "server_stopping",
2775
+ recovery: "Retry against a running instance.",
2776
+ },
2777
+ },
2778
+ },
2779
+ 503,
2780
+ {
2781
+ "MCP-Protocol-Version": statelessVersion ??
2782
+ STATELESS_FALLBACK_VERSION,
2783
+ },
2784
+ );
2785
+ }
2786
+ const ownerPrincipal = callerPrincipal(httpAuthInfo);
2787
+ if (ownerPrincipal === null) {
2788
+ return noPrincipalError(
2789
+ id,
2790
+ statelessVersion ?? STATELESS_FALLBACK_VERSION,
2791
+ );
2792
+ }
2793
+ const owner = await taskOwnerKeyFor(
2794
+ this.options,
2795
+ httpAuthInfo,
2796
+ c.req.raw,
2797
+ ownerPrincipal,
2798
+ );
2799
+ if (owner === null) {
2800
+ return noOwnerKeyError(
2801
+ id,
2802
+ statelessVersion ?? STATELESS_FALLBACK_VERSION,
2803
+ );
2804
+ }
2805
+ // Re-checked, and wrapped: the guard above sits before two awaits
2806
+ // (the principal lookup and the async owner hook), so shutdown can
2807
+ // begin in between. Without this, spawn()'s post-disposal throw
2808
+ // would escape to the POST-level catch and be reported as -32700
2809
+ // "Parse error".
2810
+ let task;
2811
+ try {
2812
+ task = this.taskStore.spawn(
2813
+ result,
2814
+ owner,
2815
+ // Same conversion the synchronous path uses, so a handler's
2816
+ // return value produces an identical result either way.
2817
+ (raw) => this.buildToolCallResult(toolName, raw),
2818
+ );
2819
+ } catch (spawnError) {
2820
+ // Narrowed to the actual shutdown condition. A blanket catch
2821
+ // reported a legitimate throw from the handler's own task setup as
2822
+ // "server is shutting down" — a diagnosis that sends the reader to
2823
+ // look at the wrong thing entirely, on a perfectly healthy server.
2824
+ if (this.stopping || this.taskStore.isDisposed) {
2825
+ return jsonRpcResponse(
2826
+ {
2827
+ jsonrpc: "2.0",
2828
+ id,
2829
+ error: {
2830
+ code: ErrorCode.InternalError,
2831
+ message:
2832
+ "Server is shutting down; no new tasks are accepted.",
2833
+ data: {
2834
+ problem: "server_stopping",
2835
+ recovery: "Retry against a running instance.",
2836
+ },
2837
+ },
2838
+ },
2839
+ 503,
2840
+ {
2841
+ "MCP-Protocol-Version": statelessVersion ??
2842
+ STATELESS_FALLBACK_VERSION,
2843
+ },
2844
+ );
2845
+ }
2846
+ // A real failure: let the tool error path report it as such.
2847
+ throw spawnError;
2848
+ }
2849
+ return c.json({
2850
+ jsonrpc: "2.0",
2851
+ id,
2852
+ // NOT stampResult(): that writes resultType "complete", and a
2853
+ // CreateTaskResult carries "task". Its fields are flat on the
2854
+ // result, not nested under a `task` key.
2855
+ //
2856
+ // Note the asymmetry with tasks/get below, which DOES carry
2857
+ // "complete" — that is an ordinary RPC response which happens to
2858
+ // describe a task. The spec states this distinction three times;
2859
+ // conflating them is the likeliest mistake here.
2860
+ result: this.stampResult(
2861
+ { ...task },
2862
+ statelessVersion,
2863
+ "task",
2864
+ ),
2865
+ });
2866
+ }
2867
+
2868
+ return c.json({
2869
+ jsonrpc: "2.0",
2870
+ id,
2871
+ result: this.stampResult(
2872
+ this.buildToolCallResult(toolName, result),
2873
+ statelessVersion,
2874
+ ),
2875
+ });
1788
2876
  } catch (error) {
1789
2877
  // Handle AuthError with proper HTTP status codes
1790
2878
  if (error instanceof AuthError) {
@@ -1811,7 +2899,13 @@ export class McpApp {
1811
2899
  return c.json({
1812
2900
  jsonrpc: "2.0",
1813
2901
  id,
1814
- result: isErrorResult,
2902
+ // An `isError: true` tool result is still a completed JSON-RPC
2903
+ // result, so it carries `resultType: "complete"`. Only MRTR
2904
+ // interim results (Track B) use `"input_required"`.
2905
+ result: this.stampResult(
2906
+ isErrorResult as Record<string, unknown>,
2907
+ statelessVersion,
2908
+ ),
1815
2909
  });
1816
2910
  } catch (rethrown) {
1817
2911
  this.log(
@@ -1848,7 +2942,13 @@ export class McpApp {
1848
2942
  return c.json({
1849
2943
  jsonrpc: "2.0",
1850
2944
  id,
1851
- result: { tools: this.buildToolListing() },
2945
+ result: this.stampResult(
2946
+ this.withCacheHints(
2947
+ { tools: this.buildToolListing() },
2948
+ statelessVersion,
2949
+ ),
2950
+ statelessVersion,
2951
+ ),
1852
2952
  });
1853
2953
  }
1854
2954
 
@@ -1857,20 +2957,44 @@ export class McpApp {
1857
2957
  return c.json({
1858
2958
  jsonrpc: "2.0",
1859
2959
  id,
1860
- result: {
1861
- resources: Array.from(this.resources.values()).map((r) => ({
1862
- uri: r.resource.uri,
1863
- name: r.resource.name,
1864
- description: r.resource.description,
1865
- mimeType: r.resource.mimeType ?? MCP_APP_MIME_TYPE,
1866
- })),
1867
- },
2960
+ result: this.stampResult(
2961
+ this.withCacheHints({
2962
+ resources: Array.from(this.resources.values()).map((r) => ({
2963
+ uri: r.resource.uri,
2964
+ name: r.resource.name,
2965
+ description: r.resource.description,
2966
+ mimeType: r.resource.mimeType ?? MCP_APP_MIME_TYPE,
2967
+ })),
2968
+ }, statelessVersion),
2969
+ statelessVersion,
2970
+ ),
1868
2971
  });
1869
2972
  }
1870
2973
 
1871
2974
  // Resources read
1872
- if (method === "resources/read" && params?.uri) {
1873
- const uri = params.uri as string;
2975
+ if (method === "resources/read") {
2976
+ // Dispatch by method, not the truthiness of its routing parameter.
2977
+ // `uri: ""` has a valid empty Mcp-Name header representation, but it
2978
+ // is not a usable resource URI. Letting it skip this branch turned a
2979
+ // malformed resources/read into a misleading -32601 method-not-found.
2980
+ const uri = isRecord(params) && typeof params["uri"] === "string" &&
2981
+ params["uri"].length > 0
2982
+ ? params["uri"]
2983
+ : undefined;
2984
+ if (uri === undefined) {
2985
+ return jsonRpcResponse(
2986
+ {
2987
+ jsonrpc: "2.0",
2988
+ id,
2989
+ error: {
2990
+ code: JSONRPC_INVALID_PARAMS,
2991
+ message:
2992
+ "resources/read requires a non-empty string 'uri' parameter",
2993
+ },
2994
+ },
2995
+ 400,
2996
+ );
2997
+ }
1874
2998
  const resourceInfo = this.resources.get(uri);
1875
2999
 
1876
3000
  if (!resourceInfo) {
@@ -1887,7 +3011,20 @@ export class McpApp {
1887
3011
  return c.json({
1888
3012
  jsonrpc: "2.0",
1889
3013
  id,
1890
- result: { contents: [finalContent] },
3014
+ result: this.stampResult(
3015
+ this.withCacheHints(
3016
+ { contents: [finalContent] },
3017
+ statelessVersion,
3018
+ {
3019
+ // resources/read is the only cacheable method an MRTR retry
3020
+ // can target, so it is the only one that needs this guard.
3021
+ isMrtrRetry: isRecord(params) &&
3022
+ (params["requestState"] !== undefined ||
3023
+ params["inputResponses"] !== undefined),
3024
+ },
3025
+ ),
3026
+ statelessVersion,
3027
+ ),
1891
3028
  });
1892
3029
  } catch (error) {
1893
3030
  this.log(
@@ -1908,31 +3045,388 @@ export class McpApp {
1908
3045
  }
1909
3046
  }
1910
3047
 
1911
- // MCP protocol methods we don't implement — return empty results
1912
- // ping: SEP-2575 removes ping in stateless mode, but we deliberately keep
1913
- // answering it for backward compatibility. A SEP-conformant client won't send
1914
- // it, and a stale client using ping for liveness keeps working. (Decision:
1915
- // tolerant over strict, consistent with the rest of the stateless conformance work.)
1916
- if (method === "ping") {
1917
- return c.json({ jsonrpc: "2.0", id, result: {} });
3048
+ // ── subscriptions/listen (SEP-2575) ──────────────────────────────
3049
+ //
3050
+ // Replaces the removed HTTP GET stream and resources/subscribe. The
3051
+ // response IS the stream: a long-lived SSE body carrying only the
3052
+ // notification types the client opted into.
3053
+ if (
3054
+ method === "subscriptions/listen" && this.subscriptions !== null &&
3055
+ statelessVersion === SPEC_2026_07_28
3056
+ ) {
3057
+ const registry = this.subscriptions;
3058
+
3059
+ // A notification-shaped listen makes no sense: the response IS the
3060
+ // stream, and the subscription id IS this request's id — with no id
3061
+ // there is nothing to correlate notifications to.
3062
+ if (id === undefined) {
3063
+ return jsonRpcResponse(
3064
+ {
3065
+ jsonrpc: "2.0",
3066
+ id: null,
3067
+ error: {
3068
+ code: JSONRPC_INVALID_PARAMS,
3069
+ message:
3070
+ "subscriptions/listen requires a JSON-RPC id: the response is the notification stream, and the id identifies the subscription",
3071
+ },
3072
+ },
3073
+ 400,
3074
+ );
3075
+ }
3076
+ const subscriptionId: string | number = id as string | number;
3077
+ // A missing or non-object filter is malformed, not "subscribe to
3078
+ // nothing": a client that meant to subscribe would otherwise get a
3079
+ // 200 stream that stays silent forever, with no way to tell why.
3080
+ if (!isRecord(params) || !isRecord(params["notifications"])) {
3081
+ return jsonRpcResponse(
3082
+ {
3083
+ jsonrpc: "2.0",
3084
+ id,
3085
+ error: {
3086
+ code: JSONRPC_INVALID_PARAMS,
3087
+ message:
3088
+ "subscriptions/listen requires a 'notifications' object naming the types to receive",
3089
+ data: {
3090
+ problem: "missing_field",
3091
+ bodyField: "params.notifications",
3092
+ recovery:
3093
+ 'Send params.notifications, e.g. { toolsListChanged: true } or { resourceSubscriptions: ["ui://x"] }.',
3094
+ },
3095
+ },
3096
+ },
3097
+ 400,
3098
+ );
3099
+ }
3100
+ const filter = validateSubscriptionFilter(
3101
+ params["notifications"] as Record<string, unknown>,
3102
+ );
3103
+ if (!filter.ok) {
3104
+ return jsonRpcResponse(
3105
+ {
3106
+ jsonrpc: "2.0",
3107
+ id,
3108
+ error: {
3109
+ code: JSONRPC_INVALID_PARAMS,
3110
+ message: filter.message,
3111
+ data: {
3112
+ problem: "malformed_field",
3113
+ bodyField: filter.bodyField,
3114
+ recovery: filter.recovery,
3115
+ },
3116
+ },
3117
+ },
3118
+ 400,
3119
+ );
3120
+ }
3121
+ const requested = filter.filter;
3122
+
3123
+ // Recognising `taskIds` is mandatory even though pushing task updates is
3124
+ // not: a client that asks for task notifications without declaring the
3125
+ // Tasks extension MUST be refused. Accepting it would open a stream that
3126
+ // can never deliver, with nothing to say why.
3127
+ if (
3128
+ Array.isArray(requested.taskIds) && requested.taskIds.length > 0
3129
+ ) {
3130
+ const guard = this.requireTasksCapability(
3131
+ isRecord(params["_meta"])
3132
+ ? params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY] as
3133
+ | ClientCapabilities
3134
+ | undefined
3135
+ : undefined,
3136
+ id,
3137
+ );
3138
+ if (guard) return guard;
3139
+ }
3140
+
3141
+ // Computed ONCE by the registry and reused for both the
3142
+ // acknowledgement and the registration. Deriving it independently here
3143
+ // is how a client ends up told it subscribed to a set the registry does
3144
+ // not actually enforce.
3145
+ const agreed = registry.computeAgreedFilter(requested);
3146
+
3147
+ let internalKey: string | null = null;
3148
+ const stream = new ReadableStream<Uint8Array>({
3149
+ start: (controller) => {
3150
+ let closed = false;
3151
+ const sink: SubscriptionSink = {
3152
+ enqueue(chunk) {
3153
+ // The cancel() callback fires before unregister(), so a write
3154
+ // can race a closed controller on every client disconnect.
3155
+ if (closed) return;
3156
+ try {
3157
+ controller.enqueue(chunk);
3158
+ } catch {
3159
+ closed = true;
3160
+ }
3161
+ },
3162
+ close() {
3163
+ if (closed) return;
3164
+ closed = true;
3165
+ try {
3166
+ controller.close();
3167
+ } catch { /* already closed */ }
3168
+ },
3169
+ get isClosed() {
3170
+ return closed;
3171
+ },
3172
+ };
3173
+
3174
+ // The acknowledgement MUST be the first message on the stream, so
3175
+ // it is enqueued BEFORE registering — otherwise a fan-out landing
3176
+ // in between would precede it.
3177
+ sink.enqueue(
3178
+ encodeSSEEvent(
3179
+ buildAcknowledgedMessage(subscriptionId, agreed),
3180
+ ),
3181
+ );
3182
+ internalKey = registry.register(subscriptionId, agreed, sink);
3183
+ },
3184
+ cancel: () => {
3185
+ // Client closed the stream: that IS the cancellation signal on
3186
+ // HTTP, and the server must send nothing further.
3187
+ if (internalKey !== null) {
3188
+ registry.unregister(internalKey, "client");
3189
+ }
3190
+ },
3191
+ });
3192
+
3193
+ return new Response(stream, {
3194
+ status: 200,
3195
+ headers: {
3196
+ "Content-Type": "text/event-stream",
3197
+ "Cache-Control": "no-cache",
3198
+ Connection: "keep-alive",
3199
+ // Tells nginx and friends not to buffer, without which events sit
3200
+ // in a proxy until the buffer fills.
3201
+ "X-Accel-Buffering": "no",
3202
+ "MCP-Protocol-Version": statelessVersion ??
3203
+ STATELESS_FALLBACK_VERSION,
3204
+ },
3205
+ });
1918
3206
  }
1919
- if (method === "prompts/list") {
1920
- return c.json({ jsonrpc: "2.0", id, result: { prompts: [] } });
3207
+
3208
+ // ── Tasks extension (io.modelcontextprotocol/tasks) ──────────────
3209
+ //
3210
+ // The capability guard repeats on every one of these, not just at task
3211
+ // creation: the spec requires the missing-capability error for a
3212
+ // non-declaring client issuing tasks/get, tasks/update OR tasks/cancel.
3213
+ // Guarding creation alone would still let such a client poll and cancel
3214
+ // tasks it could never have been handed.
3215
+ // Version-gated as well as capability-gated: a 2026-only extension must
3216
+ // not be reachable by a peer that negotiated 2025-11-25, which the Tasks
3217
+ // spec states as a MUST NOT. Falling through leaves it a 404, which is
3218
+ // what an unimplemented method looks like from that peer's perspective.
3219
+ if (
3220
+ this.taskStore !== null &&
3221
+ statelessVersion === SPEC_2026_07_28 &&
3222
+ (method === "tasks/get" || method === "tasks/update" ||
3223
+ method === "tasks/cancel")
3224
+ ) {
3225
+ // These are requests, never notifications. Without an id they would
3226
+ // otherwise slip past header validation — which exempts notifications —
3227
+ // then mutate task state and answer with an id-less, malformed
3228
+ // JSON-RPC response.
3229
+ if (id === undefined) {
3230
+ return jsonRpcResponse(
3231
+ {
3232
+ jsonrpc: "2.0",
3233
+ id: null,
3234
+ error: {
3235
+ code: JSONRPC_INVALID_PARAMS,
3236
+ message: `${method} is a request and requires a JSON-RPC id`,
3237
+ data: {
3238
+ problem: "missing_field",
3239
+ bodyField: "id",
3240
+ recovery:
3241
+ "Send the call as a JSON-RPC request with an id, not as a notification.",
3242
+ },
3243
+ },
3244
+ },
3245
+ 400,
3246
+ );
3247
+ }
3248
+ const store = this.taskStore;
3249
+ const guard = this.requireTasksCapability(
3250
+ isRecord(params) && isRecord(params["_meta"])
3251
+ ? params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY] as
3252
+ | ClientCapabilities
3253
+ | undefined
3254
+ : undefined,
3255
+ id,
3256
+ );
3257
+ if (guard) return guard;
3258
+
3259
+ const taskId =
3260
+ isRecord(params) && typeof params["taskId"] === "string"
3261
+ ? params["taskId"]
3262
+ : undefined;
3263
+ if (taskId === undefined) {
3264
+ return jsonRpcResponse(
3265
+ {
3266
+ jsonrpc: "2.0",
3267
+ id,
3268
+ error: {
3269
+ code: JSONRPC_INVALID_PARAMS,
3270
+ message: `${method} requires a string 'taskId' parameter`,
3271
+ },
3272
+ },
3273
+ 400,
3274
+ );
3275
+ }
3276
+
3277
+ const callerBase = callerPrincipal(httpAuthInfo);
3278
+ if (callerBase === null) {
3279
+ return noPrincipalError(
3280
+ id,
3281
+ statelessVersion ?? STATELESS_FALLBACK_VERSION,
3282
+ );
3283
+ }
3284
+ const caller = await taskOwnerKeyFor(
3285
+ this.options,
3286
+ httpAuthInfo,
3287
+ c.req.raw,
3288
+ callerBase,
3289
+ );
3290
+ if (caller === null) {
3291
+ return noOwnerKeyError(
3292
+ id,
3293
+ statelessVersion ?? STATELESS_FALLBACK_VERSION,
3294
+ );
3295
+ }
3296
+
3297
+ if (method === "tasks/get") {
3298
+ const task = store.get(taskId, caller);
3299
+ if (task === null) {
3300
+ return c.json({
3301
+ jsonrpc: "2.0",
3302
+ id,
3303
+ error: {
3304
+ code: JSONRPC_INVALID_PARAMS,
3305
+ message: `Unknown taskId: ${taskId}`,
3306
+ },
3307
+ });
3308
+ }
3309
+ // "complete", not "task" — see the note at task creation.
3310
+ return c.json({
3311
+ jsonrpc: "2.0",
3312
+ id,
3313
+ result: this.stampResult({ ...task }, statelessVersion),
3314
+ });
3315
+ }
3316
+
3317
+ if (method === "tasks/update") {
3318
+ // Spec field name is `inputResponses`, matching MRTR's vocabulary.
3319
+ const responses = isRecord(params) &&
3320
+ isRecord(params["inputResponses"])
3321
+ ? params["inputResponses"]
3322
+ : undefined;
3323
+ if (responses === undefined) {
3324
+ return jsonRpcResponse(
3325
+ {
3326
+ jsonrpc: "2.0",
3327
+ id,
3328
+ error: {
3329
+ code: JSONRPC_INVALID_PARAMS,
3330
+ message: "tasks/update requires an 'inputResponses' object",
3331
+ },
3332
+ },
3333
+ 400,
3334
+ );
3335
+ }
3336
+ if (!store.update(taskId, responses, caller)) {
3337
+ // SHOULD be an error for an unknown id — and an id belonging to
3338
+ // another caller is reported identically, so the response never
3339
+ // confirms that someone else's task exists.
3340
+ return c.json({
3341
+ jsonrpc: "2.0",
3342
+ id,
3343
+ error: {
3344
+ code: JSONRPC_INVALID_PARAMS,
3345
+ message: `Unknown taskId: ${taskId}`,
3346
+ },
3347
+ });
3348
+ }
3349
+ // MUST be an EMPTY acknowledgement (beyond the resultType envelope).
3350
+ // Returning the task state instead would look helpful and be
3351
+ // non-conformant — and the spec calls the ack eventually consistent,
3352
+ // so any state returned here could already be stale.
3353
+ return c.json({
3354
+ jsonrpc: "2.0",
3355
+ id,
3356
+ result: this.stampResult({}, statelessVersion),
3357
+ });
3358
+ }
3359
+
3360
+ // tasks/cancel — likewise an empty ack. Cancellation is cooperative:
3361
+ // the server acknowledges intent, and the task may still finish or
3362
+ // reach a different terminal status.
3363
+ if (!store.cancel(taskId, caller)) {
3364
+ return c.json({
3365
+ jsonrpc: "2.0",
3366
+ id,
3367
+ error: {
3368
+ code: JSONRPC_INVALID_PARAMS,
3369
+ message: `Unknown taskId: ${taskId}`,
3370
+ },
3371
+ });
3372
+ }
3373
+ return c.json({
3374
+ jsonrpc: "2.0",
3375
+ id,
3376
+ result: this.stampResult({}, statelessVersion),
3377
+ });
1921
3378
  }
1922
- // @deprecated (MCP 2026-07-28)
1923
- if (method === "logging/setLevel") {
1924
- return c.json({ jsonrpc: "2.0", id, result: {} });
3379
+
3380
+ // `ping` and `logging/setLevel` were REMOVED by spec 2026-07-28 — not
3381
+ // deprecated. 0.21.0 kept answering `ping` on the stateless path for
3382
+ // backward compatibility; that reasoning does not survive the final
3383
+ // spec, which requires 404 + -32601 for a method the server does not
3384
+ // implement. That response is also how a client distinguishes a modern
3385
+ // server from a legacy HTTP+SSE one, so answering `{}` actively misled
3386
+ // the probe.
3387
+ //
3388
+ // Rather than special-casing these two, the stateless path simply does
3389
+ // not handle them: they fall through to the generic method-not-found
3390
+ // branch at the end, which returns 404 for *any* unimplemented RPC.
3391
+ //
3392
+ // The stateful path keeps both — its peers negotiated `2025-06-18`,
3393
+ // where `logging/setLevel`'s stub is what capability negotiation
3394
+ // expects. Deliberately unstamped: no 2026 envelope on that path.
3395
+ if (this.options.transport !== "stateless") {
3396
+ if (method === "ping") {
3397
+ return c.json({ jsonrpc: "2.0", id, result: {} });
3398
+ }
3399
+ if (method === "logging/setLevel") {
3400
+ return c.json({ jsonrpc: "2.0", id, result: {} });
3401
+ }
3402
+ }
3403
+ if (method === "prompts/list") {
3404
+ return c.json({
3405
+ jsonrpc: "2.0",
3406
+ id,
3407
+ result: this.stampResult(
3408
+ this.withCacheHints({ prompts: [] }, statelessVersion),
3409
+ statelessVersion,
3410
+ ),
3411
+ });
1925
3412
  }
1926
3413
  if (method === "completion/complete") {
1927
3414
  return c.json({
1928
3415
  jsonrpc: "2.0",
1929
3416
  id,
1930
- result: { completion: { values: [] } },
3417
+ result: this.stampResult(
3418
+ { completion: { values: [] } },
3419
+ statelessVersion,
3420
+ ),
1931
3421
  });
1932
3422
  }
1933
3423
 
1934
- // Handle notifications: must have a method and no id (JSON-RPC 2.0 notification)
1935
- if (method && !id) {
3424
+ // Handle notifications: a method and NO id (JSON-RPC 2.0).
3425
+ //
3426
+ // `!id` was wrong: `0` is a valid id and is falsy, so a request with
3427
+ // `id: 0` was answered 202-with-no-body as though it were a
3428
+ // notification. The spec only forbids `null`.
3429
+ if (method && id === undefined) {
1936
3430
  return new Response(null, { status: 202 });
1937
3431
  }
1938
3432
 
@@ -1948,7 +3442,29 @@ export class McpApp {
1948
3442
  });
1949
3443
  }
1950
3444
 
1951
- // Method not found
3445
+ // Method not found.
3446
+ //
3447
+ // Spec 2026-07-28 requires HTTP **404** here, not 200: "If the server
3448
+ // does not implement the requested RPC method, it MUST respond with
3449
+ // 404 Not Found and a JSON-RPC error with code -32601". The status is
3450
+ // load-bearing — a client probing an unknown URL uses exactly this
3451
+ // response to tell a modern MCP endpoint from a legacy HTTP+SSE server,
3452
+ // so answering 200 defeats the backward-compatibility probe.
3453
+ //
3454
+ // This is the general rule that also covers the methods the spec
3455
+ // removed (`ping`, `logging/setLevel`) and the ones not yet implemented
3456
+ // (`subscriptions/listen`, Track G). The legacy stateful path keeps
3457
+ // answering 200 — its peers negotiated a revision with no such rule.
3458
+ if (this.options.transport === "stateless") {
3459
+ return jsonRpcResponse(
3460
+ {
3461
+ jsonrpc: "2.0",
3462
+ id,
3463
+ error: { code: -32601, message: `Method not found: ${method}` },
3464
+ },
3465
+ 404,
3466
+ );
3467
+ }
1952
3468
  return c.json({
1953
3469
  jsonrpc: "2.0",
1954
3470
  id,
@@ -2138,6 +3654,15 @@ export class McpApp {
2138
3654
  * @param sessionId - Session ID (or "anonymous" for clients without session)
2139
3655
  * @param message - JSON-RPC message to send
2140
3656
  */
3657
+ /**
3658
+ * Push a message to one session's SSE stream.
3659
+ *
3660
+ * @deprecated Legacy, stateful-only. Sessions do not exist in spec 2026-07-28,
3661
+ * and the GET SSE stream this writes to returns 405 there — so on the stateless
3662
+ * transport this silently reaches nobody. Use {@link sendNotification}, which
3663
+ * routes to whichever channel the active transport actually has. Dies with the
3664
+ * stateful path.
3665
+ */
2141
3666
  sendToSession(sessionId: string, message: Record<string, unknown>): void {
2142
3667
  const clients = this.sseClients.get(sessionId);
2143
3668
  if (!clients || clients.length === 0) {
@@ -2169,7 +3694,13 @@ export class McpApp {
2169
3694
  }
2170
3695
 
2171
3696
  /**
2172
- * Send a notification to all connected SSE clients
3697
+ * Send a notification to all session-keyed SSE clients.
3698
+ *
3699
+ * @deprecated Legacy, stateful-only, for the same reason as
3700
+ * {@link sendToSession}: on the stateless transport the session map is
3701
+ * necessarily empty, so this reaches nobody and reports no error. Use
3702
+ * {@link sendNotification} — it is the one verb that works on every transport,
3703
+ * fanning out through `subscriptions/listen` where that is the live channel.
2173
3704
  *
2174
3705
  * @param method - Notification method name
2175
3706
  * @param params - Notification parameters
@@ -2362,10 +3893,14 @@ export class McpApp {
2362
3893
 
2363
3894
  /**
2364
3895
  * Send a JSON-RPC notification to the connected transport.
2365
- * For stdio: writes to stdout via MCP SDK transport.
2366
- * For HTTP: broadcasts to all SSE clients.
2367
3896
  *
2368
- * @param method - Notification method (e.g. "notifications/message")
3897
+ * Routing depends on the transport:
3898
+ * - **stateless HTTP**: fanned out to `subscriptions/listen` streams, and only
3899
+ * to the subscribers that opted into that notification type.
3900
+ * - **stateful HTTP**: broadcast to session-keyed SSE clients (legacy).
3901
+ * - **stdio**: written to stdout via the SDK transport.
3902
+ *
3903
+ * @param method - Notification method (e.g. "notifications/tools/list_changed")
2369
3904
  * @param params - Notification parameters
2370
3905
  */
2371
3906
  sendNotification(
@@ -2374,7 +3909,51 @@ export class McpApp {
2374
3909
  ): void {
2375
3910
  if (!this.started) return;
2376
3911
 
2377
- // For HTTP mode, broadcast via SSE
3912
+ // Stateless: route through the subscription registry.
3913
+ //
3914
+ // Without this branch the call reached broadcastNotification, which walks the
3915
+ // session-keyed SSE map — always empty in stateless mode, since GET /mcp
3916
+ // returns 405 and no session SSE stream can exist. The notification vanished
3917
+ // with no error: a caller had every reason to believe it had been delivered.
3918
+ if (this.subscriptions !== null) {
3919
+ switch (method) {
3920
+ case "notifications/tools/list_changed":
3921
+ this.subscriptions.fanOut("toolsListChanged");
3922
+ return;
3923
+ case "notifications/prompts/list_changed":
3924
+ this.subscriptions.fanOut("promptsListChanged");
3925
+ return;
3926
+ case "notifications/resources/list_changed":
3927
+ this.subscriptions.fanOut("resourcesListChanged");
3928
+ return;
3929
+ case "notifications/resources/updated": {
3930
+ const uri = isRecord(params) && typeof params["uri"] === "string"
3931
+ ? params["uri"]
3932
+ : undefined;
3933
+ if (uri === undefined) {
3934
+ this.log(
3935
+ "[WARN] notifications/resources/updated requires a string 'uri' param; dropped",
3936
+ );
3937
+ return;
3938
+ }
3939
+ this.subscriptions.fanOutResourceUpdated(uri);
3940
+ return;
3941
+ }
3942
+ default:
3943
+ // subscriptions/listen carries only the four change types a client can
3944
+ // opt into. Anything else — a request-scoped progress or log message —
3945
+ // belongs on the response stream of the request it relates to, which is
3946
+ // not something this method can reach. Say so rather than drop silently.
3947
+ this.log(
3948
+ `[WARN] sendNotification("${method}") has no delivery channel in stateless mode: ` +
3949
+ "only the four subscriptions/listen change types can be pushed. " +
3950
+ "Request-scoped notifications must travel on their own request's response stream.",
3951
+ );
3952
+ return;
3953
+ }
3954
+ }
3955
+
3956
+ // For legacy stateful HTTP mode, broadcast via session-keyed SSE
2378
3957
  if (this.httpServer) {
2379
3958
  this.broadcastNotification(method, params);
2380
3959
  return;
@@ -2403,7 +3982,6 @@ export class McpApp {
2403
3982
  * Pre-formatted results have a `content` array and are passed through
2404
3983
  * without re-wrapping. This supports proxy/gateway patterns.
2405
3984
  */
2406
- // deno-lint-ignore no-explicit-any
2407
3985
  private isPreformattedResult(
2408
3986
  result: unknown,
2409
3987
  ): result is {
@@ -2420,6 +3998,449 @@ export class McpApp {
2420
3998
  "text" in obj.content[0];
2421
3999
  }
2422
4000
 
4001
+ /**
4002
+ * Apply the spec-2026-07-28 result envelope when — and only when — the peer
4003
+ * negotiated that revision.
4004
+ *
4005
+ * Gated on the **negotiated version**, not on the transport. An earlier draft
4006
+ * used `transport === "stateless"` as a proxy for "modern peer", which is
4007
+ * wrong: the stateless transport also accepts `2025-06-18` and `2025-11-25`
4008
+ * (see `STATELESS_SUPPORTED_VERSIONS`), so that gate stamped a 2026 envelope
4009
+ * onto responses to peers that had negotiated a revision predating it. The
4010
+ * stateful path negotiates nothing per-request and advertises `2025-06-18`, so
4011
+ * it passes `undefined` here and stays on the legacy shape.
4012
+ *
4013
+ * Omitting the envelope for a genuinely legacy peer is safe in the other
4014
+ * direction too: the spec instructs clients to read a missing `resultType` as
4015
+ * `"complete"`.
4016
+ *
4017
+ * Every HTTP result path funnels through here. Adding a new one without it is
4018
+ * the failure mode to watch for — hence the conformance test that walks the
4019
+ * method table rather than asserting one endpoint at a time.
4020
+ *
4021
+ * @param negotiatedVersion Version from the request's `_meta`, or `undefined`
4022
+ * where no per-request negotiation happens.
4023
+ */
4024
+ private stampResult(
4025
+ result: Record<string, unknown>,
4026
+ negotiatedVersion?: string,
4027
+ resultType: "complete" | "task" = "complete",
4028
+ ): Record<string, unknown> {
4029
+ if (negotiatedVersion !== SPEC_2026_07_28) return result;
4030
+ return {
4031
+ ...completeResult(result, {
4032
+ name: this.options.name,
4033
+ version: this.options.version,
4034
+ }),
4035
+ resultType,
4036
+ };
4037
+ }
4038
+
4039
+ /**
4040
+ * Resolve the MRTR signing key once, warning if a deployment has none.
4041
+ *
4042
+ * A missing key is not an error: the spec permits unprotected `requestState`
4043
+ * when tampering can cause nothing worse than the request failing. It is a
4044
+ * loud warning because that condition is easy to believe and hard to verify.
4045
+ */
4046
+ /**
4047
+ * Key lookup that reports failure instead of throwing.
4048
+ *
4049
+ * The `tools/call` call sites sit outside the tool try/catch, so a throw would
4050
+ * reach the POST-level catch and surface as -32700 "Parse error" — the same trap
4051
+ * the earlier throwing principal guard fell into. Returns a ready response
4052
+ * instead.
4053
+ */
4054
+ private async getMrtrKeySafe(
4055
+ id: unknown,
4056
+ version: string,
4057
+ ): Promise<{ key: CryptoKey | null } | { error: Response }> {
4058
+ try {
4059
+ return { key: await this.getMrtrKey() };
4060
+ } catch (error) {
4061
+ return {
4062
+ error: jsonRpcResponse(
4063
+ {
4064
+ jsonrpc: "2.0",
4065
+ id,
4066
+ error: {
4067
+ code: ErrorCode.InternalError,
4068
+ message: "MRTR signing key is unavailable",
4069
+ data: {
4070
+ problem: "mrtr_key_unavailable",
4071
+ detail: error instanceof Error ? error.message : String(error),
4072
+ recovery:
4073
+ "Check mrtr.signingKey. The import is retried on the next request, so a transient failure clears itself.",
4074
+ },
4075
+ },
4076
+ },
4077
+ 500,
4078
+ { "MCP-Protocol-Version": version },
4079
+ ),
4080
+ };
4081
+ }
4082
+ }
4083
+
4084
+ private getMrtrKey(): Promise<CryptoKey | null> {
4085
+ // Assigned synchronously, so two concurrent callers share one import rather
4086
+ // than one of them observing a half-initialised state.
4087
+ //
4088
+ // A REJECTED import is un-memoised in the catch below: caching the rejection
4089
+ // poisoned the instance permanently, and every later retry surfaced it through
4090
+ // the POST-level catch as -32700 "Parse error" — wrong code, and no second
4091
+ // attempt ever made. A transient WebCrypto failure should not be terminal.
4092
+ this.mrtrKeyPromise ??= (async () => {
4093
+ const hex = this.options.mrtr?.signingKey;
4094
+ if (hex === undefined) {
4095
+ this.log(
4096
+ "[WARN] MRTR requestState is unprotected: no mrtr.signingKey configured. " +
4097
+ "A client can tamper with it. Only acceptable when requestState " +
4098
+ "influences nothing beyond whether the request succeeds.",
4099
+ );
4100
+ return null;
4101
+ }
4102
+ try {
4103
+ return await importStateKey(hex);
4104
+ } catch (error) {
4105
+ // Drop the memoised rejection so a later request retries the import.
4106
+ this.mrtrKeyPromise = null;
4107
+ throw new Error(
4108
+ `[McpApp] mrtr.signingKey could not be imported: ${
4109
+ error instanceof Error ? error.message : String(error)
4110
+ }`,
4111
+ );
4112
+ }
4113
+ })();
4114
+ return this.mrtrKeyPromise;
4115
+ }
4116
+
4117
+ /**
4118
+ * Turn a handler's `InputRequiredSignal` into the wire result.
4119
+ *
4120
+ * Validates what the spec puts on the server rather than the client:
4121
+ * - at least one of `inputRequests` / `requestState` must be present;
4122
+ * - no input request may name a capability the client did not declare.
4123
+ *
4124
+ * A violation is the server author's bug, so it surfaces as `-32603` rather
4125
+ * than being emitted as an invalid MRTR result for the client to puzzle over.
4126
+ */
4127
+ private async buildInputRequiredResult(
4128
+ signal: InputRequiredSignal,
4129
+ context: {
4130
+ clientCapabilities: ClientCapabilities | undefined;
4131
+ principal: string;
4132
+ method: string;
4133
+ /** Digest of the arguments as received, taken before the pipeline ran. */
4134
+ paramsDigest: string;
4135
+ },
4136
+ ): Promise<
4137
+ { ok: true; result: Record<string, unknown> } | {
4138
+ ok: false;
4139
+ message: string;
4140
+ code: number;
4141
+ data?: Record<string, unknown>;
4142
+ }
4143
+ > {
4144
+ const requests = signal.inputRequests;
4145
+
4146
+ // `Object.keys(null)` throws, and `inputRequests: null` survives JSON — so an
4147
+ // unchecked map reached the generic tool-error path as a 200 instead of being
4148
+ // classified as the malformed server output it is. Validated before enumerating.
4149
+ if (requests !== undefined && !isRecord(requests)) {
4150
+ return {
4151
+ ok: false,
4152
+ code: ErrorCode.InternalError,
4153
+ message: "Malformed inputRequest: inputRequests must be an object",
4154
+ };
4155
+ }
4156
+
4157
+ const hasRequests = requests !== undefined &&
4158
+ Object.keys(requests).length > 0;
4159
+
4160
+ if (!hasRequests && signal.requestState === undefined) {
4161
+ return {
4162
+ ok: false,
4163
+ code: ErrorCode.InternalError,
4164
+ message:
4165
+ "An InputRequiredResult must carry at least one of inputRequests or requestState (spec 2026-07-28, MRTR server rule 6)",
4166
+ };
4167
+ }
4168
+
4169
+ let canonicalRequests: Record<string, unknown> | undefined;
4170
+ if (hasRequests) {
4171
+ const check = checkInputRequestCapabilities(
4172
+ requests as Record<string, InputRequestEntry>,
4173
+ context.clientCapabilities as Record<string, unknown> | undefined,
4174
+ );
4175
+ if (!check.ok) {
4176
+ // A structurally invalid input request is the SERVER's bug. Reporting it
4177
+ // as -32021 told the client to declare a capability it already had, and
4178
+ // hid the real fault behind a client-facing error.
4179
+ if (check.kind === "malformed") {
4180
+ return {
4181
+ ok: false,
4182
+ code: ErrorCode.InternalError,
4183
+ message: `Malformed inputRequest: ${
4184
+ check.missingCapabilities.join(", ")
4185
+ }`,
4186
+ };
4187
+ }
4188
+ // Spec rule 7 is a MUST NOT on the server: never ask for input the
4189
+ // client cannot provide. Emitting it anyway would strand the request.
4190
+ return {
4191
+ ok: false,
4192
+ code: MCP_MISSING_REQUIRED_CLIENT_CAPABILITY,
4193
+ message:
4194
+ `Cannot request input for capabilities the client did not declare: ${
4195
+ check.missingCapabilities.join(", ")
4196
+ }`,
4197
+ // ClientCapabilities-shaped so a typed client can read it directly and
4198
+ // learn which capability to declare.
4199
+ data: {
4200
+ // The check supplies a nested shape for sub-capabilities; otherwise
4201
+ // the names are top-level keys.
4202
+ requiredCapabilities: check.requiredCapabilities ??
4203
+ Object.fromEntries(
4204
+ check.missingCapabilities.map((cap) => [cap, {}]),
4205
+ ),
4206
+ },
4207
+ };
4208
+ }
4209
+ canonicalRequests = check.canonicalRequests;
4210
+ }
4211
+
4212
+ // Seal the token so the retry can be proven legitimate. The payload holds
4213
+ // only bindings — principal, method, argument digest, expiry, nonce — not
4214
+ // application state: since the digest guarantees identical arguments, a
4215
+ // handler rebuilds its context from those.
4216
+ //
4217
+ // The principal binding is only meaningful when auth is configured; see the
4218
+ // verification site. Sealing happens AFTER the capability check on purpose —
4219
+ // no point minting a token for a result that will be refused.
4220
+ // Resolved here regardless of `needsKey` at ingress: a FIRST leg carries
4221
+ // neither MRTR field and still needs a sealed token. A rejected import is
4222
+ // reported as what it is rather than surfacing as a tool failure — the
4223
+ // handler did nothing wrong.
4224
+ let key: CryptoKey | null;
4225
+ try {
4226
+ key = await this.getMrtrKey();
4227
+ } catch (error) {
4228
+ return {
4229
+ ok: false,
4230
+ code: ErrorCode.InternalError,
4231
+ message: "MRTR signing key is unavailable",
4232
+ data: {
4233
+ problem: "mrtr_key_unavailable",
4234
+ detail: error instanceof Error ? error.message : String(error),
4235
+ recovery:
4236
+ "Check mrtr.signingKey. The import is retried on the next request, so a transient failure clears itself.",
4237
+ },
4238
+ };
4239
+ }
4240
+ let requestState = signal.requestState;
4241
+ if (key !== null) {
4242
+ const ttl = this.options.mrtr?.defaultTtlSecs ?? 300;
4243
+ requestState = await sealRequestState({
4244
+ sub: context.principal,
4245
+ method: context.method,
4246
+ paramsDigest: context.paramsDigest,
4247
+ exp: Math.floor(Date.now() / 1000) + ttl,
4248
+ nonce: bytesToHexLocal(crypto.getRandomValues(new Uint8Array(16))),
4249
+ }, key);
4250
+ }
4251
+
4252
+ // No `?? requests` fallback. Falling back to the handler's object would
4253
+ // silently restore the very bypass this closes — a fallback that reopens a
4254
+ // security hole is worse than a failure. If the invariant ever breaks, say so.
4255
+ if (hasRequests && canonicalRequests === undefined) {
4256
+ return {
4257
+ ok: false,
4258
+ code: ErrorCode.InternalError,
4259
+ message:
4260
+ "Internal invariant violated: inputRequests were not canonicalised before emission",
4261
+ };
4262
+ }
4263
+
4264
+ // Serialisation can EMPTY the map: JSON drops keys whose value is `undefined`,
4265
+ // so `{ ask: undefined }` canonicalises to `{}`. The at-least-one rule was
4266
+ // checked against the original, so that emitted an InputRequiredResult with an
4267
+ // empty map and — where no key is configured — no requestState either, leaving
4268
+ // the client nothing to answer and no reason to retry.
4269
+ const canonicalCount = canonicalRequests === undefined
4270
+ ? 0
4271
+ : Object.keys(canonicalRequests).length;
4272
+ if (hasRequests && canonicalCount === 0) {
4273
+ return {
4274
+ ok: false,
4275
+ code: ErrorCode.InternalError,
4276
+ message:
4277
+ "inputRequests contained no serialisable entries (keys with an undefined value are dropped by JSON)",
4278
+ };
4279
+ }
4280
+ if (canonicalCount === 0 && requestState === undefined) {
4281
+ return {
4282
+ ok: false,
4283
+ code: ErrorCode.InternalError,
4284
+ message:
4285
+ "An InputRequiredResult must carry at least one of inputRequests or requestState (spec 2026-07-28, MRTR server rule 6)",
4286
+ };
4287
+ }
4288
+
4289
+ return {
4290
+ ok: true,
4291
+ result: {
4292
+ resultType: "input_required",
4293
+ // This path deliberately cannot use stampResult(): that would replace
4294
+ // its `input_required` discriminator with `complete`. It is still a
4295
+ // 2026 Result, though, so carry the same server identity envelope as
4296
+ // every other response.
4297
+ _meta: {
4298
+ [STATELESS_SERVER_INFO_KEY]: {
4299
+ name: this.options.name,
4300
+ version: this.options.version,
4301
+ },
4302
+ },
4303
+ // The clone the check inspected, NOT the handler's object. Serialising the
4304
+ // original a second time lets a stateful `toJSON()` return a different
4305
+ // value for the response than the gate approved.
4306
+ ...(canonicalRequests !== undefined
4307
+ ? { inputRequests: canonicalRequests }
4308
+ : {}),
4309
+ ...(requestState !== undefined ? { requestState } : {}),
4310
+ },
4311
+ };
4312
+ }
4313
+
4314
+ /**
4315
+ * Reject a Tasks request from a client that did not declare the extension.
4316
+ *
4317
+ * Returns a ready 400 response to return, or `null` when the client is
4318
+ * entitled to proceed. Two distinct spec rules converge here: a server
4319
+ * **MUST NOT** hand a task to a non-declaring client, and **MUST** answer the
4320
+ * missing-capability error when one calls `tasks/*`.
4321
+ *
4322
+ * `-32021` (`MissingRequiredClientCapability`) is the code, and
4323
+ * `data.requiredCapabilities` is required to list what was missing — a client
4324
+ * that gets this back needs to know which capability to add, not just that
4325
+ * something was absent.
4326
+ */
4327
+ private requireTasksCapability(
4328
+ clientCapabilities: ClientCapabilities | undefined,
4329
+ id: unknown,
4330
+ ): Response | null {
4331
+ if (this.taskStore === null) {
4332
+ return jsonRpcResponse(
4333
+ {
4334
+ jsonrpc: "2.0",
4335
+ id,
4336
+ error: {
4337
+ code: ErrorCode.MethodNotFound,
4338
+ message:
4339
+ `Tasks extension is not enabled on this server (declare "${TASKS_EXTENSION_ID}" in McpAppOptions.extensions)`,
4340
+ },
4341
+ },
4342
+ 404,
4343
+ );
4344
+ }
4345
+
4346
+ const extensions = clientCapabilities?.extensions;
4347
+ const declared = isRecord(extensions) &&
4348
+ extensions[TASKS_EXTENSION_ID] !== undefined;
4349
+ if (declared) return null;
4350
+
4351
+ return jsonRpcResponse(
4352
+ {
4353
+ jsonrpc: "2.0",
4354
+ id,
4355
+ error: {
4356
+ code: MCP_MISSING_REQUIRED_CLIENT_CAPABILITY,
4357
+ message:
4358
+ `Client did not declare the "${TASKS_EXTENSION_ID}" extension`,
4359
+ // ClientCapabilities-shaped, per the schema: capability keys mapping
4360
+ // to their settings object. An array of names would not deserialise
4361
+ // into `ClientCapabilities` on a typed client.
4362
+ data: {
4363
+ requiredCapabilities: { extensions: { [TASKS_EXTENSION_ID]: {} } },
4364
+ },
4365
+ },
4366
+ },
4367
+ 400,
4368
+ );
4369
+ }
4370
+
4371
+ /**
4372
+ * Task status transitions, for pushing to subscribers.
4373
+ *
4374
+ * The spec's notification method is `notifications/tasks` — not a
4375
+ * `tasks/`-prefixed name, which would collide with the request methods.
4376
+ *
4377
+ * Delivery goes out over `subscriptions/listen` once that route is wired
4378
+ * (Track G); the registry exists but the transport does not yet open streams.
4379
+ * Until then this is intentionally a no-op beyond the log: polling via
4380
+ * `tasks/get` is the spec's default and works without it.
4381
+ */
4382
+ private onTaskChanged(task: DetailedTask): void {
4383
+ this.log(`task ${task.taskId} → ${task.status}`);
4384
+ }
4385
+
4386
+ /**
4387
+ * Add the required `CacheableResult` fields (spec 2026-07-28, SEP-2549).
4388
+ *
4389
+ * Applies to `tools/list`, `prompts/list`, `resources/list`, `resources/read`
4390
+ * and `resources/templates/list`, where the final spec makes both fields
4391
+ * required rather than optional. Same version gate as {@link stampResult}:
4392
+ * neither field exists in an earlier revision.
4393
+ *
4394
+ * Both are hints — a client that ignores them stays correct, it just polls
4395
+ * more often.
4396
+ */
4397
+ private withCacheHints(
4398
+ result: Record<string, unknown>,
4399
+ negotiatedVersion?: string,
4400
+ request?: { readonly isMrtrRetry?: boolean },
4401
+ ): Record<string, unknown> {
4402
+ if (negotiatedVersion !== SPEC_2026_07_28) return result;
4403
+
4404
+ // A result produced by an MRTR retry MUST NOT be cached: it depends on
4405
+ // `inputResponses` / `requestState`, which are not part of the cache key, so
4406
+ // a cache would serve it for a later request that supplied different input.
4407
+ // Emitting no hints is how a server declines to make the result cacheable —
4408
+ // clients read an absent ttlMs as 0.
4409
+ if (request?.isMrtrRetry) return result;
4410
+
4411
+ return {
4412
+ ...result,
4413
+ ttlMs: this.cacheTtlMs,
4414
+ cacheScope: this.options.cache?.scope ?? "private",
4415
+ };
4416
+ }
4417
+
4418
+ /**
4419
+ * Capabilities advertised on `server/discover` and `initialize`.
4420
+ *
4421
+ * Single source of truth: these two responses used to build the same object
4422
+ * independently, which is how they drift.
4423
+ *
4424
+ * `extensions` (spec 2026-07-28) is the declaration point for opt-in
4425
+ * extensions such as `io.modelcontextprotocol/tasks`. It is emitted only when
4426
+ * the consumer actually declares one — an empty `extensions: {}` would read as
4427
+ * "this server supports no extensions", which is a stronger claim than we can
4428
+ * make while MCP Apps support is de-facto (via `ui://` resources) rather than
4429
+ * declared. Wire it up here once the Apps extension identifier is pinned.
4430
+ */
4431
+ private buildServerCapabilities(): Record<string, unknown> {
4432
+ const { extensions } = this.options;
4433
+ // The declaration in options is the single source of truth: `taskStore` is
4434
+ // created from it, so advertising and behaviour cannot drift apart.
4435
+ return {
4436
+ tools: {},
4437
+ resources: this.resources.size > 0 ? {} : undefined,
4438
+ ...(extensions && Object.keys(extensions).length > 0
4439
+ ? { extensions }
4440
+ : {}),
4441
+ };
4442
+ }
4443
+
2423
4444
  /**
2424
4445
  * Build the tools/list response, filtering out app-only tools
2425
4446
  * and passing through outputSchema/annotations when defined.
@@ -2442,7 +4463,25 @@ export class McpApp {
2442
4463
  if (t.outputSchema !== undefined) entry.outputSchema = t.outputSchema;
2443
4464
  if (t.annotations !== undefined) entry.annotations = t.annotations;
2444
4465
  return entry;
2445
- });
4466
+ })
4467
+ // Spec 2026-07-28 (minor change 3): return tools in a deterministic order.
4468
+ // It lets clients cache the list and improves LLM prompt-cache hit rates.
4469
+ //
4470
+ // Map iteration is already insertion-ordered, so this only matters where
4471
+ // registration order itself is unstable — which it is for the relay/proxy
4472
+ // case, where tools are registered as child servers are discovered
4473
+ // asynchronously. Sorting by name makes the output independent of who
4474
+ // answered first.
4475
+ //
4476
+ // Deliberately not `localeCompare`: that orders differently per host
4477
+ // locale, reintroducing the very non-determinism being removed here.
4478
+ .sort((a, b) =>
4479
+ (a.name as string) < (b.name as string)
4480
+ ? -1
4481
+ : (a.name as string) > (b.name as string)
4482
+ ? 1
4483
+ : 0
4484
+ );
2446
4485
  }
2447
4486
 
2448
4487
  /**
@@ -2473,7 +4512,7 @@ export class McpApp {
2473
4512
  ): Record<string, unknown> {
2474
4513
  // Proxy/gateway pattern — pass through as-is
2475
4514
  if (this.isPreformattedResult(result)) {
2476
- return result as Record<string, unknown>;
4515
+ return canonicaliseWireResult(result as Record<string, unknown>);
2477
4516
  }
2478
4517
 
2479
4518
  const tool = this.tools.get(toolName);
@@ -2485,7 +4524,7 @@ export class McpApp {
2485
4524
  structuredContent: result.structuredContent,
2486
4525
  };
2487
4526
  if (tool?._meta) r._meta = tool._meta;
2488
- return r;
4527
+ return canonicaliseWireResult(r);
2489
4528
  }
2490
4529
 
2491
4530
  // Plain value: JSON-stringify into content[0].text
@@ -2498,7 +4537,7 @@ export class McpApp {
2498
4537
  }],
2499
4538
  };
2500
4539
  if (tool?._meta) r._meta = tool._meta;
2501
- return r;
4540
+ return canonicaliseWireResult(r);
2502
4541
  }
2503
4542
 
2504
4543
  /**