@casys/mcp-server 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mcp-app.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * McpApp — Hono-style framework for MCP servers
3
3
  *
4
- * High-performance MCP server with built-in concurrency control,
5
- * backpressure, and optional sampling support.
4
+ * High-performance MCP server with built-in concurrency control
5
+ * and backpressure.
6
6
  *
7
7
  * Wraps the official @modelcontextprotocol/sdk with production-ready
8
8
  * middleware, auth, and observability features.
@@ -26,7 +26,6 @@ import {
26
26
  import { Hono } from "hono";
27
27
  import { cors } from "hono/cors";
28
28
  import { RequestQueue } from "./concurrency/request-queue.js";
29
- import { SamplingBridge } from "./sampling/sampling-bridge.js";
30
29
  import { RateLimiter } from "./concurrency/rate-limiter.js";
31
30
  import { SchemaValidator } from "./validation/schema-validator.js";
32
31
  import { createMiddlewareRunner } from "./middleware/runner.js";
@@ -34,6 +33,7 @@ import { createRateLimitMiddleware } from "./middleware/rate-limit.js";
34
33
  import { createValidationMiddleware } from "./middleware/validation.js";
35
34
  import { createBackpressureMiddleware } from "./middleware/backpressure.js";
36
35
  import type {
36
+ McpLogLevel,
37
37
  Middleware,
38
38
  MiddlewareContext,
39
39
  MiddlewareResult,
@@ -71,10 +71,50 @@ import {
71
71
  MCP_APP_URI_SCHEME,
72
72
  } from "./types.js";
73
73
  import { discoverViewers, resolveViewerDistPath } from "./ui/viewer-utils.js";
74
- import type { DirEntry, DiscoverViewersFS } from "./ui/viewer-utils.js";
74
+ import type { DiscoverViewersFS } from "./ui/viewer-utils.js";
75
75
  import { buildCspHeader, injectCspMetaTag } from "./security/csp.js";
76
+ import {
77
+ collectMirroredParams,
78
+ type MirroredParam,
79
+ validateRequestHeaders,
80
+ } from "./transport/request-headers.js";
81
+ import {
82
+ type DetailedTask,
83
+ isAsyncTaskDescriptor,
84
+ TaskStore,
85
+ } from "./tasks/mod.js";
86
+ import {
87
+ checkInputRequestCapabilities,
88
+ importStateKey,
89
+ type InputRequestEntry,
90
+ type InputRequiredSignal,
91
+ paramsDigest,
92
+ sealRequestState,
93
+ verifyRequestState,
94
+ } from "./mrtr/mod.js";
95
+ import {
96
+ buildAcknowledgedMessage,
97
+ encodeSSEEvent,
98
+ type SubscriptionFilter,
99
+ SubscriptionRegistry,
100
+ type SubscriptionSink,
101
+ } from "./subscriptions/subscription-registry.js";
76
102
  import { ServerMetrics } from "./observability/metrics.js";
77
103
  import { endToolCallSpan, startToolCallSpan } from "./observability/otel.js";
104
+ import {
105
+ BodyTooLargeError,
106
+ DEFAULT_MAX_BODY_BYTES,
107
+ getClientIpFromHeaders,
108
+ readBodyWithLimit,
109
+ } from "./http/body.js";
110
+ import {
111
+ bytesToHexLocal,
112
+ callerPrincipal,
113
+ noOwnerKeyError,
114
+ noPrincipalError,
115
+ taskOwnerKeyFor,
116
+ } from "./http/request-guards.js";
117
+ import { isRecord, jsonRpcResponse } from "./http/wire.js";
78
118
 
79
119
  /**
80
120
  * Tool definition with handler
@@ -91,84 +131,6 @@ interface RegisteredResourceInfo {
91
131
  handler: ResourceHandler;
92
132
  }
93
133
 
94
- /**
95
- * SSE client connection for Streamable HTTP
96
- */
97
- interface SSEClient {
98
- sessionId: string;
99
- controller: ReadableStreamDefaultController<Uint8Array>;
100
- createdAt: number;
101
- lastEventId: number;
102
- }
103
-
104
- const DEFAULT_MAX_BODY_BYTES = 1_000_000;
105
-
106
- class BodyTooLargeError extends Error {
107
- constructor(maxBytes: number) {
108
- super(`Payload too large. Max ${maxBytes} bytes.`);
109
- this.name = "BodyTooLargeError";
110
- }
111
- }
112
-
113
- /**
114
- * Generate a cryptographically secure session ID
115
- */
116
- function generateSessionId(): string {
117
- const bytes = new Uint8Array(16);
118
- crypto.getRandomValues(bytes);
119
- return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
120
- }
121
-
122
- function getClientIpFromHeaders(headers: Headers): string {
123
- const forwarded = headers.get("x-forwarded-for");
124
- if (forwarded) {
125
- return forwarded.split(",")[0]?.trim() || "unknown";
126
- }
127
- return headers.get("x-real-ip") ??
128
- headers.get("cf-connecting-ip") ??
129
- "unknown";
130
- }
131
-
132
- async function readBodyWithLimit(
133
- request: Request,
134
- maxBytes: number | null,
135
- ): Promise<Uint8Array> {
136
- const contentLength = request.headers.get("content-length");
137
- if (maxBytes !== null && contentLength) {
138
- const length = Number(contentLength);
139
- if (!Number.isNaN(length) && length > maxBytes) {
140
- throw new BodyTooLargeError(maxBytes);
141
- }
142
- }
143
-
144
- if (!request.body) {
145
- return new Uint8Array();
146
- }
147
-
148
- const reader = request.body.getReader();
149
- const chunks: Uint8Array[] = [];
150
- let total = 0;
151
-
152
- while (true) {
153
- const { done, value } = await reader.read();
154
- if (done) break;
155
- if (!value) continue;
156
- total += value.length;
157
- if (maxBytes !== null && total > maxBytes) {
158
- throw new BodyTooLargeError(maxBytes);
159
- }
160
- chunks.push(value);
161
- }
162
-
163
- const body = new Uint8Array(total);
164
- let offset = 0;
165
- for (const chunk of chunks) {
166
- body.set(chunk, offset);
167
- offset += chunk.length;
168
- }
169
- return body;
170
- }
171
-
172
134
  // ── Track A (spec 2026-07-28) — Stateless transport constants ───────────────
173
135
 
174
136
  /** Namespaced protocolVersion key in params._meta (spec 2026-07-28) */
@@ -184,27 +146,201 @@ const STATELESS_CLIENT_CAPABILITIES_KEY =
184
146
  /** Protocol versions accepted by this server in stateless mode */
185
147
  const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
186
148
  "2026-07-28",
187
- "2025-06-18",
188
- "2025-11-25",
189
149
  ];
190
150
 
191
- /** Version echoed in MCP-Protocol-Version header on error responses (server's stable baseline) */
192
- const STATELESS_FALLBACK_VERSION = "2025-06-18";
151
+ /** Namespaced serverInfo key in a result's _meta (spec 2026-07-28, SHOULD) */
152
+ const STATELESS_SERVER_INFO_KEY = "io.modelcontextprotocol/serverInfo";
153
+
154
+ /**
155
+ * Namespaced per-request log level in params._meta (spec 2026-07-28).
156
+ * Replaces the removed `logging/setLevel` RPC: the level is now scoped to the
157
+ * request that asked for it, so there is no server-side level to mutate.
158
+ */
159
+ const STATELESS_LOG_LEVEL_KEY = "io.modelcontextprotocol/logLevel";
160
+
161
+ /** Protocol version whose wire format this server implements natively */
162
+ const SPEC_2026_07_28 = "2026-07-28";
163
+
164
+ /**
165
+ * Tasks extension identifier (SEP-2663).
166
+ *
167
+ * Declaring it in `McpAppOptions.extensions` is what switches the extension on.
168
+ * The spec forbids returning a task handle to a client that did not declare
169
+ * support, and forbids advertising an extension we do not implement — so the
170
+ * declaration gates both directions.
171
+ */
172
+ const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
173
+
174
+ /** Version echoed in MCP-Protocol-Version header on error responses (server's only accepted version) */
175
+ const STATELESS_FALLBACK_VERSION = "2026-07-28";
193
176
 
194
177
  const JSONRPC_INVALID_PARAMS = ErrorCode.InvalidParams;
195
- const MCP_UNSUPPORTED_PROTOCOL_VERSION = -32004;
178
+
179
+ // ── Error codes (spec 2026-07-28, allocation policy) ────────────────────────
180
+ //
181
+ // The final spec partitions the JSON-RPC server-error range:
182
+ // -32000..-32019 implementation-defined (existing SDK usage grandfathered)
183
+ // -32020..-32099 reserved for the MCP specification
184
+ //
185
+ // The codes below were renumbered between the May 2026 Release Candidate — which
186
+ // 0.21.0 shipped against — and the final revision. Do not "restore" the RC
187
+ // values: -32001 and -32004 no longer carry these MCP-defined meanings.
188
+ //
189
+ // Note the policy is stricter than "the low range is grandfathered": the spec
190
+ // says new implementations SHOULD NOT use -32000..-32019 at all, and MUST NOT
191
+ // emit -32002 (which 2025-11-25 used for resource-not-found). Our auth and
192
+ // session errors therefore live outside the reserved range entirely — see
193
+ // auth/middleware.ts.
194
+
195
+ /** Headers disagree with the request body, or a required header is missing. */
196
+ const MCP_HEADER_MISMATCH = -32020;
197
+
198
+ /**
199
+ * Client did not declare a capability the request requires.
200
+ *
201
+ * Emitted by the Tasks extension guard. `data.requiredCapabilities` must list
202
+ * the missing capabilities alongside it.
203
+ */
204
+ const MCP_MISSING_REQUIRED_CLIENT_CAPABILITY = -32021;
205
+
206
+ /** Requested protocol version is not one this server implements. */
207
+ const MCP_UNSUPPORTED_PROTOCOL_VERSION = -32022;
196
208
 
197
209
  interface StatelessClientMeta {
198
210
  readonly clientInfo?: Implementation;
199
211
  readonly clientCapabilities?: ClientCapabilities;
212
+ readonly logLevel?: McpLogLevel;
213
+ }
214
+
215
+ /** Valid `io.modelcontextprotocol/logLevel` values (RFC 5424 severities). */
216
+ const MCP_LOG_LEVELS: readonly McpLogLevel[] = [
217
+ "debug",
218
+ "info",
219
+ "notice",
220
+ "warning",
221
+ "error",
222
+ "critical",
223
+ "alert",
224
+ "emergency",
225
+ ];
226
+
227
+ /**
228
+ * Read the per-request log level out of `params._meta`.
229
+ *
230
+ * An unrecognized value is dropped rather than rejected: the level is an
231
+ * optional hint, and failing a whole tool call because a client sent
232
+ * `"verbose"` would be a worse outcome than emitting nothing.
233
+ */
234
+ function readLogLevel(meta: Record<string, unknown>): McpLogLevel | undefined {
235
+ const raw = meta[STATELESS_LOG_LEVEL_KEY];
236
+ return typeof raw === "string" && MCP_LOG_LEVELS.includes(raw as McpLogLevel)
237
+ ? raw as McpLogLevel
238
+ : undefined;
239
+ }
240
+
241
+ /**
242
+ * Validate the client-owned subscriptions/listen filter before it reaches the
243
+ * registry. The registry deliberately works with a typed SubscriptionFilter;
244
+ * casting untrusted JSON into it made truthy values subscribe to list changes
245
+ * and let invalid URI entries reach the SSE acknowledgement.
246
+ */
247
+ function validateSubscriptionFilter(
248
+ filter: Record<string, unknown>,
249
+ ):
250
+ | { ok: true; filter: SubscriptionFilter }
251
+ | {
252
+ ok: false;
253
+ message: string;
254
+ bodyField: string;
255
+ recovery: string;
256
+ } {
257
+ for (
258
+ const field of [
259
+ "toolsListChanged",
260
+ "promptsListChanged",
261
+ "resourcesListChanged",
262
+ ] as const
263
+ ) {
264
+ if (filter[field] !== undefined && typeof filter[field] !== "boolean") {
265
+ return {
266
+ ok: false,
267
+ message: `${field} must be a boolean when present`,
268
+ bodyField: `params.notifications.${field}`,
269
+ recovery:
270
+ `Send ${field} as true or false, or omit it when that notification type is not requested.`,
271
+ };
272
+ }
273
+ }
274
+
275
+ for (const field of ["resourceSubscriptions", "taskIds"] as const) {
276
+ const value = filter[field];
277
+ if (value === undefined) continue;
278
+ if (!Array.isArray(value)) {
279
+ return {
280
+ ok: false,
281
+ message: `${field} must be an array of strings when present`,
282
+ bodyField: `params.notifications.${field}`,
283
+ recovery:
284
+ `Send ${field} as an array of strings, or omit it when no identifiers are requested.`,
285
+ };
286
+ }
287
+ const malformedIndex = value.findIndex((entry) =>
288
+ typeof entry !== "string"
289
+ );
290
+ if (malformedIndex !== -1) {
291
+ return {
292
+ ok: false,
293
+ message: `${field} entries must be strings`,
294
+ bodyField: `params.notifications.${field}[${malformedIndex}]`,
295
+ recovery:
296
+ `Send only string entries in ${field}; remove or replace the malformed entry.`,
297
+ };
298
+ }
299
+ }
300
+
301
+ return { ok: true, filter: filter as SubscriptionFilter };
302
+ }
303
+
304
+ /**
305
+ * Stamp a result with the spec-2026-07-28 envelope: the required `resultType`
306
+ * (SEP-2322) and the server's identity under `_meta` (SEP-2575, SHOULD).
307
+ *
308
+ * `_meta` is merged, never replaced — tool results carry their own `_meta` (MCP
309
+ * Apps UI hints, for instance) and losing it would break the viewers.
310
+ *
311
+ * Pure by design so the envelope can be asserted directly in tests without
312
+ * standing up a server; the caller decides whether the envelope applies.
313
+ */
314
+ function completeResult(
315
+ result: Record<string, unknown>,
316
+ serverInfo: Implementation,
317
+ ): Record<string, unknown> {
318
+ const existingMeta = isRecord(result["_meta"]) ? result["_meta"] : undefined;
319
+ return {
320
+ ...result,
321
+ resultType: "complete",
322
+ _meta: { ...existingMeta, [STATELESS_SERVER_INFO_KEY]: serverInfo },
323
+ };
200
324
  }
201
325
 
202
326
  /**
203
- * Narrow type-guard: returns true iff `v` is a plain object (not array, not null).
204
- * Used to safely extract fields from JSON-RPC `params` without unsafe casts.
327
+ * Reduce a handler-built result to the exact JSON object that will cross the
328
+ * transport boundary. Preformatted proxy results bypass the normal text
329
+ * serialisation path, so without this gate a BigInt or cycle could be stored as
330
+ * a completed task and only explode on a later tasks/get response.
205
331
  */
206
- function isRecord(v: unknown): v is Record<string, unknown> {
207
- return typeof v === "object" && v !== null && !Array.isArray(v);
332
+ function canonicaliseWireResult(
333
+ result: Record<string, unknown>,
334
+ ): Record<string, unknown> {
335
+ const serialised = JSON.stringify(result);
336
+ if (serialised === undefined) {
337
+ throw new Error("Tool result is not JSON-serialisable");
338
+ }
339
+ const canonical = JSON.parse(serialised);
340
+ if (!isRecord(canonical)) {
341
+ throw new Error("Tool result must serialise to an object");
342
+ }
343
+ return canonical;
208
344
  }
209
345
 
210
346
  // ─────────────────────────────────────────────────────────────────────────────
@@ -216,7 +352,6 @@ function isRecord(v: unknown): v is Record<string, unknown> {
216
352
  * - Wraps official @modelcontextprotocol/sdk
217
353
  * - Concurrency limiting (default: 10 max concurrent)
218
354
  * - Multiple backpressure strategies (sleep/queue/reject)
219
- * - Optional bidirectional sampling support
220
355
  * - Metrics for monitoring
221
356
  * - Graceful shutdown
222
357
  *
@@ -248,8 +383,73 @@ export class McpApp {
248
383
  private requestQueue: RequestQueue;
249
384
  private rateLimiter: RateLimiter | null = null;
250
385
  private schemaValidator: SchemaValidator | null = null;
251
- private samplingBridge: SamplingBridge | null = null;
252
386
  private tools = new Map<string, ToolWithHandler>();
387
+
388
+ /**
389
+ * Tool name → parameters the tool asked clients to mirror into
390
+ * `Mcp-Param-{Name}` headers (spec 2026-07-28, `x-mcp-header`).
391
+ *
392
+ * Populated at registration so the per-request path is a map lookup rather
393
+ * than a schema walk. Tools without annotations are simply absent.
394
+ */
395
+ private mirroredParams = new Map<string, MirroredParam[]>();
396
+
397
+ /**
398
+ * Task store for the Tasks extension, or `null` when the consumer did not
399
+ * declare it.
400
+ *
401
+ * Created only on declaration: a server not using Tasks should not pay for a
402
+ * sweep timer, and a `tasks/*` call against it must read as the unimplemented
403
+ * method it is (404 + -32601) rather than hitting an empty store.
404
+ */
405
+ private taskStore: TaskStore | null;
406
+
407
+ /**
408
+ * Set synchronously at the top of `stop()`.
409
+ *
410
+ * Checked before spawning a task, because the pipeline is async: a handler that
411
+ * settles during shutdown would otherwise start work in a store already drained,
412
+ * producing a task that outlives its server. A synchronous flag is what makes
413
+ * the check reliable — anything awaited leaves the same window open.
414
+ */
415
+ private stopping = false;
416
+
417
+ /**
418
+ * Live `subscriptions/listen` streams.
419
+ *
420
+ * Initialized unconditionally in startHttp(); null before the server starts
421
+ * or in stdio mode.
422
+ */
423
+ private subscriptions: SubscriptionRegistry | null = null;
424
+
425
+ /**
426
+ * Imported HMAC key for sealing `requestState`, or `null` when the deployment
427
+ * configured none.
428
+ *
429
+ * Resolved lazily on first use rather than in the constructor, because
430
+ * `importStateKey` is async and a constructor cannot await.
431
+ */
432
+ /**
433
+ * In-flight or resolved key import.
434
+ *
435
+ * A Promise, not a value plus a loaded flag: the flag was set before the await,
436
+ * so a second request arriving during the import saw "loaded" with the key
437
+ * still null, received an UNSIGNED requestState, and could then submit raw
438
+ * inputResponses past the verification guard. Memoising the Promise makes every
439
+ * caller await the same import.
440
+ */
441
+ private mrtrKeyPromise: Promise<CryptoKey | null> | null = null;
442
+
443
+ /**
444
+ * Validated `ttlMs`. The spec requires servers to provide a value `>= 0`, and
445
+ * an integer — clients are told to ignore a negative one, which would make a
446
+ * misconfiguration silently do nothing instead of failing.
447
+ *
448
+ * Resolved once at construction: a per-response check would pay for the same
449
+ * validation on every list call, and a bad value is a deployment error that
450
+ * should surface at startup (AX: fast fail early).
451
+ */
452
+ private readonly cacheTtlMs: number;
253
453
  private resources = new Map<string, RegisteredResourceInfo>();
254
454
  private options: McpAppOptions;
255
455
  private started = false;
@@ -267,28 +467,52 @@ export class McpApp {
267
467
  // Observability
268
468
  private serverMetrics = new ServerMetrics();
269
469
 
270
- // Streamable HTTP session management
271
- private sessions = new Map<
272
- string,
273
- { createdAt: number; lastActivity: number }
274
- >();
275
- private sseClients = new Map<string, SSEClient[]>(); // sessionId -> clients
276
- private sessionCleanupTimer: ReturnType<typeof setInterval> | null = null;
277
- private static readonly SESSION_TTL_MS = 30 * 60 * 1000; // 30 minutes
278
- private static readonly SESSION_CLEANUP_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
279
- private static readonly SESSION_GRACE_PERIOD_MS = 60 * 1000; // 60s grace for in-flight requests
280
- private static readonly MAX_SESSIONS = 10_000;
281
-
282
- // Per-IP rate limiter for initialize requests (anti-session-exhaustion)
283
- private initRateLimiter = new RateLimiter({
284
- maxRequests: 10,
285
- windowMs: 60_000,
286
- });
287
-
288
470
  constructor(options: McpAppOptions) {
289
471
  this.options = options;
290
472
  this.name = options.name;
291
473
 
474
+ // enableSampling / samplingClient are no-ops since 0.24.0 (SamplingBridge
475
+ // was removed with MCP 2026-07-28). Warn loudly so migrating consumers
476
+ // know immediately rather than discovering it silently in production.
477
+ if (options.enableSampling || options.samplingClient) {
478
+ (options.logger ?? console.error)(
479
+ "[McpApp] WARNING: enableSampling and samplingClient have no effect " +
480
+ "as of 0.24.0 — the SamplingBridge was removed with MCP 2026-07-28. " +
481
+ "Remove these options from your McpApp constructor call.",
482
+ );
483
+ }
484
+
485
+ const ttlMs = options.cache?.ttlMs ?? 0;
486
+ if (!Number.isInteger(ttlMs) || ttlMs < 0) {
487
+ throw new Error(
488
+ `[McpApp] cache.ttlMs must be a non-negative integer (got ${ttlMs}). ` +
489
+ "The spec requires servers to provide ttlMs >= 0, and clients are told " +
490
+ "to ignore a negative value — so a bad one would silently disable " +
491
+ "caching instead of failing.",
492
+ );
493
+ }
494
+ this.cacheTtlMs = ttlMs;
495
+
496
+ this.taskStore = options.extensions?.[TASKS_EXTENSION_ID] !== undefined
497
+ ? new TaskStore({
498
+ onNotification: (task) => this.onTaskChanged(task),
499
+ unrefTimer: (id) => unrefTimer(id as unknown as number),
500
+ })
501
+ : null;
502
+
503
+ // Validate the shape of the MRTR key here rather than on first use. The
504
+ // import itself is async so it stays lazy, but a typo in a 64-hex-character
505
+ // secret should surface at boot, not on the first request that needs it —
506
+ // by which point it is a runtime failure in production traffic.
507
+ const mrtrKey = options.mrtr?.signingKey;
508
+ if (mrtrKey !== undefined && !/^[0-9a-f]{64}$/.test(mrtrKey)) {
509
+ throw new Error(
510
+ "[McpApp] mrtr.signingKey must be 64 lowercase hex characters (32 bytes). " +
511
+ "Generate one with: crypto.getRandomValues(new Uint8Array(32)) rendered as hex, " +
512
+ "or the exported generateStateKey() + exportStateKey() helpers.",
513
+ );
514
+ }
515
+
292
516
  // Create SDK MCP server
293
517
  this.mcpServer = new McpServer(
294
518
  {
@@ -323,14 +547,6 @@ export class McpApp {
323
547
  this.schemaValidator = new SchemaValidator();
324
548
  }
325
549
 
326
- // Optional sampling support
327
- if (options.enableSampling && options.samplingClient) {
328
- this.log(
329
- "[DEPRECATED] Sampling is deprecated (MCP 2026-07-28) and will be removed after 2027-07-28.",
330
- );
331
- this.samplingBridge = new SamplingBridge(options.samplingClient);
332
- }
333
-
334
550
  // Setup MCP protocol handlers
335
551
  this.setupHandlers();
336
552
 
@@ -355,7 +571,7 @@ export class McpApp {
355
571
  server.registerCapabilities({ resources: {} });
356
572
 
357
573
  // resources/list — returns currently registered resources
358
- server.setRequestHandler(ListResourcesRequestSchema, async () => {
574
+ server.setRequestHandler(ListResourcesRequestSchema, () => {
359
575
  return {
360
576
  resources: Array.from(this.resources.values()).map((r) => ({
361
577
  uri: r.resource.uri,
@@ -454,6 +670,13 @@ export class McpApp {
454
670
  throw new Error(`No handler provided for tool: ${tool.name}`);
455
671
  }
456
672
 
673
+ // Validate annotations BEFORE inserting: a throw must not leave the tool
674
+ // half-registered. Registration is the right place to fail — a conforming
675
+ // client drops the whole tool from `tools/list` over a malformed
676
+ // annotation, so a typo would otherwise surface as a tool that silently
677
+ // does not exist (AX: fast fail early).
678
+ this.indexMirroredParams(tool);
679
+
457
680
  this.tools.set(tool.name, {
458
681
  ...tool,
459
682
  handler,
@@ -474,6 +697,35 @@ export class McpApp {
474
697
  * @param tool - Tool definition
475
698
  * @param handler - Tool handler function
476
699
  */
700
+ /**
701
+ * Validate and index a tool's `x-mcp-header` annotations (spec 2026-07-28).
702
+ *
703
+ * Every registration path must go through here. Wiring it into `registerTools`
704
+ * alone was a real bypass: a tool registered via `registerTool` or
705
+ * `registerToolLive` carried annotations that clients would mirror into
706
+ * `Mcp-Param-*` headers, while the server never required or checked them.
707
+ *
708
+ * Throws *before* the caller inserts the tool, so a rejected definition cannot
709
+ * leave a half-registered tool behind.
710
+ */
711
+ private indexMirroredParams(tool: MCPTool): void {
712
+ const invalid: string[] = [];
713
+ const mirrored = collectMirroredParams(
714
+ tool.inputSchema,
715
+ (reason) => invalid.push(reason),
716
+ );
717
+ if (invalid.length > 0) {
718
+ throw new Error(
719
+ `[McpApp] Tool "${tool.name}" has invalid x-mcp-header annotations:\n` +
720
+ invalid.map((r) => ` - ${r}`).join("\n"),
721
+ );
722
+ }
723
+ // Replace wholesale: re-registering a tool without annotations must clear
724
+ // whatever a previous definition left behind.
725
+ if (mirrored.length > 0) this.mirroredParams.set(tool.name, mirrored);
726
+ else this.mirroredParams.delete(tool.name);
727
+ }
728
+
477
729
  registerTool(tool: MCPTool, handler: ToolHandler): void {
478
730
  if (this.started) {
479
731
  throw new Error(
@@ -481,6 +733,7 @@ export class McpApp {
481
733
  "Call registerTool() before start() or startHttp().",
482
734
  );
483
735
  }
736
+ this.indexMirroredParams(tool);
484
737
  this.tools.set(tool.name, {
485
738
  ...tool,
486
739
  handler,
@@ -507,6 +760,7 @@ export class McpApp {
507
760
  * @param handler - Tool handler function
508
761
  */
509
762
  registerToolLive(tool: MCPTool, handler: ToolHandler): void {
763
+ this.indexMirroredParams(tool);
510
764
  this.tools.set(tool.name, {
511
765
  ...tool,
512
766
  handler,
@@ -554,6 +808,9 @@ export class McpApp {
554
808
  */
555
809
  unregisterTool(toolName: string): boolean {
556
810
  const deleted = this.tools.delete(toolName);
811
+ // Stale mirror metadata would make the server demand `Mcp-Param-*` headers
812
+ // for a tool that no longer exists.
813
+ this.mirroredParams.delete(toolName);
557
814
  if (deleted) {
558
815
  this.log(
559
816
  `Unregistered tool: ${toolName} (remaining: ${this.tools.size})`,
@@ -658,6 +915,13 @@ export class McpApp {
658
915
  ...(ctx.clientCapabilities !== undefined
659
916
  ? { clientCapabilities: ctx.clientCapabilities }
660
917
  : {}),
918
+ ...(ctx.logLevel !== undefined ? { logLevel: ctx.logLevel } : {}),
919
+ ...(ctx.inputResponses !== undefined
920
+ ? { inputResponses: ctx.inputResponses }
921
+ : {}),
922
+ ...(ctx.retryVerified !== undefined
923
+ ? { retryVerified: ctx.retryVerified }
924
+ : {}),
661
925
  }));
662
926
  });
663
927
  }
@@ -679,6 +943,10 @@ export class McpApp {
679
943
  sessionId?: string,
680
944
  preVerifiedAuthInfo?: AuthInfo,
681
945
  clientMeta?: StatelessClientMeta,
946
+ mrtr?: {
947
+ inputResponses?: Record<string, unknown>;
948
+ retryVerified?: boolean;
949
+ },
682
950
  ): Promise<MiddlewareResult> {
683
951
  if (!this.middlewareRunner) {
684
952
  throw new Error(
@@ -701,6 +969,15 @@ export class McpApp {
701
969
  ...(clientMeta?.clientCapabilities !== undefined
702
970
  ? { clientCapabilities: clientMeta.clientCapabilities }
703
971
  : {}),
972
+ ...(clientMeta?.logLevel !== undefined
973
+ ? { logLevel: clientMeta.logLevel }
974
+ : {}),
975
+ ...(mrtr?.inputResponses !== undefined
976
+ ? { inputResponses: mrtr.inputResponses }
977
+ : {}),
978
+ ...(mrtr?.retryVerified !== undefined
979
+ ? { retryVerified: mrtr.retryVerified }
980
+ : {}),
704
981
  };
705
982
 
706
983
  // OTel span + metrics
@@ -716,8 +993,6 @@ export class McpApp {
716
993
  this.serverMetrics.setGauges({
717
994
  activeRequests: queueMetrics.inFlight,
718
995
  queuedRequests: queueMetrics.queued,
719
- activeSessions: this.sessions.size,
720
- sseClients: this.getSSEClientCount(),
721
996
  rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
722
997
  });
723
998
 
@@ -985,10 +1260,19 @@ export class McpApp {
985
1260
  * Start the MCP server with stdio transport
986
1261
  */
987
1262
  async start(): Promise<void> {
1263
+ // Guard FIRST. Resetting before the guard meant a concurrent start() during
1264
+ // stop() cleared `stopping` and rebuilt the store on its way to failing with
1265
+ // "already started" — after which a held request produced a live task on a
1266
+ // stopped server. `startHttp()` had the order right; this did not.
988
1267
  if (this.started) {
989
1268
  throw new Error("Server already started");
990
1269
  }
991
1270
 
1271
+ // Same reset as the HTTP path. Without it a stdio server that had been stopped
1272
+ // kept `stopping` set and its store disposed, so it refused every task for the
1273
+ // rest of its life — with nothing to say why.
1274
+ this.prepareForStart();
1275
+
992
1276
  // Build middleware pipeline before connecting transport
993
1277
  this.buildPipeline();
994
1278
 
@@ -1015,67 +1299,52 @@ export class McpApp {
1015
1299
  }
1016
1300
 
1017
1301
  /**
1018
- * Clean up expired sessions to prevent memory leaks.
1019
- * Removes sessions that haven't had activity within SESSION_TTL_MS.
1302
+ * Restore the invariants a running server relies on.
1303
+ *
1304
+ * Called by both transports' start paths. `stop()` disposes the task store and
1305
+ * leaves it disposed — rebuilding it mid-teardown is what let an in-flight call
1306
+ * spawn into a store nobody would drain — so coming back up is where a live one
1307
+ * is created.
1020
1308
  */
1021
- private cleanupSessions(): void {
1022
- const now = Date.now();
1023
- const ttlWithGrace = McpApp.SESSION_TTL_MS +
1024
- McpApp.SESSION_GRACE_PERIOD_MS;
1025
- let cleaned = 0;
1026
- for (const [sessionId, session] of this.sessions) {
1027
- if (now - session.lastActivity > ttlWithGrace) {
1028
- this.sessions.delete(sessionId);
1029
- // Also clean up SSE clients for this session
1030
- const clients = this.sseClients.get(sessionId);
1031
- if (clients) {
1032
- for (const client of clients) {
1033
- try {
1034
- client.controller.close();
1035
- } catch { /* already closed */ }
1036
- }
1037
- this.sseClients.delete(sessionId);
1038
- }
1039
- cleaned++;
1040
- }
1041
- }
1042
- if (cleaned > 0) {
1043
- this.serverMetrics.recordSessionExpired(cleaned);
1044
- this.log(
1045
- `Session cleanup: removed ${cleaned} expired sessions (${this.sessions.size} remaining)`,
1046
- );
1309
+ private prepareForStart(): void {
1310
+ this.stopping = false;
1311
+ if (
1312
+ this.options.extensions?.[TASKS_EXTENSION_ID] !== undefined &&
1313
+ (this.taskStore === null || this.taskStore.isDisposed)
1314
+ ) {
1315
+ this.taskStore = new TaskStore({
1316
+ onNotification: (task) => this.onTaskChanged(task),
1317
+ unrefTimer: (timerId) => unrefTimer(timerId as unknown as number),
1318
+ });
1047
1319
  }
1048
1320
  }
1049
1321
 
1050
- /**
1051
- * Stop the server gracefully
1052
- */
1053
1322
  async stop(): Promise<void> {
1054
- if (!this.started) {
1055
- return;
1056
- }
1057
-
1058
- // Stop session cleanup timer
1059
- if (this.sessionCleanupTimer) {
1060
- clearInterval(this.sessionCleanupTimer);
1061
- this.sessionCleanupTimer = null;
1323
+ // Synchronous, before any await: a handler settling during shutdown must see
1324
+ // this immediately or it can still spawn a task.
1325
+ this.stopping = true;
1326
+
1327
+ // Release the subsystems whose timers exist from construction, BEFORE the
1328
+ // `started` guard: they are created in the constructor, so a server that
1329
+ // failed during startup still has them armed, and returning early left them
1330
+ // running with no way to reach them again.
1331
+ //
1332
+ // Disposed and left disposed — NOT replaced. Replacing here opened a window
1333
+ // where an in-flight call could spawn into a fresh store while the server was
1334
+ // stopping, producing a task that outlived its server. `startHttp()` builds a
1335
+ // new store instead, which keeps "a started server has a live store" true
1336
+ // without inventing one mid-teardown.
1337
+ if (this.taskStore) {
1338
+ this.taskStore.drain();
1339
+ this.taskStore.dispose();
1062
1340
  }
1063
-
1064
- // Cancel pending sampling requests
1065
- if (this.samplingBridge) {
1066
- this.samplingBridge.cancelAll();
1341
+ if (this.subscriptions) {
1342
+ this.subscriptions.shutdown();
1343
+ this.subscriptions = null;
1067
1344
  }
1068
1345
 
1069
- // Close all SSE clients BEFORE shutting down HTTP server.
1070
- // Deno.serve().shutdown() waits for all connections to drain,
1071
- // so long-lived SSE connections must be closed first to avoid blocking.
1072
- for (const [sessionId, clients] of this.sseClients) {
1073
- for (const client of clients) {
1074
- try {
1075
- client.controller.close();
1076
- } catch { /* already closed */ }
1077
- }
1078
- this.sseClients.delete(sessionId);
1346
+ if (!this.started) {
1347
+ return;
1079
1348
  }
1080
1349
 
1081
1350
  // Stop HTTP server if running
@@ -1160,6 +1429,18 @@ export class McpApp {
1160
1429
  this.buildPipeline();
1161
1430
 
1162
1431
  const hostname = options.hostname ?? "0.0.0.0";
1432
+ this.prepareForStart();
1433
+
1434
+ if (this.subscriptions === null) {
1435
+ this.subscriptions = new SubscriptionRegistry({
1436
+ serverInfo: { name: this.options.name, version: this.options.version },
1437
+ });
1438
+ this.subscriptions.startKeepAlive(
1439
+ setInterval,
1440
+ (id) => unrefTimer(id as unknown as number),
1441
+ );
1442
+ }
1443
+
1163
1444
  const enableCors = options.cors ?? true;
1164
1445
  const corsOrigins = options.corsOrigins ?? "*";
1165
1446
  const maxBodyBytes = options.maxBodyBytes === null
@@ -1196,13 +1477,26 @@ export class McpApp {
1196
1477
  "Content-Type",
1197
1478
  "Accept",
1198
1479
  "Authorization",
1199
- "mcp-session-id",
1200
1480
  "mcp-protocol-version",
1201
- "last-event-id",
1481
+ // Spec 2026-07-28 request-metadata headers. Omitting them broke
1482
+ // browser clients outright: the preflight rejects the actual request
1483
+ // before the server ever sees it, so a conforming client could not
1484
+ // send the headers the server now requires.
1485
+ "mcp-method",
1486
+ "mcp-name",
1487
+ // `Mcp-Param-*` names are defined by the tools themselves, so the
1488
+ // allowlist is derived from the registered annotations rather than
1489
+ // opened to `*` — which would also widen it for every other header.
1490
+ //
1491
+ // Known limitation: a tool registered via `registerToolLive` AFTER
1492
+ // startHttp() is not reflected here. Register annotated tools before
1493
+ // starting, or widen `corsOrigins`/headers deliberately.
1494
+ ...[...this.mirroredParams.values()]
1495
+ .flat()
1496
+ .map((param) => `mcp-param-${param.headerName.toLowerCase()}`),
1202
1497
  ],
1203
1498
  exposeHeaders: [
1204
1499
  "Content-Length",
1205
- "mcp-session-id",
1206
1500
  "mcp-protocol-version",
1207
1501
  ],
1208
1502
  maxAge: 600,
@@ -1228,8 +1522,6 @@ export class McpApp {
1228
1522
  this.serverMetrics.setGauges({
1229
1523
  activeRequests: qm.inFlight,
1230
1524
  queuedRequests: qm.queued,
1231
- activeSessions: this.sessions.size,
1232
- sseClients: this.getSSEClientCount(),
1233
1525
  rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
1234
1526
  });
1235
1527
  return new Response(this.serverMetrics.toPrometheusFormat(), {
@@ -1335,20 +1627,6 @@ export class McpApp {
1335
1627
  return { allowed: true, retryAfterMs: 0 };
1336
1628
  };
1337
1629
 
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
1630
  // Custom routes (registered before MCP catch-all)
1353
1631
  if (options.customRoutes) {
1354
1632
  for (const route of options.customRoutes) {
@@ -1356,105 +1634,18 @@ export class McpApp {
1356
1634
  }
1357
1635
  }
1358
1636
 
1359
- // MCP endpoint - GET opens SSE stream for server→client messages (Streamable HTTP spec)
1360
- // deno-lint-ignore no-explicit-any
1361
- const handleMcpGet = async (c: any) => {
1362
- // Track A: stateless V2 — SSE channel not applicable (Track B replaces it)
1363
- if (this.options.transport === "stateless") {
1364
- return c.text("Method Not Allowed", 405);
1365
- }
1366
-
1367
- const accept = c.req.header("accept") ?? "";
1368
- const sessionId = c.req.header("mcp-session-id");
1369
- const lastEventId = c.req.header("last-event-id");
1370
-
1371
- const rateLimit = await checkHttpRateLimit(c.req.raw, sessionId);
1372
- if (!rateLimit.allowed) {
1373
- const retryAfter = Math.max(
1374
- 1,
1375
- Math.ceil(rateLimit.retryAfterMs / 1000),
1376
- );
1377
- return new Response(
1378
- `Rate limit exceeded. Retry after ${retryAfter}s`,
1379
- {
1380
- status: 429,
1381
- headers: { "Retry-After": retryAfter.toString() },
1382
- },
1383
- );
1384
- }
1385
-
1386
- // Check if client accepts SSE
1387
- if (!accept.includes("text/event-stream")) {
1388
- return c.text("Method Not Allowed", 405);
1389
- }
1390
-
1391
- // Auth gate: SSE connections require valid token when auth is configured
1392
- const sseAuthResult = await verifyHttpAuth(c.req.raw);
1393
- if ("denied" in sseAuthResult) return sseAuthResult.denied;
1394
-
1395
- // Validate session if provided
1396
- if (sessionId && !this.sessions.has(sessionId)) {
1397
- return c.text("Session not found", 404);
1398
- }
1399
-
1400
- // Create SSE stream
1401
- const encoder = new TextEncoder();
1402
- let sseClient: SSEClient | null = null;
1403
-
1404
- const stream = new ReadableStream<Uint8Array>({
1405
- start: (controller) => {
1406
- const clientSessionId = sessionId ?? "anonymous";
1407
- const parsedEventId = lastEventId ? parseInt(lastEventId, 10) : 0;
1408
- sseClient = {
1409
- sessionId: clientSessionId,
1410
- controller,
1411
- createdAt: Date.now(),
1412
- lastEventId: Number.isNaN(parsedEventId) ? 0 : parsedEventId,
1413
- };
1414
-
1415
- // Register client
1416
- if (!this.sseClients.has(clientSessionId)) {
1417
- this.sseClients.set(clientSessionId, []);
1418
- }
1419
- this.sseClients.get(clientSessionId)!.push(sseClient);
1420
-
1421
- this.log(`SSE client connected (session: ${clientSessionId})`);
1422
-
1423
- // Send initial comment to establish connection
1424
- controller.enqueue(encoder.encode(": connected\n\n"));
1425
- },
1426
- cancel: () => {
1427
- // Remove client on disconnect
1428
- if (sseClient) {
1429
- const clients = this.sseClients.get(sseClient.sessionId);
1430
- if (clients) {
1431
- const idx = clients.indexOf(sseClient);
1432
- if (idx !== -1) clients.splice(idx, 1);
1433
- if (clients.length === 0) {
1434
- this.sseClients.delete(sseClient.sessionId);
1435
- }
1436
- }
1437
- this.log(
1438
- `SSE client disconnected (session: ${sseClient.sessionId})`,
1439
- );
1440
- }
1441
- },
1442
- });
1443
-
1444
- return new Response(stream, {
1445
- headers: {
1446
- "Content-Type": "text/event-stream",
1447
- "Cache-Control": "no-cache",
1448
- "Connection": "keep-alive",
1449
- ...(sessionId ? { "Mcp-Session-Id": sessionId } : {}),
1450
- },
1451
- });
1452
- };
1453
-
1454
- // deno-lint-ignore no-explicit-any
1455
- app.get("/mcp", handleMcpGet as any);
1637
+ // Legacy verbs from 2025-03-26..2025-11-25: GET opened a standalone SSE
1638
+ // stream, DELETE terminated a session. Neither exists in this revision, and
1639
+ // the spec says a server supporting only this revision SHOULD answer both
1640
+ // with 405 — not 404, which an older client would read as "no MCP endpoint
1641
+ // here" and use to fall back to the deprecated HTTP+SSE transport.
1642
+ // Use subscriptions/listen for server-initiated notifications.
1456
1643
  // deno-lint-ignore no-explicit-any
1457
- app.get("/", handleMcpGet as any);
1644
+ const methodNotAllowed = (c: any) => c.text("Method Not Allowed", 405);
1645
+ app.get("/mcp", methodNotAllowed);
1646
+ app.get("/", methodNotAllowed);
1647
+ app.delete("/mcp", methodNotAllowed);
1648
+ app.delete("/", methodNotAllowed);
1458
1649
 
1459
1650
  // MCP endpoint - POST handles JSON-RPC
1460
1651
  const handleMcpPost = async (
@@ -1471,23 +1662,16 @@ export class McpApp {
1471
1662
  ) => {
1472
1663
  let requestId: string | number | null = null;
1473
1664
  try {
1474
- // Track A: in stateless mode, ignore Mcp-Session-Id so it cannot be used
1475
- // as a rate-limit key (session bypass attack surface removed).
1476
- const reqSessionId = this.options.transport === "stateless"
1477
- ? undefined
1478
- : c.req.header("mcp-session-id");
1479
- // Track A: strip mcp-session-id from headers passed to rate-limit context
1480
- // so a keyExtractor cannot use rotating session IDs to bypass IP-level limits.
1481
- const rlHeaders = this.options.transport === "stateless"
1482
- ? (() => {
1483
- const h = new Headers(c.req.raw.headers);
1484
- h.delete("mcp-session-id");
1485
- return h;
1486
- })()
1487
- : undefined;
1665
+ // Strip mcp-session-id from headers passed to rate-limit context
1666
+ // so a keyExtractor cannot use session IDs to bypass IP-level limits.
1667
+ const rlHeaders = (() => {
1668
+ const h = new Headers(c.req.raw.headers);
1669
+ h.delete("mcp-session-id");
1670
+ return h;
1671
+ })();
1488
1672
  const rateLimit = await checkHttpRateLimit(
1489
1673
  c.req.raw,
1490
- reqSessionId,
1674
+ undefined,
1491
1675
  rlHeaders,
1492
1676
  );
1493
1677
  if (!rateLimit.allowed) {
@@ -1552,94 +1736,196 @@ export class McpApp {
1552
1736
  httpAuthInfo = authResult.authInfo;
1553
1737
  }
1554
1738
 
1555
- // Track A: per-request protocolVersion validation in stateless mode.
1739
+ // The `MCP-Protocol-Version` header is REQUIRED on every POST, and its
1740
+ // absence is a header-validation failure — not a malformed body. The
1741
+ // spec is explicit: "Validation failure conditions include: A required
1742
+ // standard header (MCP-Protocol-Version, Mcp-Method, Mcp-Name) is
1743
+ // missing", answered with 400 + -32020 (HeaderMismatch).
1744
+ //
1745
+ // This has to run BEFORE the `_meta` version check below, because a
1746
+ // legacy client sends neither and would otherwise get -32602 for a
1747
+ // missing body field when the primary violation is the missing header.
1748
+ // A client reading -32602 looks for the wrong fix.
1749
+ //
1750
+ // Notifications are exempt: the revision leaves header requirements for
1751
+ // notification POSTs undefined, so demanding one there invents a rule.
1752
+ if (
1753
+ id !== undefined && c.req.header("MCP-Protocol-Version") === undefined
1754
+ ) {
1755
+ return jsonRpcResponse(
1756
+ {
1757
+ jsonrpc: "2.0",
1758
+ id,
1759
+ error: {
1760
+ code: MCP_HEADER_MISMATCH,
1761
+ message:
1762
+ "Missing required header 'MCP-Protocol-Version'. It must be present and match params._meta['io.modelcontextprotocol/protocolVersion'].",
1763
+ data: {
1764
+ problem: "missing_header",
1765
+ header: "MCP-Protocol-Version",
1766
+ recovery:
1767
+ "Send MCP-Protocol-Version: 2026-07-28 and the matching _meta field.",
1768
+ },
1769
+ },
1770
+ },
1771
+ 400,
1772
+ { "MCP-Protocol-Version": SPEC_2026_07_28 },
1773
+ );
1774
+ }
1775
+
1776
+ // Per-request protocolVersion validation (spec 2026-07-28).
1556
1777
  // Must run BEFORE any method dispatch so every call (not just initialize)
1557
1778
  // is validated. Sets MCP-Protocol-Version header on all subsequent responses
1558
1779
  // via Hono's c.header() accumulation.
1559
1780
  // Key location: params._meta[STATELESS_PROTO_KEY] (SEP-2575 Final).
1560
- // Tolerant mode: MCP-Protocol-Version may be absent for backward compatibility;
1561
- // when present it must match the _meta version.
1562
- let statelessVersion: string | undefined;
1563
- if (this.options.transport === "stateless") {
1564
- const clientVersion = isRecord(params) && isRecord(params["_meta"])
1565
- ? params["_meta"][STATELESS_PROTO_KEY]
1566
- : undefined;
1781
+ const clientVersion = isRecord(params) && isRecord(params["_meta"])
1782
+ ? params["_meta"][STATELESS_PROTO_KEY]
1783
+ : undefined;
1567
1784
 
1568
- if (typeof clientVersion !== "string") {
1569
- // Header uses fallback version — no negotiated version available yet
1570
- return jsonRpcResponse(
1571
- {
1572
- jsonrpc: "2.0",
1573
- id,
1574
- error: {
1575
- code: JSONRPC_INVALID_PARAMS,
1576
- message: `Missing required field '${STATELESS_PROTO_KEY}'`,
1785
+ // `clientCapabilities` is a REQUIRED per-request `_meta` field in the
1786
+ // final spec (`clientInfo` is not — it is only SHOULD). A request
1787
+ // missing a required field is malformed: -32602 + HTTP 400.
1788
+ //
1789
+ // Checked after the version so a client on an unsupported revision
1790
+ // gets the clearer version error first.
1791
+ // Must be an OBJECT, not merely present. `!== undefined` accepted
1792
+ // `null`, a scalar or an array, which then reached the handler as a
1793
+ // supposed ClientCapabilities and failed later as -32603 — an internal
1794
+ // error for what is plainly a malformed request.
1795
+ const capabilitiesValid = isRecord(params) &&
1796
+ isRecord(params["_meta"]) &&
1797
+ isRecord(params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY]);
1798
+
1799
+ if (typeof clientVersion !== "string") {
1800
+ // Header uses fallback version — no negotiated version available yet
1801
+ return jsonRpcResponse(
1802
+ {
1803
+ jsonrpc: "2.0",
1804
+ id,
1805
+ error: {
1806
+ code: JSONRPC_INVALID_PARAMS,
1807
+ message: `Missing required field '${STATELESS_PROTO_KEY}'`,
1808
+ },
1809
+ },
1810
+ 400,
1811
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1812
+ );
1813
+ }
1814
+
1815
+ if (!STATELESS_SUPPORTED_VERSIONS.includes(clientVersion)) {
1816
+ // AX: data carries machine-readable supported/requested for agent recovery
1817
+ return jsonRpcResponse(
1818
+ {
1819
+ jsonrpc: "2.0",
1820
+ id,
1821
+ error: {
1822
+ code: MCP_UNSUPPORTED_PROTOCOL_VERSION,
1823
+ message: `Unsupported protocolVersion: "${clientVersion}"`,
1824
+ data: {
1825
+ supported: [...STATELESS_SUPPORTED_VERSIONS],
1826
+ requested: clientVersion,
1577
1827
  },
1578
1828
  },
1579
- 400,
1580
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1581
- );
1582
- }
1829
+ },
1830
+ 400,
1831
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1832
+ );
1833
+ }
1583
1834
 
1584
- if (!STATELESS_SUPPORTED_VERSIONS.includes(clientVersion)) {
1585
- // AX: data carries machine-readable supported/requested for agent recovery
1586
- return jsonRpcResponse(
1587
- {
1588
- jsonrpc: "2.0",
1589
- id,
1590
- error: {
1591
- code: MCP_UNSUPPORTED_PROTOCOL_VERSION,
1592
- message: `Unsupported protocolVersion: "${clientVersion}"`,
1593
- data: {
1594
- supported: [...STATELESS_SUPPORTED_VERSIONS],
1595
- requested: clientVersion,
1596
- },
1835
+ if (!capabilitiesValid) {
1836
+ return jsonRpcResponse(
1837
+ {
1838
+ jsonrpc: "2.0",
1839
+ id,
1840
+ error: {
1841
+ code: JSONRPC_INVALID_PARAMS,
1842
+ message:
1843
+ `Missing or malformed field '${STATELESS_CLIENT_CAPABILITIES_KEY}' in params._meta: expected an object`,
1844
+ data: {
1845
+ problem: "missing_field",
1846
+ bodyField:
1847
+ `params._meta['${STATELESS_CLIENT_CAPABILITIES_KEY}']`,
1848
+ recovery:
1849
+ "Send a ClientCapabilities object; `{}` is valid and means no capabilities declared.",
1597
1850
  },
1598
1851
  },
1599
- 400,
1600
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1601
- );
1602
- }
1852
+ },
1853
+ 400,
1854
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1855
+ );
1856
+ }
1603
1857
 
1604
- const headerVersion = c.req.header("MCP-Protocol-Version");
1605
- if (
1606
- headerVersion !== undefined &&
1607
- headerVersion !== clientVersion
1608
- ) {
1858
+ // Track C: request-metadata headers (SEP-2243).
1859
+ //
1860
+ // Notifications are exempt: the revision explicitly leaves header
1861
+ // requirements for notification POSTs undefined, so a missing
1862
+ // `Mcp-Method` there is not a violation to invent.
1863
+ if (id !== undefined) {
1864
+ const validation = validateRequestHeaders({
1865
+ getHeader: (name) => c.req.header(name),
1866
+ method: typeof method === "string" ? method : "",
1867
+ params: isRecord(params) ? params : undefined,
1868
+ bodyProtocolVersion: clientVersion,
1869
+ mirroredParams: typeof params?.name === "string"
1870
+ ? this.mirroredParams.get(params.name)
1871
+ : undefined,
1872
+ });
1873
+ if (!validation.ok) {
1609
1874
  return jsonRpcResponse(
1610
1875
  {
1611
1876
  jsonrpc: "2.0",
1612
1877
  id,
1613
1878
  error: {
1614
- code: JSONRPC_INVALID_PARAMS,
1615
- message:
1616
- `MCP-Protocol-Version header "${headerVersion}" does not match _meta protocolVersion "${clientVersion}"`,
1879
+ code: MCP_HEADER_MISMATCH,
1880
+ message: validation.message,
1881
+ // AX: the caller has to fix the request, so what to fix
1882
+ // travels as data. `problem` is an enum to switch on,
1883
+ // `recovery` is one concrete action — neither requires
1884
+ // parsing the English message.
1885
+ data: validation.detail,
1617
1886
  },
1618
1887
  },
1619
1888
  400,
1620
1889
  { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1621
1890
  );
1622
1891
  }
1892
+ }
1893
+
1894
+ const statelessVersion: string = clientVersion;
1895
+ // Spec 2026-07-28: echo negotiated version in every response header.
1896
+ // c.header() accumulates headers — all subsequent c.json() calls inherit it.
1897
+ c.header("MCP-Protocol-Version", statelessVersion);
1623
1898
 
1624
- statelessVersion = clientVersion;
1625
- // Spec 2026-07-28: echo negotiated version in every response header.
1626
- // c.header() accumulates headers — all subsequent c.json() calls inherit it.
1627
- c.header("MCP-Protocol-Version", statelessVersion);
1899
+ if (method === "server/discover") {
1900
+ return c.json({
1901
+ jsonrpc: "2.0",
1902
+ id,
1903
+ result: this.stampResult(
1904
+ this.withCacheHints({
1905
+ supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
1906
+ capabilities: this.buildServerCapabilities(),
1907
+ serverInfo: {
1908
+ name: this.options.name,
1909
+ version: this.options.version,
1910
+ },
1911
+ ...(this.options.instructions
1912
+ ? { instructions: this.options.instructions }
1913
+ : {}),
1914
+ }, statelessVersion),
1915
+ statelessVersion,
1916
+ ),
1917
+ });
1628
1918
  }
1629
1919
 
1630
- if (
1631
- method === "server/discover" &&
1632
- this.options.transport === "stateless"
1633
- ) {
1920
+ // Initialize — respond without creating a session or emitting Mcp-Session-Id.
1921
+ // statelessVersion is guaranteed defined here (version check above returned early otherwise).
1922
+ if (method === "initialize") {
1634
1923
  return c.json({
1635
1924
  jsonrpc: "2.0",
1636
1925
  id,
1637
- result: {
1638
- supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
1639
- capabilities: {
1640
- tools: {},
1641
- resources: this.resources.size > 0 ? {} : undefined,
1642
- },
1926
+ result: this.stampResult({
1927
+ protocolVersion: statelessVersion,
1928
+ capabilities: this.buildServerCapabilities(),
1643
1929
  serverInfo: {
1644
1930
  name: this.options.name,
1645
1931
  version: this.options.version,
@@ -1647,120 +1933,43 @@ export class McpApp {
1647
1933
  ...(this.options.instructions
1648
1934
  ? { instructions: this.options.instructions }
1649
1935
  : {}),
1650
- },
1936
+ }, statelessVersion),
1651
1937
  });
1938
+ // Note: c.json() inherits MCP-Protocol-Version header set above.
1939
+ // No Mcp-Session-Id header emitted — stateless by design.
1652
1940
  }
1653
1941
 
1654
- // Initialize - create session and return session ID (now auth-verified)
1655
- if (method === "initialize") {
1656
- // Track A: stateless V2 — respond without creating a session or emitting Mcp-Session-Id.
1657
- // statelessVersion is guaranteed defined here (per-request block above returned early otherwise).
1658
- if (this.options.transport === "stateless") {
1659
- return c.json({
1660
- jsonrpc: "2.0",
1661
- id,
1662
- result: {
1663
- protocolVersion: statelessVersion as string,
1664
- capabilities: {
1665
- tools: {},
1666
- resources: this.resources.size > 0 ? {} : undefined,
1667
- },
1668
- serverInfo: {
1669
- name: this.options.name,
1670
- version: this.options.version,
1671
- },
1672
- ...(this.options.instructions
1673
- ? { instructions: this.options.instructions }
1674
- : {}),
1675
- },
1676
- });
1677
- // Note: c.json() inherits MCP-Protocol-Version header set above.
1678
- // No Mcp-Session-Id header emitted — stateless by design.
1679
- }
1680
-
1681
- // Per-IP rate limit on initialize to prevent session exhaustion attacks
1682
- const clientIp = getClientIpFromHeaders(c.req.raw.headers);
1683
- if (!this.initRateLimiter.checkLimit(clientIp)) {
1684
- return c.json({
1685
- jsonrpc: "2.0",
1686
- id,
1687
- error: {
1688
- code: -32000,
1689
- message: "Too many initialize requests. Try again later.",
1690
- },
1691
- }, 429);
1692
- }
1693
-
1694
- // Guard against session exhaustion
1695
- if (this.sessions.size >= McpApp.MAX_SESSIONS) {
1696
- this.cleanupSessions();
1697
- if (this.sessions.size >= McpApp.MAX_SESSIONS) {
1698
- return c.json({
1942
+ // Tools call (delegates to middleware pipeline, which handles auth internally)
1943
+ if (method === "tools/call") {
1944
+ // Dispatch by method rather than the truthiness of `name`. An empty
1945
+ // string can be represented faithfully by Mcp-Name, but it is not a
1946
+ // usable tool name and must be InvalidParams rather than an apparent
1947
+ // method that this server does not implement.
1948
+ const toolParams = isRecord(params) ? params : undefined;
1949
+ if (
1950
+ toolParams === undefined ||
1951
+ typeof toolParams["name"] !== "string" ||
1952
+ toolParams["name"].length === 0
1953
+ ) {
1954
+ return jsonRpcResponse(
1955
+ {
1699
1956
  jsonrpc: "2.0",
1700
1957
  id,
1701
- error: { code: -32000, message: "Too many active sessions" },
1702
- }, 503);
1703
- }
1704
- }
1705
- const sessionId = generateSessionId();
1706
- const now = Date.now();
1707
- this.sessions.set(sessionId, { createdAt: now, lastActivity: now });
1708
- this.serverMetrics.recordSessionCreated();
1709
-
1710
- this.log(`New session created: ${sessionId}`);
1711
-
1712
- return new Response(
1713
- JSON.stringify({
1714
- jsonrpc: "2.0",
1715
- id,
1716
- result: {
1717
- protocolVersion: "2025-06-18",
1718
- capabilities: {
1719
- tools: {},
1720
- resources: this.resources.size > 0 ? {} : undefined,
1721
- },
1722
- serverInfo: {
1723
- name: this.options.name,
1724
- version: this.options.version,
1958
+ error: {
1959
+ code: JSONRPC_INVALID_PARAMS,
1960
+ message:
1961
+ "tools/call requires a non-empty string 'name' parameter",
1725
1962
  },
1726
- ...(this.options.instructions
1727
- ? { instructions: this.options.instructions }
1728
- : {}),
1729
1963
  },
1730
- }),
1731
- {
1732
- headers: {
1733
- "Content-Type": "application/json",
1734
- "Mcp-Session-Id": sessionId,
1735
- },
1736
- },
1737
- );
1738
- }
1739
-
1740
- // Session validation: all methods after initialize must provide a valid session.
1741
- // Skipped in stateless V2 mode (Track A) — no session concept.
1742
- if (this.options.transport !== "stateless" && reqSessionId) {
1743
- const session = this.sessions.get(reqSessionId);
1744
- if (!session) {
1745
- return c.json({
1746
- jsonrpc: "2.0",
1747
- id,
1748
- error: { code: -32001, message: "Session not found or expired" },
1749
- }, 404);
1964
+ 400,
1965
+ );
1750
1966
  }
1751
- // Update last activity to prevent premature cleanup
1752
- session.lastActivity = Date.now();
1753
- }
1754
-
1755
- // 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>) || {};
1967
+ const toolName = toolParams["name"];
1968
+ const args = (toolParams["arguments"] as Record<string, unknown>) ||
1969
+ {};
1759
1970
  const statelessClientMeta:
1760
1971
  | StatelessClientMeta
1761
- | undefined = this.options.transport === "stateless" &&
1762
- isRecord(params) &&
1763
- isRecord(params["_meta"])
1972
+ | undefined = isRecord(params) && isRecord(params["_meta"])
1764
1973
  ? {
1765
1974
  clientInfo: params["_meta"][STATELESS_CLIENT_INFO_KEY] as
1766
1975
  | Implementation
@@ -1768,22 +1977,338 @@ export class McpApp {
1768
1977
  clientCapabilities: params["_meta"][
1769
1978
  STATELESS_CLIENT_CAPABILITIES_KEY
1770
1979
  ] as ClientCapabilities | undefined,
1980
+ logLevel: readLogLevel(params["_meta"]),
1771
1981
  }
1772
1982
  : undefined;
1773
1983
 
1984
+ // MRTR retry fields live in `params` directly — siblings of `_meta`,
1985
+ // not members of it, unlike every other per-request field. Reading them
1986
+ // from `_meta` yields a silent undefined even when the client sent them.
1987
+ //
1988
+ // MRTR is always enabled on 2026-07-28 (the only supported version).
1989
+ const mrtrEnabled = true;
1990
+
1991
+ // Digest of the arguments AS RECEIVED, taken before the middleware
1992
+ // pipeline runs. Re-deriving it at seal time would hash whatever the
1993
+ // pipeline left in `args` — validation coercion, defaults, redaction —
1994
+ // so a client replaying the request byte-for-byte would fail
1995
+ // `wrong_params` through no fault of its own.
1996
+ const ingressDigest = mrtrEnabled
1997
+ ? await paramsDigest({ arguments: args, name: toolName })
1998
+ : "";
1999
+ // A scalar or array `inputResponses` was silently dropped, so a client
2000
+ // sending the wrong shape saw its answers ignored and the same
2001
+ // InputRequiredResult come back, with nothing to indicate why.
2002
+ const rawResponses = mrtrEnabled && isRecord(params)
2003
+ ? params["inputResponses"]
2004
+ : undefined;
2005
+ if (rawResponses !== undefined && !isRecord(rawResponses)) {
2006
+ return jsonRpcResponse(
2007
+ {
2008
+ jsonrpc: "2.0",
2009
+ id,
2010
+ error: {
2011
+ code: JSONRPC_INVALID_PARAMS,
2012
+ message:
2013
+ "inputResponses must be an object keyed by the ids from inputRequests",
2014
+ data: {
2015
+ problem: "malformed_field",
2016
+ bodyField: "params.inputResponses",
2017
+ recovery:
2018
+ "Send an object whose keys match the inputRequests keys the server issued.",
2019
+ },
2020
+ },
2021
+ },
2022
+ 400,
2023
+ {
2024
+ "MCP-Protocol-Version": statelessVersion,
2025
+ },
2026
+ );
2027
+ }
2028
+ const echoedResponses = isRecord(rawResponses)
2029
+ ? rawResponses
2030
+ : undefined;
2031
+ const echoedState = mrtrEnabled && isRecord(params) &&
2032
+ typeof params["requestState"] === "string"
2033
+ ? params["requestState"]
2034
+ : undefined;
2035
+
2036
+ let retryVerified: boolean | undefined;
2037
+
2038
+ // A retry carrying answers but no token cannot be verified, and the
2039
+ // server always issues a token when it has a key. So this combination
2040
+ // is either a confused client or an attempt to inject answers past the
2041
+ // verification gate — refuse it rather than forwarding unverified
2042
+ // responses to the handler.
2043
+ // Resolved only when MRTR is actually in play. Resolving on every 2026
2044
+ // tools/call meant a transient key-import failure also broke ordinary
2045
+ // tools that never touch MRTR.
2046
+ const needsKey = mrtrEnabled &&
2047
+ (echoedResponses !== undefined || echoedState !== undefined);
2048
+ const guardKey = needsKey
2049
+ ? await this.getMrtrKeySafe(
2050
+ id,
2051
+ statelessVersion,
2052
+ )
2053
+ : { key: null as CryptoKey | null };
2054
+ if ("error" in guardKey) return guardKey.error;
2055
+ if (
2056
+ echoedResponses !== undefined && echoedState === undefined &&
2057
+ guardKey.key !== null
2058
+ ) {
2059
+ return jsonRpcResponse(
2060
+ {
2061
+ jsonrpc: "2.0",
2062
+ id,
2063
+ error: {
2064
+ code: JSONRPC_INVALID_PARAMS,
2065
+ message:
2066
+ "inputResponses supplied without the requestState issued with them",
2067
+ data: {
2068
+ problem: "missing_request_state",
2069
+ recovery:
2070
+ "Echo back the exact requestState string from the InputRequiredResult alongside inputResponses.",
2071
+ },
2072
+ },
2073
+ },
2074
+ 400,
2075
+ {
2076
+ "MCP-Protocol-Version": statelessVersion,
2077
+ },
2078
+ );
2079
+ }
2080
+
2081
+ if (echoedState !== undefined) {
2082
+ const key = guardKey.key;
2083
+ if (key === null) {
2084
+ // Unprotected mode: nothing to verify, and the handler is told so
2085
+ // rather than being handed a false assurance.
2086
+ retryVerified = false;
2087
+ } else {
2088
+ // On an authenticated server this binds the token to one user, so
2089
+ // a token minted for A cannot be spent by B. On an UNAUTHENTICATED
2090
+ // server every caller is "anonymous", and the binding protects
2091
+ // nothing — correctly so: without auth there is no user boundary to
2092
+ // cross, and any caller could invoke the tool directly anyway. The
2093
+ // method and argument bindings still apply in both cases.
2094
+ const principal = callerPrincipal(httpAuthInfo);
2095
+ if (principal === null) {
2096
+ return noPrincipalError(
2097
+ id,
2098
+ statelessVersion,
2099
+ );
2100
+ }
2101
+ const verdict = await verifyRequestState(echoedState, key, {
2102
+ principal,
2103
+ method: "tools/call",
2104
+ paramsDigest: ingressDigest,
2105
+ });
2106
+ if (!verdict.ok) {
2107
+ // Attacker-controlled input that failed its integrity or binding
2108
+ // checks. Rejected before the handler runs, and the reason is
2109
+ // returned so a legitimate client can recover (e.g. re-elicit
2110
+ // after an expiry) rather than guessing.
2111
+ return jsonRpcResponse(
2112
+ {
2113
+ jsonrpc: "2.0",
2114
+ id,
2115
+ error: {
2116
+ code: JSONRPC_INVALID_PARAMS,
2117
+ message: `Invalid requestState: ${verdict.reason}`,
2118
+ data: { reason: verdict.reason },
2119
+ },
2120
+ },
2121
+ 400,
2122
+ );
2123
+ }
2124
+ retryVerified = true;
2125
+ }
2126
+ }
2127
+
1774
2128
  try {
1775
2129
  const result = await this.executeToolCall(
1776
2130
  toolName,
1777
2131
  args,
1778
2132
  c.req.raw,
1779
- reqSessionId,
2133
+ undefined,
1780
2134
  httpAuthInfo,
1781
2135
  statelessClientMeta,
2136
+ {
2137
+ ...(echoedResponses !== undefined
2138
+ ? { inputResponses: echoedResponses }
2139
+ : {}),
2140
+ ...(retryVerified !== undefined ? { retryVerified } : {}),
2141
+ },
1782
2142
  );
2143
+ // MRTR: the handler is asking the client for input rather than
2144
+ // returning a result. Checked BEFORE the task branch and before
2145
+ // stampResult, which would overwrite resultType with "complete".
2146
+ if (
2147
+ mrtrEnabled && isRecord(result) &&
2148
+ result["resultType"] === "input_required"
2149
+ ) {
2150
+ const sealPrincipal = callerPrincipal(httpAuthInfo);
2151
+ if (sealPrincipal === null) {
2152
+ return noPrincipalError(
2153
+ id,
2154
+ statelessVersion,
2155
+ );
2156
+ }
2157
+ const built = await this.buildInputRequiredResult(
2158
+ result as unknown as InputRequiredSignal,
2159
+ {
2160
+ clientCapabilities: statelessClientMeta?.clientCapabilities,
2161
+ principal: sealPrincipal,
2162
+ method: "tools/call",
2163
+ paramsDigest: ingressDigest,
2164
+ },
2165
+ );
2166
+ if (!built.ok) {
2167
+ return jsonRpcResponse(
2168
+ {
2169
+ jsonrpc: "2.0",
2170
+ id,
2171
+ error: {
2172
+ code: built.code,
2173
+ message: built.message,
2174
+ ...(built.data !== undefined ? { data: built.data } : {}),
2175
+ },
2176
+ },
2177
+ // Status follows the code: an InternalError is a server fault
2178
+ // (500), a capability or shape problem is the caller's (400).
2179
+ // Flattening both to 400 told a client to fix a request that a
2180
+ // misconfigured signing key had broken — and the sibling ingress
2181
+ // path already answered 500 for exactly that.
2182
+ built.code === ErrorCode.InternalError ? 500 : 400,
2183
+ {
2184
+ "MCP-Protocol-Version": statelessVersion,
2185
+ },
2186
+ );
2187
+ }
2188
+ return c.json({ jsonrpc: "2.0", id, result: built.result });
2189
+ }
2190
+
2191
+ // Tasks extension: the handler asked for a task handle instead of
2192
+ // a synchronous result.
2193
+ if (isAsyncTaskDescriptor(result)) {
2194
+ const guard = this.requireTasksCapability(
2195
+ statelessClientMeta?.clientCapabilities,
2196
+ id,
2197
+ );
2198
+ if (guard) return guard;
2199
+
2200
+ // Owner binding: the spec requires an authorization check on every
2201
+ // task-related request, and a task id alone is only one line of
2202
+ // defence.
2203
+ if (this.stopping || this.taskStore === null) {
2204
+ return jsonRpcResponse(
2205
+ {
2206
+ jsonrpc: "2.0",
2207
+ id,
2208
+ error: {
2209
+ code: ErrorCode.InternalError,
2210
+ message:
2211
+ "Server is shutting down; no new tasks are accepted.",
2212
+ data: {
2213
+ problem: "server_stopping",
2214
+ recovery: "Retry against a running instance.",
2215
+ },
2216
+ },
2217
+ },
2218
+ 503,
2219
+ {
2220
+ "MCP-Protocol-Version": statelessVersion,
2221
+ },
2222
+ );
2223
+ }
2224
+ const ownerPrincipal = callerPrincipal(httpAuthInfo);
2225
+ if (ownerPrincipal === null) {
2226
+ return noPrincipalError(
2227
+ id,
2228
+ statelessVersion,
2229
+ );
2230
+ }
2231
+ const owner = await taskOwnerKeyFor(
2232
+ this.options,
2233
+ httpAuthInfo,
2234
+ c.req.raw,
2235
+ ownerPrincipal,
2236
+ );
2237
+ if (owner === null) {
2238
+ return noOwnerKeyError(
2239
+ id,
2240
+ statelessVersion,
2241
+ );
2242
+ }
2243
+ // Re-checked, and wrapped: the guard above sits before two awaits
2244
+ // (the principal lookup and the async owner hook), so shutdown can
2245
+ // begin in between. Without this, spawn()'s post-disposal throw
2246
+ // would escape to the POST-level catch and be reported as -32700
2247
+ // "Parse error".
2248
+ let task;
2249
+ try {
2250
+ task = this.taskStore.spawn(
2251
+ result,
2252
+ owner,
2253
+ // Same conversion the synchronous path uses, so a handler's
2254
+ // return value produces an identical result either way.
2255
+ (raw) => this.buildToolCallResult(toolName, raw),
2256
+ );
2257
+ } catch (spawnError) {
2258
+ // Narrowed to the actual shutdown condition. A blanket catch
2259
+ // reported a legitimate throw from the handler's own task setup as
2260
+ // "server is shutting down" — a diagnosis that sends the reader to
2261
+ // look at the wrong thing entirely, on a perfectly healthy server.
2262
+ if (this.stopping || this.taskStore.isDisposed) {
2263
+ return jsonRpcResponse(
2264
+ {
2265
+ jsonrpc: "2.0",
2266
+ id,
2267
+ error: {
2268
+ code: ErrorCode.InternalError,
2269
+ message:
2270
+ "Server is shutting down; no new tasks are accepted.",
2271
+ data: {
2272
+ problem: "server_stopping",
2273
+ recovery: "Retry against a running instance.",
2274
+ },
2275
+ },
2276
+ },
2277
+ 503,
2278
+ {
2279
+ "MCP-Protocol-Version": statelessVersion,
2280
+ },
2281
+ );
2282
+ }
2283
+ // A real failure: let the tool error path report it as such.
2284
+ throw spawnError;
2285
+ }
2286
+ return c.json({
2287
+ jsonrpc: "2.0",
2288
+ id,
2289
+ // NOT stampResult(): that writes resultType "complete", and a
2290
+ // CreateTaskResult carries "task". Its fields are flat on the
2291
+ // result, not nested under a `task` key.
2292
+ //
2293
+ // Note the asymmetry with tasks/get below, which DOES carry
2294
+ // "complete" — that is an ordinary RPC response which happens to
2295
+ // describe a task. The spec states this distinction three times;
2296
+ // conflating them is the likeliest mistake here.
2297
+ result: this.stampResult(
2298
+ { ...task },
2299
+ statelessVersion,
2300
+ "task",
2301
+ ),
2302
+ });
2303
+ }
2304
+
1783
2305
  return c.json({
1784
2306
  jsonrpc: "2.0",
1785
2307
  id,
1786
- result: this.buildToolCallResult(toolName, result),
2308
+ result: this.stampResult(
2309
+ this.buildToolCallResult(toolName, result),
2310
+ statelessVersion,
2311
+ ),
1787
2312
  });
1788
2313
  } catch (error) {
1789
2314
  // Handle AuthError with proper HTTP status codes
@@ -1811,7 +2336,13 @@ export class McpApp {
1811
2336
  return c.json({
1812
2337
  jsonrpc: "2.0",
1813
2338
  id,
1814
- result: isErrorResult,
2339
+ // An `isError: true` tool result is still a completed JSON-RPC
2340
+ // result, so it carries `resultType: "complete"`. Only MRTR
2341
+ // interim results (Track B) use `"input_required"`.
2342
+ result: this.stampResult(
2343
+ isErrorResult as Record<string, unknown>,
2344
+ statelessVersion,
2345
+ ),
1815
2346
  });
1816
2347
  } catch (rethrown) {
1817
2348
  this.log(
@@ -1848,7 +2379,13 @@ export class McpApp {
1848
2379
  return c.json({
1849
2380
  jsonrpc: "2.0",
1850
2381
  id,
1851
- result: { tools: this.buildToolListing() },
2382
+ result: this.stampResult(
2383
+ this.withCacheHints(
2384
+ { tools: this.buildToolListing() },
2385
+ statelessVersion,
2386
+ ),
2387
+ statelessVersion,
2388
+ ),
1852
2389
  });
1853
2390
  }
1854
2391
 
@@ -1857,82 +2394,450 @@ export class McpApp {
1857
2394
  return c.json({
1858
2395
  jsonrpc: "2.0",
1859
2396
  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
- },
2397
+ result: this.stampResult(
2398
+ this.withCacheHints({
2399
+ resources: Array.from(this.resources.values()).map((r) => ({
2400
+ uri: r.resource.uri,
2401
+ name: r.resource.name,
2402
+ description: r.resource.description,
2403
+ mimeType: r.resource.mimeType ?? MCP_APP_MIME_TYPE,
2404
+ })),
2405
+ }, statelessVersion),
2406
+ statelessVersion,
2407
+ ),
1868
2408
  });
1869
2409
  }
1870
2410
 
1871
2411
  // Resources read
1872
- if (method === "resources/read" && params?.uri) {
1873
- const uri = params.uri as string;
2412
+ if (method === "resources/read") {
2413
+ // Dispatch by method, not the truthiness of its routing parameter.
2414
+ // `uri: ""` has a valid empty Mcp-Name header representation, but it
2415
+ // is not a usable resource URI. Letting it skip this branch turned a
2416
+ // malformed resources/read into a misleading -32601 method-not-found.
2417
+ const uri = isRecord(params) && typeof params["uri"] === "string" &&
2418
+ params["uri"].length > 0
2419
+ ? params["uri"]
2420
+ : undefined;
2421
+ if (uri === undefined) {
2422
+ return jsonRpcResponse(
2423
+ {
2424
+ jsonrpc: "2.0",
2425
+ id,
2426
+ error: {
2427
+ code: JSONRPC_INVALID_PARAMS,
2428
+ message:
2429
+ "resources/read requires a non-empty string 'uri' parameter",
2430
+ },
2431
+ },
2432
+ 400,
2433
+ );
2434
+ }
1874
2435
  const resourceInfo = this.resources.get(uri);
1875
2436
 
1876
2437
  if (!resourceInfo) {
1877
2438
  return c.json({
1878
2439
  jsonrpc: "2.0",
1879
2440
  id,
1880
- error: { code: -32602, message: `Resource not found: ${uri}` },
2441
+ error: { code: -32602, message: `Resource not found: ${uri}` },
2442
+ });
2443
+ }
2444
+
2445
+ try {
2446
+ const content = await resourceInfo.handler(new URL(uri));
2447
+ const finalContent = this.applyResourceCsp(content);
2448
+ return c.json({
2449
+ jsonrpc: "2.0",
2450
+ id,
2451
+ result: this.stampResult(
2452
+ this.withCacheHints(
2453
+ { contents: [finalContent] },
2454
+ statelessVersion,
2455
+ {
2456
+ // resources/read is the only cacheable method an MRTR retry
2457
+ // can target, so it is the only one that needs this guard.
2458
+ isMrtrRetry: isRecord(params) &&
2459
+ (params["requestState"] !== undefined ||
2460
+ params["inputResponses"] !== undefined),
2461
+ },
2462
+ ),
2463
+ statelessVersion,
2464
+ ),
2465
+ });
2466
+ } catch (error) {
2467
+ this.log(
2468
+ `Error reading resource ${uri}: ${
2469
+ error instanceof Error ? error.message : String(error)
2470
+ }`,
2471
+ );
2472
+ return c.json({
2473
+ jsonrpc: "2.0",
2474
+ id,
2475
+ error: {
2476
+ code: -32603,
2477
+ message: error instanceof Error
2478
+ ? error.message
2479
+ : "Resource read failed",
2480
+ },
2481
+ });
2482
+ }
2483
+ }
2484
+
2485
+ // ── subscriptions/listen (SEP-2575) ──────────────────────────────
2486
+ //
2487
+ // Replaces the removed HTTP GET stream and resources/subscribe. The
2488
+ // response IS the stream: a long-lived SSE body carrying only the
2489
+ // notification types the client opted into.
2490
+ if (method === "subscriptions/listen" && this.subscriptions !== null) {
2491
+ const registry = this.subscriptions;
2492
+
2493
+ // A notification-shaped listen makes no sense: the response IS the
2494
+ // stream, and the subscription id IS this request's id — with no id
2495
+ // there is nothing to correlate notifications to.
2496
+ if (id === undefined) {
2497
+ return jsonRpcResponse(
2498
+ {
2499
+ jsonrpc: "2.0",
2500
+ id: null,
2501
+ error: {
2502
+ code: JSONRPC_INVALID_PARAMS,
2503
+ message:
2504
+ "subscriptions/listen requires a JSON-RPC id: the response is the notification stream, and the id identifies the subscription",
2505
+ },
2506
+ },
2507
+ 400,
2508
+ );
2509
+ }
2510
+ const subscriptionId: string | number = id as string | number;
2511
+ // A missing or non-object filter is malformed, not "subscribe to
2512
+ // nothing": a client that meant to subscribe would otherwise get a
2513
+ // 200 stream that stays silent forever, with no way to tell why.
2514
+ if (!isRecord(params) || !isRecord(params["notifications"])) {
2515
+ return jsonRpcResponse(
2516
+ {
2517
+ jsonrpc: "2.0",
2518
+ id,
2519
+ error: {
2520
+ code: JSONRPC_INVALID_PARAMS,
2521
+ message:
2522
+ "subscriptions/listen requires a 'notifications' object naming the types to receive",
2523
+ data: {
2524
+ problem: "missing_field",
2525
+ bodyField: "params.notifications",
2526
+ recovery:
2527
+ 'Send params.notifications, e.g. { toolsListChanged: true } or { resourceSubscriptions: ["ui://x"] }.',
2528
+ },
2529
+ },
2530
+ },
2531
+ 400,
2532
+ );
2533
+ }
2534
+ const filter = validateSubscriptionFilter(
2535
+ params["notifications"] as Record<string, unknown>,
2536
+ );
2537
+ if (!filter.ok) {
2538
+ return jsonRpcResponse(
2539
+ {
2540
+ jsonrpc: "2.0",
2541
+ id,
2542
+ error: {
2543
+ code: JSONRPC_INVALID_PARAMS,
2544
+ message: filter.message,
2545
+ data: {
2546
+ problem: "malformed_field",
2547
+ bodyField: filter.bodyField,
2548
+ recovery: filter.recovery,
2549
+ },
2550
+ },
2551
+ },
2552
+ 400,
2553
+ );
2554
+ }
2555
+ const requested = filter.filter;
2556
+
2557
+ // Recognising `taskIds` is mandatory even though pushing task updates is
2558
+ // not: a client that asks for task notifications without declaring the
2559
+ // Tasks extension MUST be refused. Accepting it would open a stream that
2560
+ // can never deliver, with nothing to say why.
2561
+ if (
2562
+ Array.isArray(requested.taskIds) && requested.taskIds.length > 0
2563
+ ) {
2564
+ const guard = this.requireTasksCapability(
2565
+ isRecord(params["_meta"])
2566
+ ? params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY] as
2567
+ | ClientCapabilities
2568
+ | undefined
2569
+ : undefined,
2570
+ id,
2571
+ );
2572
+ if (guard) return guard;
2573
+ }
2574
+
2575
+ // Computed ONCE by the registry and reused for both the
2576
+ // acknowledgement and the registration. Deriving it independently here
2577
+ // is how a client ends up told it subscribed to a set the registry does
2578
+ // not actually enforce.
2579
+ const agreed = registry.computeAgreedFilter(requested);
2580
+
2581
+ let internalKey: string | null = null;
2582
+ const stream = new ReadableStream<Uint8Array>({
2583
+ start: (controller) => {
2584
+ let closed = false;
2585
+ const sink: SubscriptionSink = {
2586
+ enqueue(chunk) {
2587
+ // The cancel() callback fires before unregister(), so a write
2588
+ // can race a closed controller on every client disconnect.
2589
+ if (closed) return;
2590
+ try {
2591
+ controller.enqueue(chunk);
2592
+ } catch {
2593
+ closed = true;
2594
+ }
2595
+ },
2596
+ close() {
2597
+ if (closed) return;
2598
+ closed = true;
2599
+ try {
2600
+ controller.close();
2601
+ } catch { /* already closed */ }
2602
+ },
2603
+ get isClosed() {
2604
+ return closed;
2605
+ },
2606
+ };
2607
+
2608
+ // The acknowledgement MUST be the first message on the stream, so
2609
+ // it is enqueued BEFORE registering — otherwise a fan-out landing
2610
+ // in between would precede it.
2611
+ sink.enqueue(
2612
+ encodeSSEEvent(
2613
+ buildAcknowledgedMessage(subscriptionId, agreed),
2614
+ ),
2615
+ );
2616
+ internalKey = registry.register(subscriptionId, agreed, sink);
2617
+ },
2618
+ cancel: () => {
2619
+ // Client closed the stream: that IS the cancellation signal on
2620
+ // HTTP, and the server must send nothing further.
2621
+ if (internalKey !== null) {
2622
+ registry.unregister(internalKey, "client");
2623
+ }
2624
+ },
2625
+ });
2626
+
2627
+ return new Response(stream, {
2628
+ status: 200,
2629
+ headers: {
2630
+ "Content-Type": "text/event-stream",
2631
+ "Cache-Control": "no-cache",
2632
+ Connection: "keep-alive",
2633
+ // Tells nginx and friends not to buffer, without which events sit
2634
+ // in a proxy until the buffer fills.
2635
+ "X-Accel-Buffering": "no",
2636
+ "MCP-Protocol-Version": statelessVersion,
2637
+ },
2638
+ });
2639
+ }
2640
+
2641
+ // ── Tasks extension (io.modelcontextprotocol/tasks) ──────────────
2642
+ //
2643
+ // The capability guard repeats on every one of these, not just at task
2644
+ // creation: the spec requires the missing-capability error for a
2645
+ // non-declaring client issuing tasks/get, tasks/update OR tasks/cancel.
2646
+ // Guarding creation alone would still let such a client poll and cancel
2647
+ // tasks it could never have been handed.
2648
+ // Capability-gated: a non-declaring client must not reach tasks/*.
2649
+ // The version gate (STATELESS_SUPPORTED_VERSIONS) upstream of this block
2650
+ // already rejects any peer running a pre-2026 protocol version.
2651
+ if (
2652
+ this.taskStore !== null &&
2653
+ (method === "tasks/get" || method === "tasks/update" ||
2654
+ method === "tasks/cancel")
2655
+ ) {
2656
+ // These are requests, never notifications. Without an id they would
2657
+ // otherwise slip past header validation — which exempts notifications —
2658
+ // then mutate task state and answer with an id-less, malformed
2659
+ // JSON-RPC response.
2660
+ if (id === undefined) {
2661
+ return jsonRpcResponse(
2662
+ {
2663
+ jsonrpc: "2.0",
2664
+ id: null,
2665
+ error: {
2666
+ code: JSONRPC_INVALID_PARAMS,
2667
+ message: `${method} is a request and requires a JSON-RPC id`,
2668
+ data: {
2669
+ problem: "missing_field",
2670
+ bodyField: "id",
2671
+ recovery:
2672
+ "Send the call as a JSON-RPC request with an id, not as a notification.",
2673
+ },
2674
+ },
2675
+ },
2676
+ 400,
2677
+ );
2678
+ }
2679
+ const store = this.taskStore;
2680
+ const guard = this.requireTasksCapability(
2681
+ isRecord(params) && isRecord(params["_meta"])
2682
+ ? params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY] as
2683
+ | ClientCapabilities
2684
+ | undefined
2685
+ : undefined,
2686
+ id,
2687
+ );
2688
+ if (guard) return guard;
2689
+
2690
+ const taskId =
2691
+ isRecord(params) && typeof params["taskId"] === "string"
2692
+ ? params["taskId"]
2693
+ : undefined;
2694
+ if (taskId === undefined) {
2695
+ return jsonRpcResponse(
2696
+ {
2697
+ jsonrpc: "2.0",
2698
+ id,
2699
+ error: {
2700
+ code: JSONRPC_INVALID_PARAMS,
2701
+ message: `${method} requires a string 'taskId' parameter`,
2702
+ },
2703
+ },
2704
+ 400,
2705
+ );
2706
+ }
2707
+
2708
+ const callerBase = callerPrincipal(httpAuthInfo);
2709
+ if (callerBase === null) {
2710
+ return noPrincipalError(
2711
+ id,
2712
+ statelessVersion,
2713
+ );
2714
+ }
2715
+ const caller = await taskOwnerKeyFor(
2716
+ this.options,
2717
+ httpAuthInfo,
2718
+ c.req.raw,
2719
+ callerBase,
2720
+ );
2721
+ if (caller === null) {
2722
+ return noOwnerKeyError(
2723
+ id,
2724
+ statelessVersion,
2725
+ );
2726
+ }
2727
+
2728
+ if (method === "tasks/get") {
2729
+ const task = store.get(taskId, caller);
2730
+ if (task === null) {
2731
+ return c.json({
2732
+ jsonrpc: "2.0",
2733
+ id,
2734
+ error: {
2735
+ code: JSONRPC_INVALID_PARAMS,
2736
+ message: `Unknown taskId: ${taskId}`,
2737
+ },
2738
+ });
2739
+ }
2740
+ // "complete", not "task" — see the note at task creation.
2741
+ return c.json({
2742
+ jsonrpc: "2.0",
2743
+ id,
2744
+ result: this.stampResult({ ...task }, statelessVersion),
1881
2745
  });
1882
2746
  }
1883
2747
 
1884
- try {
1885
- const content = await resourceInfo.handler(new URL(uri));
1886
- const finalContent = this.applyResourceCsp(content);
2748
+ if (method === "tasks/update") {
2749
+ // Spec field name is `inputResponses`, matching MRTR's vocabulary.
2750
+ const responses = isRecord(params) &&
2751
+ isRecord(params["inputResponses"])
2752
+ ? params["inputResponses"]
2753
+ : undefined;
2754
+ if (responses === undefined) {
2755
+ return jsonRpcResponse(
2756
+ {
2757
+ jsonrpc: "2.0",
2758
+ id,
2759
+ error: {
2760
+ code: JSONRPC_INVALID_PARAMS,
2761
+ message: "tasks/update requires an 'inputResponses' object",
2762
+ },
2763
+ },
2764
+ 400,
2765
+ );
2766
+ }
2767
+ if (!store.update(taskId, responses, caller)) {
2768
+ // SHOULD be an error for an unknown id — and an id belonging to
2769
+ // another caller is reported identically, so the response never
2770
+ // confirms that someone else's task exists.
2771
+ return c.json({
2772
+ jsonrpc: "2.0",
2773
+ id,
2774
+ error: {
2775
+ code: JSONRPC_INVALID_PARAMS,
2776
+ message: `Unknown taskId: ${taskId}`,
2777
+ },
2778
+ });
2779
+ }
2780
+ // MUST be an EMPTY acknowledgement (beyond the resultType envelope).
2781
+ // Returning the task state instead would look helpful and be
2782
+ // non-conformant — and the spec calls the ack eventually consistent,
2783
+ // so any state returned here could already be stale.
1887
2784
  return c.json({
1888
2785
  jsonrpc: "2.0",
1889
2786
  id,
1890
- result: { contents: [finalContent] },
2787
+ result: this.stampResult({}, statelessVersion),
1891
2788
  });
1892
- } catch (error) {
1893
- this.log(
1894
- `Error reading resource ${uri}: ${
1895
- error instanceof Error ? error.message : String(error)
1896
- }`,
1897
- );
2789
+ }
2790
+
2791
+ // tasks/cancel — likewise an empty ack. Cancellation is cooperative:
2792
+ // the server acknowledges intent, and the task may still finish or
2793
+ // reach a different terminal status.
2794
+ if (!store.cancel(taskId, caller)) {
1898
2795
  return c.json({
1899
2796
  jsonrpc: "2.0",
1900
2797
  id,
1901
2798
  error: {
1902
- code: -32603,
1903
- message: error instanceof Error
1904
- ? error.message
1905
- : "Resource read failed",
2799
+ code: JSONRPC_INVALID_PARAMS,
2800
+ message: `Unknown taskId: ${taskId}`,
1906
2801
  },
1907
2802
  });
1908
2803
  }
2804
+ return c.json({
2805
+ jsonrpc: "2.0",
2806
+ id,
2807
+ result: this.stampResult({}, statelessVersion),
2808
+ });
1909
2809
  }
1910
2810
 
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: {} });
1918
- }
2811
+ // `ping` and `logging/setLevel` were REMOVED by spec 2026-07-28.
2812
+ // They fall through to method-not-found below (404 + -32601), which is
2813
+ // how a client distinguishes a modern server from a legacy HTTP+SSE one.
1919
2814
  if (method === "prompts/list") {
1920
- return c.json({ jsonrpc: "2.0", id, result: { prompts: [] } });
1921
- }
1922
- // @deprecated (MCP 2026-07-28)
1923
- if (method === "logging/setLevel") {
1924
- return c.json({ jsonrpc: "2.0", id, result: {} });
2815
+ return c.json({
2816
+ jsonrpc: "2.0",
2817
+ id,
2818
+ result: this.stampResult(
2819
+ this.withCacheHints({ prompts: [] }, statelessVersion),
2820
+ statelessVersion,
2821
+ ),
2822
+ });
1925
2823
  }
1926
2824
  if (method === "completion/complete") {
1927
2825
  return c.json({
1928
2826
  jsonrpc: "2.0",
1929
2827
  id,
1930
- result: { completion: { values: [] } },
2828
+ result: this.stampResult(
2829
+ { completion: { values: [] } },
2830
+ statelessVersion,
2831
+ ),
1931
2832
  });
1932
2833
  }
1933
2834
 
1934
- // Handle notifications: must have a method and no id (JSON-RPC 2.0 notification)
1935
- if (method && !id) {
2835
+ // Handle notifications: a method and NO id (JSON-RPC 2.0).
2836
+ //
2837
+ // `!id` was wrong: `0` is a valid id and is falsy, so a request with
2838
+ // `id: 0` was answered 202-with-no-body as though it were a
2839
+ // notification. The spec only forbids `null`.
2840
+ if (method && id === undefined) {
1936
2841
  return new Response(null, { status: 202 });
1937
2842
  }
1938
2843
 
@@ -1948,12 +2853,23 @@ export class McpApp {
1948
2853
  });
1949
2854
  }
1950
2855
 
1951
- // Method not found
1952
- return c.json({
1953
- jsonrpc: "2.0",
1954
- id,
1955
- error: { code: -32601, message: `Method not found: ${method}` },
1956
- });
2856
+ // Method not found.
2857
+ //
2858
+ // Spec 2026-07-28 requires HTTP **404** here, not 200: "If the server
2859
+ // does not implement the requested RPC method, it MUST respond with
2860
+ // 404 Not Found and a JSON-RPC error with code -32601". The status is
2861
+ // load-bearing — a client probing an unknown URL uses exactly this
2862
+ // response to tell a modern MCP endpoint from a legacy HTTP+SSE server.
2863
+ //
2864
+ // This also covers the removed methods (`ping`, `logging/setLevel`).
2865
+ return jsonRpcResponse(
2866
+ {
2867
+ jsonrpc: "2.0",
2868
+ id,
2869
+ error: { code: -32601, message: `Method not found: ${method}` },
2870
+ },
2871
+ 404,
2872
+ );
1957
2873
  } catch (error) {
1958
2874
  this.log(
1959
2875
  `HTTP request error: ${
@@ -1975,8 +2891,7 @@ export class McpApp {
1975
2891
 
1976
2892
  // Embedded mode: skip serve(), surface the Hono fetch handler to the
1977
2893
  // caller and let them mount it inside their own framework (Fresh, Hono,
1978
- // Express, etc.). The session cleanup timer + post-init still runs so
1979
- // SSE clients and sessions are managed identically to the serve() path.
2894
+ // Express, etc.).
1980
2895
  if (options.embedded) {
1981
2896
  if (!options.embeddedHandlerCallback) {
1982
2897
  throw new Error(
@@ -1986,14 +2901,6 @@ export class McpApp {
1986
2901
  // deno-lint-ignore no-explicit-any
1987
2902
  options.embeddedHandlerCallback(app.fetch as any);
1988
2903
  this.started = true;
1989
- // Track A: no sessions in stateless mode — skip cleanup timer
1990
- if (this.options.transport !== "stateless") {
1991
- this.sessionCleanupTimer = setInterval(
1992
- () => this.cleanupSessions(),
1993
- McpApp.SESSION_CLEANUP_INTERVAL_MS,
1994
- );
1995
- unrefTimer(this.sessionCleanupTimer as unknown as number);
1996
- }
1997
2904
  this.log(
1998
2905
  `HTTP handler ready (embedded mode — no port bound, max concurrent: ${
1999
2906
  this.options.maxConcurrent ?? 10
@@ -2024,17 +2931,6 @@ export class McpApp {
2024
2931
 
2025
2932
  this.started = true;
2026
2933
 
2027
- // Start session cleanup timer (prevents unbounded memory growth).
2028
- // Track A: no sessions in stateless mode — skip timer to keep contract clean.
2029
- if (this.options.transport !== "stateless") {
2030
- this.sessionCleanupTimer = setInterval(
2031
- () => this.cleanupSessions(),
2032
- McpApp.SESSION_CLEANUP_INTERVAL_MS,
2033
- );
2034
- // Don't block Deno from exiting because of cleanup timer
2035
- unrefTimer(this.sessionCleanupTimer as unknown as number);
2036
- }
2037
-
2038
2934
  const rateLimitInfo = this.options.rateLimit
2039
2935
  ? `, rate limit: ${this.options.rateLimit.maxRequests}/${this.options.rateLimit.windowMs}ms`
2040
2936
  : "";
@@ -2078,13 +2974,12 @@ export class McpApp {
2078
2974
  *
2079
2975
  * The returned handler accepts a Web Standard {@link Request} and returns
2080
2976
  * a Web Standard {@link Response}. It exposes the same routes as
2081
- * {@link startHttp}: `POST /mcp`, `GET /mcp` (SSE), `GET /health`,
2082
- * `GET /metrics`, and `GET /.well-known/oauth-protected-resource`.
2977
+ * {@link startHttp}: `POST /mcp`, `GET /health`, `GET /metrics`, and
2978
+ * `GET /.well-known/oauth-protected-resource`. `GET /mcp` returns 405.
2083
2979
  *
2084
2980
  * Auth, multi-tenant middleware, scope checks, and rate limiting are all
2085
- * applied identically. The session cleanup timer and OTel hooks are
2086
- * started, so the server is fully live after this returns — just without
2087
- * its own listening socket.
2981
+ * applied identically. OTel hooks are started, so the server is fully
2982
+ * live after this returns — just without its own listening socket.
2088
2983
  *
2089
2984
  * Multi-tenant SaaS pattern: cache one `McpApp` per tenant
2090
2985
  * and call `getFetchHandler()` once per server, then dispatch each
@@ -2131,84 +3026,6 @@ export class McpApp {
2131
3026
  return captured;
2132
3027
  }
2133
3028
 
2134
- /**
2135
- * Send a JSON-RPC message to all SSE clients in a session
2136
- * Used for server-initiated notifications and requests
2137
- *
2138
- * @param sessionId - Session ID (or "anonymous" for clients without session)
2139
- * @param message - JSON-RPC message to send
2140
- */
2141
- sendToSession(sessionId: string, message: Record<string, unknown>): void {
2142
- const clients = this.sseClients.get(sessionId);
2143
- if (!clients || clients.length === 0) {
2144
- this.log(`No SSE clients for session: ${sessionId}`);
2145
- return;
2146
- }
2147
-
2148
- const encoder = new TextEncoder();
2149
- const eventId = Date.now();
2150
- const data = `id: ${eventId}\ndata: ${JSON.stringify(message)}\n\n`;
2151
-
2152
- // Iterate in reverse so splice doesn't shift indices
2153
- for (let i = clients.length - 1; i >= 0; i--) {
2154
- const client = clients[i];
2155
- try {
2156
- client.controller.enqueue(encoder.encode(data));
2157
- client.lastEventId = eventId;
2158
- } catch {
2159
- // Stream is closed/broken — remove zombie client to prevent memory leak
2160
- clients.splice(i, 1);
2161
- this.log(`Removed dead SSE client from session: ${sessionId}`);
2162
- }
2163
- }
2164
-
2165
- // Clean up empty session entry
2166
- if (clients.length === 0) {
2167
- this.sseClients.delete(sessionId);
2168
- }
2169
- }
2170
-
2171
- /**
2172
- * Send a notification to all connected SSE clients
2173
- *
2174
- * @param method - Notification method name
2175
- * @param params - Notification parameters
2176
- */
2177
- broadcastNotification(
2178
- method: string,
2179
- params?: Record<string, unknown>,
2180
- ): void {
2181
- const message = {
2182
- jsonrpc: "2.0",
2183
- method,
2184
- params,
2185
- };
2186
-
2187
- for (const sessionId of this.sseClients.keys()) {
2188
- this.sendToSession(sessionId, message);
2189
- }
2190
- }
2191
-
2192
- /**
2193
- * Get number of active SSE connections
2194
- */
2195
- getSSEClientCount(): number {
2196
- let count = 0;
2197
- for (const clients of this.sseClients.values()) {
2198
- count += clients.length;
2199
- }
2200
- return count;
2201
- }
2202
-
2203
- /**
2204
- * Get sampling bridge (if enabled)
2205
- *
2206
- * @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
2207
- */
2208
- getSamplingBridge(): SamplingBridge | null {
2209
- return this.samplingBridge;
2210
- }
2211
-
2212
3029
  /**
2213
3030
  * Read the MCP Apps capability advertised by the connected client.
2214
3031
  *
@@ -2261,8 +3078,6 @@ export class McpApp {
2261
3078
  this.serverMetrics.setGauges({
2262
3079
  activeRequests: qm.inFlight,
2263
3080
  queuedRequests: qm.queued,
2264
- activeSessions: this.sessions.size,
2265
- sseClients: this.getSSEClientCount(),
2266
3081
  rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
2267
3082
  });
2268
3083
  return this.serverMetrics.getSnapshot();
@@ -2362,10 +3177,13 @@ export class McpApp {
2362
3177
 
2363
3178
  /**
2364
3179
  * 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
3180
  *
2368
- * @param method - Notification method (e.g. "notifications/message")
3181
+ * Routing depends on the transport:
3182
+ * - **HTTP**: fanned out to `subscriptions/listen` streams, only to
3183
+ * subscribers that opted into that notification type.
3184
+ * - **stdio**: written to stdout via the SDK transport.
3185
+ *
3186
+ * @param method - Notification method (e.g. "notifications/tools/list_changed")
2369
3187
  * @param params - Notification parameters
2370
3188
  */
2371
3189
  sendNotification(
@@ -2374,10 +3192,43 @@ export class McpApp {
2374
3192
  ): void {
2375
3193
  if (!this.started) return;
2376
3194
 
2377
- // For HTTP mode, broadcast via SSE
2378
- if (this.httpServer) {
2379
- this.broadcastNotification(method, params);
2380
- return;
3195
+ // Route through the subscription registry (subscriptions/listen streams).
3196
+ if (this.subscriptions !== null) {
3197
+ switch (method) {
3198
+ case "notifications/tools/list_changed":
3199
+ this.subscriptions.fanOut("toolsListChanged");
3200
+ return;
3201
+ case "notifications/prompts/list_changed":
3202
+ this.subscriptions.fanOut("promptsListChanged");
3203
+ return;
3204
+ case "notifications/resources/list_changed":
3205
+ this.subscriptions.fanOut("resourcesListChanged");
3206
+ return;
3207
+ case "notifications/resources/updated": {
3208
+ const uri = isRecord(params) && typeof params["uri"] === "string"
3209
+ ? params["uri"]
3210
+ : undefined;
3211
+ if (uri === undefined) {
3212
+ this.log(
3213
+ "[WARN] notifications/resources/updated requires a string 'uri' param; dropped",
3214
+ );
3215
+ return;
3216
+ }
3217
+ this.subscriptions.fanOutResourceUpdated(uri);
3218
+ return;
3219
+ }
3220
+ default:
3221
+ // subscriptions/listen carries only the four change types a client can
3222
+ // opt into. Anything else — a request-scoped progress or log message —
3223
+ // belongs on the response stream of the request it relates to, which is
3224
+ // not something this method can reach. Say so rather than drop silently.
3225
+ this.log(
3226
+ `[WARN] sendNotification("${method}") has no delivery channel in stateless mode: ` +
3227
+ "only the four subscriptions/listen change types can be pushed. " +
3228
+ "Request-scoped notifications must travel on their own request's response stream.",
3229
+ );
3230
+ return;
3231
+ }
2381
3232
  }
2382
3233
 
2383
3234
  // For stdio mode, send via SDK transport
@@ -2403,7 +3254,6 @@ export class McpApp {
2403
3254
  * Pre-formatted results have a `content` array and are passed through
2404
3255
  * without re-wrapping. This supports proxy/gateway patterns.
2405
3256
  */
2406
- // deno-lint-ignore no-explicit-any
2407
3257
  private isPreformattedResult(
2408
3258
  result: unknown,
2409
3259
  ): result is {
@@ -2420,6 +3270,444 @@ export class McpApp {
2420
3270
  "text" in obj.content[0];
2421
3271
  }
2422
3272
 
3273
+ /**
3274
+ * Apply the spec-2026-07-28 result envelope when — and only when — the peer
3275
+ * negotiated that revision.
3276
+ *
3277
+ * Always applies on the stateless transport, which only accepts 2026-07-28.
3278
+ * Stdio mode passes `undefined` and stays on the legacy shape.
3279
+ *
3280
+ * Omitting the envelope for a genuinely legacy peer is safe in the other
3281
+ * direction too: the spec instructs clients to read a missing `resultType` as
3282
+ * `"complete"`.
3283
+ *
3284
+ * Every HTTP result path funnels through here. Adding a new one without it is
3285
+ * the failure mode to watch for — hence the conformance test that walks the
3286
+ * method table rather than asserting one endpoint at a time.
3287
+ *
3288
+ * @param negotiatedVersion Version from the request's `_meta`, or `undefined`
3289
+ * where no per-request negotiation happens.
3290
+ */
3291
+ private stampResult(
3292
+ result: Record<string, unknown>,
3293
+ negotiatedVersion?: string,
3294
+ resultType: "complete" | "task" = "complete",
3295
+ ): Record<string, unknown> {
3296
+ if (negotiatedVersion !== SPEC_2026_07_28) return result;
3297
+ return {
3298
+ ...completeResult(result, {
3299
+ name: this.options.name,
3300
+ version: this.options.version,
3301
+ }),
3302
+ resultType,
3303
+ };
3304
+ }
3305
+
3306
+ /**
3307
+ * Resolve the MRTR signing key once, warning if a deployment has none.
3308
+ *
3309
+ * A missing key is not an error: the spec permits unprotected `requestState`
3310
+ * when tampering can cause nothing worse than the request failing. It is a
3311
+ * loud warning because that condition is easy to believe and hard to verify.
3312
+ */
3313
+ /**
3314
+ * Key lookup that reports failure instead of throwing.
3315
+ *
3316
+ * The `tools/call` call sites sit outside the tool try/catch, so a throw would
3317
+ * reach the POST-level catch and surface as -32700 "Parse error" — the same trap
3318
+ * the earlier throwing principal guard fell into. Returns a ready response
3319
+ * instead.
3320
+ */
3321
+ private async getMrtrKeySafe(
3322
+ id: unknown,
3323
+ version: string,
3324
+ ): Promise<{ key: CryptoKey | null } | { error: Response }> {
3325
+ try {
3326
+ return { key: await this.getMrtrKey() };
3327
+ } catch (error) {
3328
+ return {
3329
+ error: jsonRpcResponse(
3330
+ {
3331
+ jsonrpc: "2.0",
3332
+ id,
3333
+ error: {
3334
+ code: ErrorCode.InternalError,
3335
+ message: "MRTR signing key is unavailable",
3336
+ data: {
3337
+ problem: "mrtr_key_unavailable",
3338
+ detail: error instanceof Error ? error.message : String(error),
3339
+ recovery:
3340
+ "Check mrtr.signingKey. The import is retried on the next request, so a transient failure clears itself.",
3341
+ },
3342
+ },
3343
+ },
3344
+ 500,
3345
+ { "MCP-Protocol-Version": version },
3346
+ ),
3347
+ };
3348
+ }
3349
+ }
3350
+
3351
+ private getMrtrKey(): Promise<CryptoKey | null> {
3352
+ // Assigned synchronously, so two concurrent callers share one import rather
3353
+ // than one of them observing a half-initialised state.
3354
+ //
3355
+ // A REJECTED import is un-memoised in the catch below: caching the rejection
3356
+ // poisoned the instance permanently, and every later retry surfaced it through
3357
+ // the POST-level catch as -32700 "Parse error" — wrong code, and no second
3358
+ // attempt ever made. A transient WebCrypto failure should not be terminal.
3359
+ this.mrtrKeyPromise ??= (async () => {
3360
+ const hex = this.options.mrtr?.signingKey;
3361
+ if (hex === undefined) {
3362
+ this.log(
3363
+ "[WARN] MRTR requestState is unprotected: no mrtr.signingKey configured. " +
3364
+ "A client can tamper with it. Only acceptable when requestState " +
3365
+ "influences nothing beyond whether the request succeeds.",
3366
+ );
3367
+ return null;
3368
+ }
3369
+ try {
3370
+ return await importStateKey(hex);
3371
+ } catch (error) {
3372
+ // Drop the memoised rejection so a later request retries the import.
3373
+ this.mrtrKeyPromise = null;
3374
+ throw new Error(
3375
+ `[McpApp] mrtr.signingKey could not be imported: ${
3376
+ error instanceof Error ? error.message : String(error)
3377
+ }`,
3378
+ );
3379
+ }
3380
+ })();
3381
+ return this.mrtrKeyPromise;
3382
+ }
3383
+
3384
+ /**
3385
+ * Turn a handler's `InputRequiredSignal` into the wire result.
3386
+ *
3387
+ * Validates what the spec puts on the server rather than the client:
3388
+ * - at least one of `inputRequests` / `requestState` must be present;
3389
+ * - no input request may name a capability the client did not declare.
3390
+ *
3391
+ * A violation is the server author's bug, so it surfaces as `-32603` rather
3392
+ * than being emitted as an invalid MRTR result for the client to puzzle over.
3393
+ */
3394
+ private async buildInputRequiredResult(
3395
+ signal: InputRequiredSignal,
3396
+ context: {
3397
+ clientCapabilities: ClientCapabilities | undefined;
3398
+ principal: string;
3399
+ method: string;
3400
+ /** Digest of the arguments as received, taken before the pipeline ran. */
3401
+ paramsDigest: string;
3402
+ },
3403
+ ): Promise<
3404
+ { ok: true; result: Record<string, unknown> } | {
3405
+ ok: false;
3406
+ message: string;
3407
+ code: number;
3408
+ data?: Record<string, unknown>;
3409
+ }
3410
+ > {
3411
+ const requests = signal.inputRequests;
3412
+
3413
+ // `Object.keys(null)` throws, and `inputRequests: null` survives JSON — so an
3414
+ // unchecked map reached the generic tool-error path as a 200 instead of being
3415
+ // classified as the malformed server output it is. Validated before enumerating.
3416
+ if (requests !== undefined && !isRecord(requests)) {
3417
+ return {
3418
+ ok: false,
3419
+ code: ErrorCode.InternalError,
3420
+ message: "Malformed inputRequest: inputRequests must be an object",
3421
+ };
3422
+ }
3423
+
3424
+ const hasRequests = requests !== undefined &&
3425
+ Object.keys(requests).length > 0;
3426
+
3427
+ if (!hasRequests && signal.requestState === undefined) {
3428
+ return {
3429
+ ok: false,
3430
+ code: ErrorCode.InternalError,
3431
+ message:
3432
+ "An InputRequiredResult must carry at least one of inputRequests or requestState (spec 2026-07-28, MRTR server rule 6)",
3433
+ };
3434
+ }
3435
+
3436
+ let canonicalRequests: Record<string, unknown> | undefined;
3437
+ if (hasRequests) {
3438
+ const check = checkInputRequestCapabilities(
3439
+ requests as Record<string, InputRequestEntry>,
3440
+ context.clientCapabilities as Record<string, unknown> | undefined,
3441
+ );
3442
+ if (!check.ok) {
3443
+ // A structurally invalid input request is the SERVER's bug. Reporting it
3444
+ // as -32021 told the client to declare a capability it already had, and
3445
+ // hid the real fault behind a client-facing error.
3446
+ if (check.kind === "malformed") {
3447
+ return {
3448
+ ok: false,
3449
+ code: ErrorCode.InternalError,
3450
+ message: `Malformed inputRequest: ${
3451
+ check.missingCapabilities.join(", ")
3452
+ }`,
3453
+ };
3454
+ }
3455
+ // Spec rule 7 is a MUST NOT on the server: never ask for input the
3456
+ // client cannot provide. Emitting it anyway would strand the request.
3457
+ return {
3458
+ ok: false,
3459
+ code: MCP_MISSING_REQUIRED_CLIENT_CAPABILITY,
3460
+ message:
3461
+ `Cannot request input for capabilities the client did not declare: ${
3462
+ check.missingCapabilities.join(", ")
3463
+ }`,
3464
+ // ClientCapabilities-shaped so a typed client can read it directly and
3465
+ // learn which capability to declare.
3466
+ data: {
3467
+ // The check supplies a nested shape for sub-capabilities; otherwise
3468
+ // the names are top-level keys.
3469
+ requiredCapabilities: check.requiredCapabilities ??
3470
+ Object.fromEntries(
3471
+ check.missingCapabilities.map((cap) => [cap, {}]),
3472
+ ),
3473
+ },
3474
+ };
3475
+ }
3476
+ canonicalRequests = check.canonicalRequests;
3477
+ }
3478
+
3479
+ // Seal the token so the retry can be proven legitimate. The payload holds
3480
+ // only bindings — principal, method, argument digest, expiry, nonce — not
3481
+ // application state: since the digest guarantees identical arguments, a
3482
+ // handler rebuilds its context from those.
3483
+ //
3484
+ // The principal binding is only meaningful when auth is configured; see the
3485
+ // verification site. Sealing happens AFTER the capability check on purpose —
3486
+ // no point minting a token for a result that will be refused.
3487
+ // Resolved here regardless of `needsKey` at ingress: a FIRST leg carries
3488
+ // neither MRTR field and still needs a sealed token. A rejected import is
3489
+ // reported as what it is rather than surfacing as a tool failure — the
3490
+ // handler did nothing wrong.
3491
+ let key: CryptoKey | null;
3492
+ try {
3493
+ key = await this.getMrtrKey();
3494
+ } catch (error) {
3495
+ return {
3496
+ ok: false,
3497
+ code: ErrorCode.InternalError,
3498
+ message: "MRTR signing key is unavailable",
3499
+ data: {
3500
+ problem: "mrtr_key_unavailable",
3501
+ detail: error instanceof Error ? error.message : String(error),
3502
+ recovery:
3503
+ "Check mrtr.signingKey. The import is retried on the next request, so a transient failure clears itself.",
3504
+ },
3505
+ };
3506
+ }
3507
+ let requestState = signal.requestState;
3508
+ if (key !== null) {
3509
+ const ttl = this.options.mrtr?.defaultTtlSecs ?? 300;
3510
+ requestState = await sealRequestState({
3511
+ sub: context.principal,
3512
+ method: context.method,
3513
+ paramsDigest: context.paramsDigest,
3514
+ exp: Math.floor(Date.now() / 1000) + ttl,
3515
+ nonce: bytesToHexLocal(crypto.getRandomValues(new Uint8Array(16))),
3516
+ }, key);
3517
+ }
3518
+
3519
+ // No `?? requests` fallback. Falling back to the handler's object would
3520
+ // silently restore the very bypass this closes — a fallback that reopens a
3521
+ // security hole is worse than a failure. If the invariant ever breaks, say so.
3522
+ if (hasRequests && canonicalRequests === undefined) {
3523
+ return {
3524
+ ok: false,
3525
+ code: ErrorCode.InternalError,
3526
+ message:
3527
+ "Internal invariant violated: inputRequests were not canonicalised before emission",
3528
+ };
3529
+ }
3530
+
3531
+ // Serialisation can EMPTY the map: JSON drops keys whose value is `undefined`,
3532
+ // so `{ ask: undefined }` canonicalises to `{}`. The at-least-one rule was
3533
+ // checked against the original, so that emitted an InputRequiredResult with an
3534
+ // empty map and — where no key is configured — no requestState either, leaving
3535
+ // the client nothing to answer and no reason to retry.
3536
+ const canonicalCount = canonicalRequests === undefined
3537
+ ? 0
3538
+ : Object.keys(canonicalRequests).length;
3539
+ if (hasRequests && canonicalCount === 0) {
3540
+ return {
3541
+ ok: false,
3542
+ code: ErrorCode.InternalError,
3543
+ message:
3544
+ "inputRequests contained no serialisable entries (keys with an undefined value are dropped by JSON)",
3545
+ };
3546
+ }
3547
+ if (canonicalCount === 0 && requestState === undefined) {
3548
+ return {
3549
+ ok: false,
3550
+ code: ErrorCode.InternalError,
3551
+ message:
3552
+ "An InputRequiredResult must carry at least one of inputRequests or requestState (spec 2026-07-28, MRTR server rule 6)",
3553
+ };
3554
+ }
3555
+
3556
+ return {
3557
+ ok: true,
3558
+ result: {
3559
+ resultType: "input_required",
3560
+ // This path deliberately cannot use stampResult(): that would replace
3561
+ // its `input_required` discriminator with `complete`. It is still a
3562
+ // 2026 Result, though, so carry the same server identity envelope as
3563
+ // every other response.
3564
+ _meta: {
3565
+ [STATELESS_SERVER_INFO_KEY]: {
3566
+ name: this.options.name,
3567
+ version: this.options.version,
3568
+ },
3569
+ },
3570
+ // The clone the check inspected, NOT the handler's object. Serialising the
3571
+ // original a second time lets a stateful `toJSON()` return a different
3572
+ // value for the response than the gate approved.
3573
+ ...(canonicalRequests !== undefined
3574
+ ? { inputRequests: canonicalRequests }
3575
+ : {}),
3576
+ ...(requestState !== undefined ? { requestState } : {}),
3577
+ },
3578
+ };
3579
+ }
3580
+
3581
+ /**
3582
+ * Reject a Tasks request from a client that did not declare the extension.
3583
+ *
3584
+ * Returns a ready 400 response to return, or `null` when the client is
3585
+ * entitled to proceed. Two distinct spec rules converge here: a server
3586
+ * **MUST NOT** hand a task to a non-declaring client, and **MUST** answer the
3587
+ * missing-capability error when one calls `tasks/*`.
3588
+ *
3589
+ * `-32021` (`MissingRequiredClientCapability`) is the code, and
3590
+ * `data.requiredCapabilities` is required to list what was missing — a client
3591
+ * that gets this back needs to know which capability to add, not just that
3592
+ * something was absent.
3593
+ */
3594
+ private requireTasksCapability(
3595
+ clientCapabilities: ClientCapabilities | undefined,
3596
+ id: unknown,
3597
+ ): Response | null {
3598
+ if (this.taskStore === null) {
3599
+ return jsonRpcResponse(
3600
+ {
3601
+ jsonrpc: "2.0",
3602
+ id,
3603
+ error: {
3604
+ code: ErrorCode.MethodNotFound,
3605
+ message:
3606
+ `Tasks extension is not enabled on this server (declare "${TASKS_EXTENSION_ID}" in McpAppOptions.extensions)`,
3607
+ },
3608
+ },
3609
+ 404,
3610
+ );
3611
+ }
3612
+
3613
+ const extensions = clientCapabilities?.extensions;
3614
+ const declared = isRecord(extensions) &&
3615
+ extensions[TASKS_EXTENSION_ID] !== undefined;
3616
+ if (declared) return null;
3617
+
3618
+ return jsonRpcResponse(
3619
+ {
3620
+ jsonrpc: "2.0",
3621
+ id,
3622
+ error: {
3623
+ code: MCP_MISSING_REQUIRED_CLIENT_CAPABILITY,
3624
+ message:
3625
+ `Client did not declare the "${TASKS_EXTENSION_ID}" extension`,
3626
+ // ClientCapabilities-shaped, per the schema: capability keys mapping
3627
+ // to their settings object. An array of names would not deserialise
3628
+ // into `ClientCapabilities` on a typed client.
3629
+ data: {
3630
+ requiredCapabilities: { extensions: { [TASKS_EXTENSION_ID]: {} } },
3631
+ },
3632
+ },
3633
+ },
3634
+ 400,
3635
+ );
3636
+ }
3637
+
3638
+ /**
3639
+ * Task status transitions, for pushing to subscribers.
3640
+ *
3641
+ * The spec's notification method is `notifications/tasks` — not a
3642
+ * `tasks/`-prefixed name, which would collide with the request methods.
3643
+ *
3644
+ * Delivery goes out over `subscriptions/listen` once that route is wired
3645
+ * (Track G); the registry exists but the transport does not yet open streams.
3646
+ * Until then this is intentionally a no-op beyond the log: polling via
3647
+ * `tasks/get` is the spec's default and works without it.
3648
+ */
3649
+ private onTaskChanged(task: DetailedTask): void {
3650
+ this.log(`task ${task.taskId} → ${task.status}`);
3651
+ }
3652
+
3653
+ /**
3654
+ * Add the required `CacheableResult` fields (spec 2026-07-28, SEP-2549).
3655
+ *
3656
+ * Applies to `tools/list`, `prompts/list`, `resources/list`, `resources/read`
3657
+ * and `resources/templates/list`, where the final spec makes both fields
3658
+ * required rather than optional. Same version gate as {@link stampResult}:
3659
+ * neither field exists in an earlier revision.
3660
+ *
3661
+ * Both are hints — a client that ignores them stays correct, it just polls
3662
+ * more often.
3663
+ */
3664
+ private withCacheHints(
3665
+ result: Record<string, unknown>,
3666
+ negotiatedVersion?: string,
3667
+ request?: { readonly isMrtrRetry?: boolean },
3668
+ ): Record<string, unknown> {
3669
+ if (negotiatedVersion !== SPEC_2026_07_28) return result;
3670
+
3671
+ // A result produced by an MRTR retry MUST NOT be cached: it depends on
3672
+ // `inputResponses` / `requestState`, which are not part of the cache key, so
3673
+ // a cache would serve it for a later request that supplied different input.
3674
+ // Emitting no hints is how a server declines to make the result cacheable —
3675
+ // clients read an absent ttlMs as 0.
3676
+ if (request?.isMrtrRetry) return result;
3677
+
3678
+ return {
3679
+ ...result,
3680
+ ttlMs: this.cacheTtlMs,
3681
+ cacheScope: this.options.cache?.scope ?? "private",
3682
+ };
3683
+ }
3684
+
3685
+ /**
3686
+ * Capabilities advertised on `server/discover` and `initialize`.
3687
+ *
3688
+ * Single source of truth: these two responses used to build the same object
3689
+ * independently, which is how they drift.
3690
+ *
3691
+ * `extensions` (spec 2026-07-28) is the declaration point for opt-in
3692
+ * extensions such as `io.modelcontextprotocol/tasks`. It is emitted only when
3693
+ * the consumer actually declares one — an empty `extensions: {}` would read as
3694
+ * "this server supports no extensions", which is a stronger claim than we can
3695
+ * make while MCP Apps support is de-facto (via `ui://` resources) rather than
3696
+ * declared. Wire it up here once the Apps extension identifier is pinned.
3697
+ */
3698
+ private buildServerCapabilities(): Record<string, unknown> {
3699
+ const { extensions } = this.options;
3700
+ // The declaration in options is the single source of truth: `taskStore` is
3701
+ // created from it, so advertising and behaviour cannot drift apart.
3702
+ return {
3703
+ tools: {},
3704
+ resources: this.resources.size > 0 ? {} : undefined,
3705
+ ...(extensions && Object.keys(extensions).length > 0
3706
+ ? { extensions }
3707
+ : {}),
3708
+ };
3709
+ }
3710
+
2423
3711
  /**
2424
3712
  * Build the tools/list response, filtering out app-only tools
2425
3713
  * and passing through outputSchema/annotations when defined.
@@ -2442,7 +3730,25 @@ export class McpApp {
2442
3730
  if (t.outputSchema !== undefined) entry.outputSchema = t.outputSchema;
2443
3731
  if (t.annotations !== undefined) entry.annotations = t.annotations;
2444
3732
  return entry;
2445
- });
3733
+ })
3734
+ // Spec 2026-07-28 (minor change 3): return tools in a deterministic order.
3735
+ // It lets clients cache the list and improves LLM prompt-cache hit rates.
3736
+ //
3737
+ // Map iteration is already insertion-ordered, so this only matters where
3738
+ // registration order itself is unstable — which it is for the relay/proxy
3739
+ // case, where tools are registered as child servers are discovered
3740
+ // asynchronously. Sorting by name makes the output independent of who
3741
+ // answered first.
3742
+ //
3743
+ // Deliberately not `localeCompare`: that orders differently per host
3744
+ // locale, reintroducing the very non-determinism being removed here.
3745
+ .sort((a, b) =>
3746
+ (a.name as string) < (b.name as string)
3747
+ ? -1
3748
+ : (a.name as string) > (b.name as string)
3749
+ ? 1
3750
+ : 0
3751
+ );
2446
3752
  }
2447
3753
 
2448
3754
  /**
@@ -2473,7 +3779,7 @@ export class McpApp {
2473
3779
  ): Record<string, unknown> {
2474
3780
  // Proxy/gateway pattern — pass through as-is
2475
3781
  if (this.isPreformattedResult(result)) {
2476
- return result as Record<string, unknown>;
3782
+ return canonicaliseWireResult(result as Record<string, unknown>);
2477
3783
  }
2478
3784
 
2479
3785
  const tool = this.tools.get(toolName);
@@ -2485,7 +3791,7 @@ export class McpApp {
2485
3791
  structuredContent: result.structuredContent,
2486
3792
  };
2487
3793
  if (tool?._meta) r._meta = tool._meta;
2488
- return r;
3794
+ return canonicaliseWireResult(r);
2489
3795
  }
2490
3796
 
2491
3797
  // Plain value: JSON-stringify into content[0].text
@@ -2498,7 +3804,7 @@ export class McpApp {
2498
3804
  }],
2499
3805
  };
2500
3806
  if (tool?._meta) r._meta = tool._meta;
2501
- return r;
3807
+ return canonicaliseWireResult(r);
2502
3808
  }
2503
3809
 
2504
3810
  /**