@casys/mcp-server 0.23.0 → 0.24.1

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";
@@ -89,6 +88,8 @@ import {
89
88
  importStateKey,
90
89
  type InputRequestEntry,
91
90
  type InputRequiredSignal,
91
+ MemoryMrtrReplayStore,
92
+ type MrtrReplayStore,
92
93
  paramsDigest,
93
94
  sealRequestState,
94
95
  verifyRequestState,
@@ -102,6 +103,20 @@ import {
102
103
  } from "./subscriptions/subscription-registry.js";
103
104
  import { ServerMetrics } from "./observability/metrics.js";
104
105
  import { endToolCallSpan, startToolCallSpan } from "./observability/otel.js";
106
+ import {
107
+ BodyTooLargeError,
108
+ DEFAULT_MAX_BODY_BYTES,
109
+ getClientIpFromHeaders,
110
+ readBodyWithLimit,
111
+ } from "./http/body.js";
112
+ import {
113
+ bytesToHexLocal,
114
+ callerPrincipal,
115
+ noOwnerKeyError,
116
+ noPrincipalError,
117
+ taskOwnerKeyFor,
118
+ } from "./http/request-guards.js";
119
+ import { isRecord, jsonRpcResponse } from "./http/wire.js";
105
120
 
106
121
  /**
107
122
  * Tool definition with handler
@@ -118,84 +133,6 @@ interface RegisteredResourceInfo {
118
133
  handler: ResourceHandler;
119
134
  }
120
135
 
121
- /**
122
- * SSE client connection for Streamable HTTP
123
- */
124
- interface SSEClient {
125
- sessionId: string;
126
- controller: ReadableStreamDefaultController<Uint8Array>;
127
- createdAt: number;
128
- lastEventId: number;
129
- }
130
-
131
- const DEFAULT_MAX_BODY_BYTES = 1_000_000;
132
-
133
- class BodyTooLargeError extends Error {
134
- constructor(maxBytes: number) {
135
- super(`Payload too large. Max ${maxBytes} bytes.`);
136
- this.name = "BodyTooLargeError";
137
- }
138
- }
139
-
140
- /**
141
- * Generate a cryptographically secure session ID
142
- */
143
- function generateSessionId(): string {
144
- const bytes = new Uint8Array(16);
145
- crypto.getRandomValues(bytes);
146
- return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
147
- }
148
-
149
- function getClientIpFromHeaders(headers: Headers): string {
150
- const forwarded = headers.get("x-forwarded-for");
151
- if (forwarded) {
152
- return forwarded.split(",")[0]?.trim() || "unknown";
153
- }
154
- return headers.get("x-real-ip") ??
155
- headers.get("cf-connecting-ip") ??
156
- "unknown";
157
- }
158
-
159
- async function readBodyWithLimit(
160
- request: Request,
161
- maxBytes: number | null,
162
- ): Promise<Uint8Array> {
163
- const contentLength = request.headers.get("content-length");
164
- if (maxBytes !== null && contentLength) {
165
- const length = Number(contentLength);
166
- if (!Number.isNaN(length) && length > maxBytes) {
167
- throw new BodyTooLargeError(maxBytes);
168
- }
169
- }
170
-
171
- if (!request.body) {
172
- return new Uint8Array();
173
- }
174
-
175
- const reader = request.body.getReader();
176
- const chunks: Uint8Array[] = [];
177
- let total = 0;
178
-
179
- while (true) {
180
- const { done, value } = await reader.read();
181
- if (done) break;
182
- if (!value) continue;
183
- total += value.length;
184
- if (maxBytes !== null && total > maxBytes) {
185
- throw new BodyTooLargeError(maxBytes);
186
- }
187
- chunks.push(value);
188
- }
189
-
190
- const body = new Uint8Array(total);
191
- let offset = 0;
192
- for (const chunk of chunks) {
193
- body.set(chunk, offset);
194
- offset += chunk.length;
195
- }
196
- return body;
197
- }
198
-
199
136
  // ── Track A (spec 2026-07-28) — Stateless transport constants ───────────────
200
137
 
201
138
  /** Namespaced protocolVersion key in params._meta (spec 2026-07-28) */
@@ -211,8 +148,6 @@ const STATELESS_CLIENT_CAPABILITIES_KEY =
211
148
  /** Protocol versions accepted by this server in stateless mode */
212
149
  const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
213
150
  "2026-07-28",
214
- "2025-06-18",
215
- "2025-11-25",
216
151
  ];
217
152
 
218
153
  /** Namespaced serverInfo key in a result's _meta (spec 2026-07-28, SHOULD) */
@@ -238,8 +173,8 @@ const SPEC_2026_07_28 = "2026-07-28";
238
173
  */
239
174
  const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
240
175
 
241
- /** Version echoed in MCP-Protocol-Version header on error responses (server's stable baseline) */
242
- const STATELESS_FALLBACK_VERSION = "2025-06-18";
176
+ /** Version echoed in MCP-Protocol-Version header on error responses (server's only accepted version) */
177
+ const STATELESS_FALLBACK_VERSION = "2026-07-28";
243
178
 
244
179
  const JSONRPC_INVALID_PARAMS = ErrorCode.InvalidParams;
245
180
 
@@ -305,155 +240,6 @@ function readLogLevel(meta: Record<string, unknown>): McpLogLevel | undefined {
305
240
  : undefined;
306
241
  }
307
242
 
308
- /**
309
- * Sentinel used when there is no authentication at all.
310
- *
311
- * Deliberately not a plausible subject value: the NUL prefix cannot appear in a
312
- * JWT `sub`, so it can never collide with a real principal.
313
- */
314
- const MRTR_NO_AUTH_PRINCIPAL = "\u0000unauthenticated";
315
-
316
- /**
317
- * Principal to bind a `requestState` to.
318
- *
319
- * Three cases, only two of which are acceptable:
320
- *
321
- * 1. **No auth configured** — every caller shares one authority by definition, so
322
- * there is no boundary to enforce and the sentinel above is honest about it.
323
- * The method and argument bindings still apply.
324
- * 2. **Authenticated with a subject** — the binding separates callers, which is
325
- * the case it exists for.
326
- * 3. **Authenticated without a usable subject** — `AuthInfo.subject` falls back to
327
- * `"unknown"` for a valid token carrying no `sub` claim. Sealing against that
328
- * would put every such caller under one identity: a token minted for one could
329
- * be spent by another, while the code reads as though the binding were
330
- * enforced. That is worse than no auth, because it is invisible. Throws.
331
- */
332
- function callerPrincipal(authInfo: AuthInfo | undefined): string | null {
333
- if (authInfo === undefined) return MRTR_NO_AUTH_PRINCIPAL;
334
- const subject = authInfo.subject;
335
- if (subject === undefined || subject === "" || subject === "unknown") {
336
- // `null`, not a throw: the task handlers call this outside any try/catch, so
337
- // a throw would surface through the POST-level catch as -32700 "Parse error"
338
- // — a diagnosis pointing nowhere near a misconfigured auth provider. The
339
- // caller turns this into an explicit error instead.
340
- return null;
341
- }
342
- return subject;
343
- }
344
-
345
- /**
346
- * Authorization key for a task-related request.
347
- *
348
- * Defaults to the authenticated principal. A consumer whose authorization depends
349
- * on more than identity — a tenant, an organisation, a workspace — supplies
350
- * `taskOwnerKey` so that dimension becomes part of the key. Without it, binding to
351
- * the subject alone leaves a task created under one tenant reachable from another
352
- * by the same user.
353
- */
354
- async function taskOwnerKeyFor(
355
- options: McpAppOptions,
356
- authInfo: AuthInfo | undefined,
357
- request: Request | undefined,
358
- principal: string,
359
- ): Promise<string | null> {
360
- if (options.taskOwnerKey === undefined || request === undefined) {
361
- return principal;
362
- }
363
- let key: unknown;
364
- try {
365
- key = await options.taskOwnerKey(authInfo, request);
366
- } catch {
367
- // A throwing hook is a consumer bug, but it must fail closed and legibly —
368
- // not escape to the POST-level catch and be reported as -32700 Parse error.
369
- return null;
370
- }
371
- // An empty or non-string key would put every caller under one owner, undoing
372
- // the isolation the hook exists to provide — and `""` is exactly what the
373
- // obvious implementation yields when a header is missing. Refuse it rather
374
- // than silently sharing tasks between callers.
375
- if (typeof key !== "string" || key.length === 0) return null;
376
- return key;
377
- }
378
-
379
- /** The error to return when `taskOwnerKey` produced an unusable value. */
380
- function noOwnerKeyError(id: unknown, version: string): Response {
381
- return jsonRpcResponse(
382
- {
383
- jsonrpc: "2.0",
384
- id,
385
- error: {
386
- code: ErrorCode.InternalError,
387
- message:
388
- "taskOwnerKey returned an empty or non-string value, which would place every caller under one owner.",
389
- data: {
390
- problem: "invalid_task_owner_key",
391
- recovery:
392
- 'Return a non-empty string. If the value it derives from can be absent, decide explicitly what an anonymous caller\'s key is rather than letting it fall to "".',
393
- },
394
- },
395
- },
396
- 500,
397
- { "MCP-Protocol-Version": version },
398
- );
399
- }
400
-
401
- /** The error to return when no caller boundary can be established. */
402
- function noPrincipalError(id: unknown, version: string): Response {
403
- return jsonRpcResponse(
404
- {
405
- jsonrpc: "2.0",
406
- id,
407
- error: {
408
- code: ErrorCode.InternalError,
409
- message:
410
- "Server cannot establish a caller identity: the auth provider returned no usable subject for an authenticated request.",
411
- data: {
412
- problem: "no_caller_principal",
413
- recovery:
414
- "Configure the auth provider to supply a subject claim, or disable auth if all callers genuinely share one authority.",
415
- },
416
- },
417
- },
418
- 500,
419
- { "MCP-Protocol-Version": version },
420
- );
421
- }
422
-
423
- /** Lowercase hex encoding, for the requestState nonce. */
424
- function bytesToHexLocal(bytes: Uint8Array): string {
425
- return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
426
- }
427
-
428
- /**
429
- * Build a JSON-RPC response with an explicit HTTP status.
430
- *
431
- * Module-scoped rather than nested in `startHttp`: request-validation helpers on
432
- * the class need it too, and duplicating the header defaults is how a response
433
- * ends up missing its Content-Type.
434
- */
435
- function jsonRpcResponse(
436
- payload: Record<string, unknown>,
437
- status: number,
438
- headers?: Record<string, string>,
439
- ): Response {
440
- return new Response(JSON.stringify(payload), {
441
- status,
442
- headers: {
443
- "Content-Type": "application/json",
444
- ...(headers ?? {}),
445
- },
446
- });
447
- }
448
-
449
- /**
450
- * Narrow type-guard: returns true iff `v` is a plain object (not array, not null).
451
- * Used to safely extract fields from JSON-RPC `params` without unsafe casts.
452
- */
453
- function isRecord(v: unknown): v is Record<string, unknown> {
454
- return typeof v === "object" && v !== null && !Array.isArray(v);
455
- }
456
-
457
243
  /**
458
244
  * Validate the client-owned subscriptions/listen filter before it reaches the
459
245
  * registry. The registry deliberately works with a typed SubscriptionFilter;
@@ -568,7 +354,6 @@ function canonicaliseWireResult(
568
354
  * - Wraps official @modelcontextprotocol/sdk
569
355
  * - Concurrency limiting (default: 10 max concurrent)
570
356
  * - Multiple backpressure strategies (sleep/queue/reject)
571
- * - Optional bidirectional sampling support
572
357
  * - Metrics for monitoring
573
358
  * - Graceful shutdown
574
359
  *
@@ -600,7 +385,6 @@ export class McpApp {
600
385
  private requestQueue: RequestQueue;
601
386
  private rateLimiter: RateLimiter | null = null;
602
387
  private schemaValidator: SchemaValidator | null = null;
603
- private samplingBridge: SamplingBridge | null = null;
604
388
  private tools = new Map<string, ToolWithHandler>();
605
389
 
606
390
  /**
@@ -633,11 +417,10 @@ export class McpApp {
633
417
  private stopping = false;
634
418
 
635
419
  /**
636
- * Live `subscriptions/listen` streams, or `null` outside stateless mode.
420
+ * Live `subscriptions/listen` streams.
637
421
  *
638
- * Core protocol rather than an extension, so it is unconditional on the
639
- * stateless path. The stateful transport keeps its own session-keyed SSE
640
- * machinery, which this replaces once that path is retired.
422
+ * Initialized unconditionally in startHttp(); null before the server starts
423
+ * or in stdio mode.
641
424
  */
642
425
  private subscriptions: SubscriptionRegistry | null = null;
643
426
 
@@ -659,6 +442,14 @@ export class McpApp {
659
442
  */
660
443
  private mrtrKeyPromise: Promise<CryptoKey | null> | null = null;
661
444
 
445
+ /**
446
+ * Consumes a verified requestState nonce before the handler runs.
447
+ *
448
+ * A signed deployment always has a store: process-local by default, or the
449
+ * shared atomic implementation supplied by the consumer.
450
+ */
451
+ private readonly mrtrReplayStore: MrtrReplayStore | null;
452
+
662
453
  /**
663
454
  * Validated `ttlMs`. The spec requires servers to provide a value `>= 0`, and
664
455
  * an integer — clients are told to ignore a negative one, which would make a
@@ -686,28 +477,21 @@ export class McpApp {
686
477
  // Observability
687
478
  private serverMetrics = new ServerMetrics();
688
479
 
689
- // Streamable HTTP session management
690
- private sessions = new Map<
691
- string,
692
- { createdAt: number; lastActivity: number }
693
- >();
694
- private sseClients = new Map<string, SSEClient[]>(); // sessionId -> clients
695
- private sessionCleanupTimer: ReturnType<typeof setInterval> | null = null;
696
- private static readonly SESSION_TTL_MS = 30 * 60 * 1000; // 30 minutes
697
- private static readonly SESSION_CLEANUP_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
698
- private static readonly SESSION_GRACE_PERIOD_MS = 60 * 1000; // 60s grace for in-flight requests
699
- private static readonly MAX_SESSIONS = 10_000;
700
-
701
- // Per-IP rate limiter for initialize requests (anti-session-exhaustion)
702
- private initRateLimiter = new RateLimiter({
703
- maxRequests: 10,
704
- windowMs: 60_000,
705
- });
706
-
707
480
  constructor(options: McpAppOptions) {
708
481
  this.options = options;
709
482
  this.name = options.name;
710
483
 
484
+ // enableSampling / samplingClient are no-ops since 0.24.0 (SamplingBridge
485
+ // was removed with MCP 2026-07-28). Warn loudly so migrating consumers
486
+ // know immediately rather than discovering it silently in production.
487
+ if (options.enableSampling || options.samplingClient) {
488
+ (options.logger ?? console.error)(
489
+ "[McpApp] WARNING: enableSampling and samplingClient have no effect " +
490
+ "as of 0.24.0 — the SamplingBridge was removed with MCP 2026-07-28. " +
491
+ "Remove these options from your McpApp constructor call.",
492
+ );
493
+ }
494
+
711
495
  const ttlMs = options.cache?.ttlMs ?? 0;
712
496
  if (!Number.isInteger(ttlMs) || ttlMs < 0) {
713
497
  throw new Error(
@@ -738,6 +522,23 @@ export class McpApp {
738
522
  "or the exported generateStateKey() + exportStateKey() helpers.",
739
523
  );
740
524
  }
525
+ if (
526
+ options.mrtr?.replayStore !== undefined && mrtrKey === undefined
527
+ ) {
528
+ throw new Error(
529
+ "[McpApp] mrtr.replayStore requires mrtr.signingKey. " +
530
+ "Only a verified token exposes a trusted nonce to consume.",
531
+ );
532
+ }
533
+ this.mrtrReplayStore = mrtrKey === undefined
534
+ ? null
535
+ : options.mrtr?.replayStore ?? new MemoryMrtrReplayStore();
536
+ if (mrtrKey !== undefined && options.mrtr?.replayStore === undefined) {
537
+ (options.logger ?? console.error)(
538
+ "[McpApp] WARNING: MRTR replay protection is process-local. " +
539
+ "Load-balanced deployments must configure one shared atomic mrtr.replayStore.",
540
+ );
541
+ }
741
542
 
742
543
  // Create SDK MCP server
743
544
  this.mcpServer = new McpServer(
@@ -773,27 +574,6 @@ export class McpApp {
773
574
  this.schemaValidator = new SchemaValidator();
774
575
  }
775
576
 
776
- // Optional sampling support
777
- if (options.enableSampling && options.samplingClient) {
778
- this.log(
779
- "[DEPRECATED] Sampling is deprecated (MCP 2026-07-28) and will be removed after 2027-07-28.",
780
- );
781
- if (options.transport === "stateless") {
782
- // Stronger than deprecation: the bridge sends a server-initiated
783
- // request, which 2026-07-28 removed outright. There is no channel for it
784
- // on this transport, so it cannot work — MRTR is the only legal path.
785
- // Said plainly here because the failure would otherwise appear as a
786
- // request that simply never gets answered.
787
- this.log(
788
- "[WARN] enableSampling has no effect on the stateless transport: " +
789
- "spec 2026-07-28 removed server-initiated requests. Return an " +
790
- "InputRequiredResult with a sampling/createMessage inputRequest " +
791
- "(MRTR) instead.",
792
- );
793
- }
794
- this.samplingBridge = new SamplingBridge(options.samplingClient);
795
- }
796
-
797
577
  // Setup MCP protocol handlers
798
578
  this.setupHandlers();
799
579
 
@@ -1240,8 +1020,6 @@ export class McpApp {
1240
1020
  this.serverMetrics.setGauges({
1241
1021
  activeRequests: queueMetrics.inFlight,
1242
1022
  queuedRequests: queueMetrics.queued,
1243
- activeSessions: this.sessions.size,
1244
- sseClients: this.getSSEClientCount(),
1245
1023
  rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
1246
1024
  });
1247
1025
 
@@ -1547,42 +1325,6 @@ export class McpApp {
1547
1325
  this.log(`Tools available: ${this.tools.size}`);
1548
1326
  }
1549
1327
 
1550
- /**
1551
- * Clean up expired sessions to prevent memory leaks.
1552
- * Removes sessions that haven't had activity within SESSION_TTL_MS.
1553
- */
1554
- private cleanupSessions(): void {
1555
- const now = Date.now();
1556
- const ttlWithGrace = McpApp.SESSION_TTL_MS +
1557
- McpApp.SESSION_GRACE_PERIOD_MS;
1558
- let cleaned = 0;
1559
- for (const [sessionId, session] of this.sessions) {
1560
- if (now - session.lastActivity > ttlWithGrace) {
1561
- this.sessions.delete(sessionId);
1562
- // Also clean up SSE clients for this session
1563
- const clients = this.sseClients.get(sessionId);
1564
- if (clients) {
1565
- for (const client of clients) {
1566
- try {
1567
- client.controller.close();
1568
- } catch { /* already closed */ }
1569
- }
1570
- this.sseClients.delete(sessionId);
1571
- }
1572
- cleaned++;
1573
- }
1574
- }
1575
- if (cleaned > 0) {
1576
- this.serverMetrics.recordSessionExpired(cleaned);
1577
- this.log(
1578
- `Session cleanup: removed ${cleaned} expired sessions (${this.sessions.size} remaining)`,
1579
- );
1580
- }
1581
- }
1582
-
1583
- /**
1584
- * Stop the server gracefully
1585
- */
1586
1328
  /**
1587
1329
  * Restore the invariants a running server relies on.
1588
1330
  *
@@ -1632,29 +1374,6 @@ export class McpApp {
1632
1374
  return;
1633
1375
  }
1634
1376
 
1635
- // Stop session cleanup timer
1636
- if (this.sessionCleanupTimer) {
1637
- clearInterval(this.sessionCleanupTimer);
1638
- this.sessionCleanupTimer = null;
1639
- }
1640
-
1641
- // Cancel pending sampling requests
1642
- if (this.samplingBridge) {
1643
- this.samplingBridge.cancelAll();
1644
- }
1645
-
1646
- // Close all SSE clients BEFORE shutting down HTTP server.
1647
- // Deno.serve().shutdown() waits for all connections to drain,
1648
- // so long-lived SSE connections must be closed first to avoid blocking.
1649
- for (const [sessionId, clients] of this.sseClients) {
1650
- for (const client of clients) {
1651
- try {
1652
- client.controller.close();
1653
- } catch { /* already closed */ }
1654
- }
1655
- this.sseClients.delete(sessionId);
1656
- }
1657
-
1658
1377
  // Stop HTTP server if running
1659
1378
  if (this.httpServer) {
1660
1379
  await this.httpServer.shutdown();
@@ -1739,14 +1458,10 @@ export class McpApp {
1739
1458
  const hostname = options.hostname ?? "0.0.0.0";
1740
1459
  this.prepareForStart();
1741
1460
 
1742
- if (this.options.transport === "stateless" && this.subscriptions === null) {
1461
+ if (this.subscriptions === null) {
1743
1462
  this.subscriptions = new SubscriptionRegistry({
1744
1463
  serverInfo: { name: this.options.name, version: this.options.version },
1745
1464
  });
1746
- // Unref'd: a keep-alive ticker must not by itself hold the process open.
1747
- // The cast matches the existing session-timer call sites — `UnrefTimerFn`
1748
- // is typed for Deno's numeric handle, while Node's `setInterval` returns a
1749
- // Timeout object.
1750
1465
  this.subscriptions.startKeepAlive(
1751
1466
  setInterval,
1752
1467
  (id) => unrefTimer(id as unknown as number),
@@ -1789,9 +1504,7 @@ export class McpApp {
1789
1504
  "Content-Type",
1790
1505
  "Accept",
1791
1506
  "Authorization",
1792
- "mcp-session-id",
1793
1507
  "mcp-protocol-version",
1794
- "last-event-id",
1795
1508
  // Spec 2026-07-28 request-metadata headers. Omitting them broke
1796
1509
  // browser clients outright: the preflight rejects the actual request
1797
1510
  // before the server ever sees it, so a conforming client could not
@@ -1811,7 +1524,6 @@ export class McpApp {
1811
1524
  ],
1812
1525
  exposeHeaders: [
1813
1526
  "Content-Length",
1814
- "mcp-session-id",
1815
1527
  "mcp-protocol-version",
1816
1528
  ],
1817
1529
  maxAge: 600,
@@ -1837,8 +1549,6 @@ export class McpApp {
1837
1549
  this.serverMetrics.setGauges({
1838
1550
  activeRequests: qm.inFlight,
1839
1551
  queuedRequests: qm.queued,
1840
- activeSessions: this.sessions.size,
1841
- sseClients: this.getSSEClientCount(),
1842
1552
  rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
1843
1553
  });
1844
1554
  return new Response(this.serverMetrics.toPrometheusFormat(), {
@@ -1951,105 +1661,18 @@ export class McpApp {
1951
1661
  }
1952
1662
  }
1953
1663
 
1954
- // MCP endpoint - GET opens SSE stream for server→client messages (Streamable HTTP spec)
1955
- // deno-lint-ignore no-explicit-any
1956
- const handleMcpGet = async (c: any) => {
1957
- // Track A: stateless V2 — SSE channel not applicable (Track B replaces it)
1958
- if (this.options.transport === "stateless") {
1959
- return c.text("Method Not Allowed", 405);
1960
- }
1961
-
1962
- const accept = c.req.header("accept") ?? "";
1963
- const sessionId = c.req.header("mcp-session-id");
1964
- const lastEventId = c.req.header("last-event-id");
1965
-
1966
- const rateLimit = await checkHttpRateLimit(c.req.raw, sessionId);
1967
- if (!rateLimit.allowed) {
1968
- const retryAfter = Math.max(
1969
- 1,
1970
- Math.ceil(rateLimit.retryAfterMs / 1000),
1971
- );
1972
- return new Response(
1973
- `Rate limit exceeded. Retry after ${retryAfter}s`,
1974
- {
1975
- status: 429,
1976
- headers: { "Retry-After": retryAfter.toString() },
1977
- },
1978
- );
1979
- }
1980
-
1981
- // Check if client accepts SSE
1982
- if (!accept.includes("text/event-stream")) {
1983
- return c.text("Method Not Allowed", 405);
1984
- }
1985
-
1986
- // Auth gate: SSE connections require valid token when auth is configured
1987
- const sseAuthResult = await verifyHttpAuth(c.req.raw);
1988
- if ("denied" in sseAuthResult) return sseAuthResult.denied;
1989
-
1990
- // Validate session if provided
1991
- if (sessionId && !this.sessions.has(sessionId)) {
1992
- return c.text("Session not found", 404);
1993
- }
1994
-
1995
- // Create SSE stream
1996
- const encoder = new TextEncoder();
1997
- let sseClient: SSEClient | null = null;
1998
-
1999
- const stream = new ReadableStream<Uint8Array>({
2000
- start: (controller) => {
2001
- const clientSessionId = sessionId ?? "anonymous";
2002
- const parsedEventId = lastEventId ? parseInt(lastEventId, 10) : 0;
2003
- sseClient = {
2004
- sessionId: clientSessionId,
2005
- controller,
2006
- createdAt: Date.now(),
2007
- lastEventId: Number.isNaN(parsedEventId) ? 0 : parsedEventId,
2008
- };
2009
-
2010
- // Register client
2011
- if (!this.sseClients.has(clientSessionId)) {
2012
- this.sseClients.set(clientSessionId, []);
2013
- }
2014
- this.sseClients.get(clientSessionId)!.push(sseClient);
2015
-
2016
- this.log(`SSE client connected (session: ${clientSessionId})`);
2017
-
2018
- // Send initial comment to establish connection
2019
- controller.enqueue(encoder.encode(": connected\n\n"));
2020
- },
2021
- cancel: () => {
2022
- // Remove client on disconnect
2023
- if (sseClient) {
2024
- const clients = this.sseClients.get(sseClient.sessionId);
2025
- if (clients) {
2026
- const idx = clients.indexOf(sseClient);
2027
- if (idx !== -1) clients.splice(idx, 1);
2028
- if (clients.length === 0) {
2029
- this.sseClients.delete(sseClient.sessionId);
2030
- }
2031
- }
2032
- this.log(
2033
- `SSE client disconnected (session: ${sseClient.sessionId})`,
2034
- );
2035
- }
2036
- },
2037
- });
2038
-
2039
- return new Response(stream, {
2040
- headers: {
2041
- "Content-Type": "text/event-stream",
2042
- "Cache-Control": "no-cache",
2043
- "Connection": "keep-alive",
2044
- ...(sessionId ? { "Mcp-Session-Id": sessionId } : {}),
2045
- },
2046
- });
2047
- };
2048
-
1664
+ // Legacy verbs from 2025-03-26..2025-11-25: GET opened a standalone SSE
1665
+ // stream, DELETE terminated a session. Neither exists in this revision, and
1666
+ // the spec says a server supporting only this revision SHOULD answer both
1667
+ // with 405 — not 404, which an older client would read as "no MCP endpoint
1668
+ // here" and use to fall back to the deprecated HTTP+SSE transport.
1669
+ // Use subscriptions/listen for server-initiated notifications.
2049
1670
  // deno-lint-ignore no-explicit-any
2050
- app.get("/mcp", handleMcpGet as any);
2051
- // deno-lint-ignore no-explicit-any
2052
- app.get("/", handleMcpGet as any);
1671
+ const methodNotAllowed = (c: any) => c.text("Method Not Allowed", 405);
1672
+ app.get("/mcp", methodNotAllowed);
1673
+ app.get("/", methodNotAllowed);
1674
+ app.delete("/mcp", methodNotAllowed);
1675
+ app.delete("/", methodNotAllowed);
2053
1676
 
2054
1677
  // MCP endpoint - POST handles JSON-RPC
2055
1678
  const handleMcpPost = async (
@@ -2066,23 +1689,16 @@ export class McpApp {
2066
1689
  ) => {
2067
1690
  let requestId: string | number | null = null;
2068
1691
  try {
2069
- // Track A: in stateless mode, ignore Mcp-Session-Id so it cannot be used
2070
- // as a rate-limit key (session bypass attack surface removed).
2071
- const reqSessionId = this.options.transport === "stateless"
2072
- ? undefined
2073
- : c.req.header("mcp-session-id");
2074
- // Track A: strip mcp-session-id from headers passed to rate-limit context
2075
- // so a keyExtractor cannot use rotating session IDs to bypass IP-level limits.
2076
- const rlHeaders = this.options.transport === "stateless"
2077
- ? (() => {
2078
- const h = new Headers(c.req.raw.headers);
2079
- h.delete("mcp-session-id");
2080
- return h;
2081
- })()
2082
- : undefined;
1692
+ // Strip mcp-session-id from headers passed to rate-limit context
1693
+ // so a keyExtractor cannot use session IDs to bypass IP-level limits.
1694
+ const rlHeaders = (() => {
1695
+ const h = new Headers(c.req.raw.headers);
1696
+ h.delete("mcp-session-id");
1697
+ return h;
1698
+ })();
2083
1699
  const rateLimit = await checkHttpRateLimit(
2084
1700
  c.req.raw,
2085
- reqSessionId,
1701
+ undefined,
2086
1702
  rlHeaders,
2087
1703
  );
2088
1704
  if (!rateLimit.allowed) {
@@ -2147,207 +1763,167 @@ export class McpApp {
2147
1763
  httpAuthInfo = authResult.authInfo;
2148
1764
  }
2149
1765
 
2150
- // Track A: per-request protocolVersion validation in stateless mode.
1766
+ // The `MCP-Protocol-Version` header is REQUIRED on every POST, and its
1767
+ // absence is a header-validation failure — not a malformed body. The
1768
+ // spec is explicit: "Validation failure conditions include: A required
1769
+ // standard header (MCP-Protocol-Version, Mcp-Method, Mcp-Name) is
1770
+ // missing", answered with 400 + -32020 (HeaderMismatch).
1771
+ //
1772
+ // This has to run BEFORE the `_meta` version check below, because a
1773
+ // legacy client sends neither and would otherwise get -32602 for a
1774
+ // missing body field when the primary violation is the missing header.
1775
+ // A client reading -32602 looks for the wrong fix.
1776
+ //
1777
+ // Notifications are exempt: the revision leaves header requirements for
1778
+ // notification POSTs undefined, so demanding one there invents a rule.
1779
+ if (
1780
+ id !== undefined && c.req.header("MCP-Protocol-Version") === undefined
1781
+ ) {
1782
+ return jsonRpcResponse(
1783
+ {
1784
+ jsonrpc: "2.0",
1785
+ id,
1786
+ error: {
1787
+ code: MCP_HEADER_MISMATCH,
1788
+ message:
1789
+ "Missing required header 'MCP-Protocol-Version'. It must be present and match params._meta['io.modelcontextprotocol/protocolVersion'].",
1790
+ data: {
1791
+ problem: "missing_header",
1792
+ header: "MCP-Protocol-Version",
1793
+ recovery:
1794
+ "Send MCP-Protocol-Version: 2026-07-28 and the matching _meta field.",
1795
+ },
1796
+ },
1797
+ },
1798
+ 400,
1799
+ { "MCP-Protocol-Version": SPEC_2026_07_28 },
1800
+ );
1801
+ }
1802
+
1803
+ // Per-request protocolVersion validation (spec 2026-07-28).
2151
1804
  // Must run BEFORE any method dispatch so every call (not just initialize)
2152
1805
  // is validated. Sets MCP-Protocol-Version header on all subsequent responses
2153
1806
  // via Hono's c.header() accumulation.
2154
1807
  // Key location: params._meta[STATELESS_PROTO_KEY] (SEP-2575 Final).
2155
- // Tolerant mode: MCP-Protocol-Version may be absent for backward compatibility;
2156
- // when present it must match the _meta version.
2157
- let statelessVersion: string | undefined;
2158
- if (this.options.transport === "stateless") {
2159
- const clientVersion = isRecord(params) && isRecord(params["_meta"])
2160
- ? params["_meta"][STATELESS_PROTO_KEY]
2161
- : undefined;
1808
+ const clientVersion = isRecord(params) && isRecord(params["_meta"])
1809
+ ? params["_meta"][STATELESS_PROTO_KEY]
1810
+ : undefined;
2162
1811
 
2163
- // `clientCapabilities` is a REQUIRED per-request `_meta` field in the
2164
- // final spec (`clientInfo` is not — it is only SHOULD). A request
2165
- // missing a required field is malformed: -32602 + HTTP 400.
2166
- //
2167
- // Checked after the version so a client on an older revision, which
2168
- // never had this field, still gets the clearer version error first.
2169
- // Must be an OBJECT, not merely present. `!== undefined` accepted
2170
- // `null`, a scalar or an array, which then reached the handler as a
2171
- // supposed ClientCapabilities and failed later as -32603 — an internal
2172
- // error for what is plainly a malformed request.
2173
- const capabilitiesValid = isRecord(params) &&
2174
- isRecord(params["_meta"]) &&
2175
- isRecord(params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY]);
2176
-
2177
- if (typeof clientVersion !== "string") {
2178
- // Header uses fallback version — no negotiated version available yet
2179
- return jsonRpcResponse(
2180
- {
2181
- jsonrpc: "2.0",
2182
- id,
2183
- error: {
2184
- code: JSONRPC_INVALID_PARAMS,
2185
- message: `Missing required field '${STATELESS_PROTO_KEY}'`,
1812
+ // `clientCapabilities` is a REQUIRED per-request `_meta` field in the
1813
+ // final spec (`clientInfo` is not — it is only SHOULD). A request
1814
+ // missing a required field is malformed: -32602 + HTTP 400.
1815
+ //
1816
+ // Checked after the version so a client on an unsupported revision
1817
+ // gets the clearer version error first.
1818
+ // Must be an OBJECT, not merely present. `!== undefined` accepted
1819
+ // `null`, a scalar or an array, which then reached the handler as a
1820
+ // supposed ClientCapabilities and failed later as -32603 — an internal
1821
+ // error for what is plainly a malformed request.
1822
+ const capabilitiesValid = isRecord(params) &&
1823
+ isRecord(params["_meta"]) &&
1824
+ isRecord(params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY]);
1825
+
1826
+ if (typeof clientVersion !== "string") {
1827
+ // Header uses fallback version — no negotiated version available yet
1828
+ return jsonRpcResponse(
1829
+ {
1830
+ jsonrpc: "2.0",
1831
+ id,
1832
+ error: {
1833
+ code: JSONRPC_INVALID_PARAMS,
1834
+ message: `Missing required field '${STATELESS_PROTO_KEY}'`,
1835
+ },
1836
+ },
1837
+ 400,
1838
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1839
+ );
1840
+ }
1841
+
1842
+ if (!STATELESS_SUPPORTED_VERSIONS.includes(clientVersion)) {
1843
+ // AX: data carries machine-readable supported/requested for agent recovery
1844
+ return jsonRpcResponse(
1845
+ {
1846
+ jsonrpc: "2.0",
1847
+ id,
1848
+ error: {
1849
+ code: MCP_UNSUPPORTED_PROTOCOL_VERSION,
1850
+ message: `Unsupported protocolVersion: "${clientVersion}"`,
1851
+ data: {
1852
+ supported: [...STATELESS_SUPPORTED_VERSIONS],
1853
+ requested: clientVersion,
2186
1854
  },
2187
1855
  },
2188
- 400,
2189
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2190
- );
2191
- }
1856
+ },
1857
+ 400,
1858
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1859
+ );
1860
+ }
2192
1861
 
2193
- if (!STATELESS_SUPPORTED_VERSIONS.includes(clientVersion)) {
2194
- // AX: data carries machine-readable supported/requested for agent recovery
2195
- return jsonRpcResponse(
2196
- {
2197
- jsonrpc: "2.0",
2198
- id,
2199
- error: {
2200
- code: MCP_UNSUPPORTED_PROTOCOL_VERSION,
2201
- message: `Unsupported protocolVersion: "${clientVersion}"`,
2202
- data: {
2203
- supported: [...STATELESS_SUPPORTED_VERSIONS],
2204
- requested: clientVersion,
2205
- },
1862
+ if (!capabilitiesValid) {
1863
+ return jsonRpcResponse(
1864
+ {
1865
+ jsonrpc: "2.0",
1866
+ id,
1867
+ error: {
1868
+ code: JSONRPC_INVALID_PARAMS,
1869
+ message:
1870
+ `Missing or malformed field '${STATELESS_CLIENT_CAPABILITIES_KEY}' in params._meta: expected an object`,
1871
+ data: {
1872
+ problem: "missing_field",
1873
+ bodyField:
1874
+ `params._meta['${STATELESS_CLIENT_CAPABILITIES_KEY}']`,
1875
+ recovery:
1876
+ "Send a ClientCapabilities object; `{}` is valid and means no capabilities declared.",
2206
1877
  },
2207
1878
  },
2208
- 400,
2209
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2210
- );
2211
- }
1879
+ },
1880
+ 400,
1881
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1882
+ );
1883
+ }
2212
1884
 
2213
- if (clientVersion === SPEC_2026_07_28 && !capabilitiesValid) {
1885
+ // Track C: request-metadata headers (SEP-2243).
1886
+ //
1887
+ // Notifications are exempt: the revision explicitly leaves header
1888
+ // requirements for notification POSTs undefined, so a missing
1889
+ // `Mcp-Method` there is not a violation to invent.
1890
+ if (id !== undefined) {
1891
+ const validation = validateRequestHeaders({
1892
+ getHeader: (name) => c.req.header(name),
1893
+ method: typeof method === "string" ? method : "",
1894
+ params: isRecord(params) ? params : undefined,
1895
+ bodyProtocolVersion: clientVersion,
1896
+ mirroredParams: typeof params?.name === "string"
1897
+ ? this.mirroredParams.get(params.name)
1898
+ : undefined,
1899
+ });
1900
+ if (!validation.ok) {
2214
1901
  return jsonRpcResponse(
2215
1902
  {
2216
1903
  jsonrpc: "2.0",
2217
1904
  id,
2218
1905
  error: {
2219
- code: JSONRPC_INVALID_PARAMS,
2220
- message:
2221
- `Missing or malformed field '${STATELESS_CLIENT_CAPABILITIES_KEY}' in params._meta: expected an object`,
2222
- data: {
2223
- problem: "missing_field",
2224
- bodyField:
2225
- `params._meta['${STATELESS_CLIENT_CAPABILITIES_KEY}']`,
2226
- recovery:
2227
- "Send a ClientCapabilities object; `{}` is valid and means no capabilities declared.",
2228
- },
1906
+ code: MCP_HEADER_MISMATCH,
1907
+ message: validation.message,
1908
+ // AX: the caller has to fix the request, so what to fix
1909
+ // travels as data. `problem` is an enum to switch on,
1910
+ // `recovery` is one concrete action — neither requires
1911
+ // parsing the English message.
1912
+ data: validation.detail,
2229
1913
  },
2230
1914
  },
2231
1915
  400,
2232
1916
  { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2233
1917
  );
2234
1918
  }
2235
-
2236
- // Track C: request-metadata headers (SEP-2243).
2237
- //
2238
- // Enforced only for peers that negotiated 2026-07-28 — `Mcp-Method`
2239
- // and `Mcp-Name` do not exist in earlier revisions, so demanding them
2240
- // from a 2025-11-25 client would reject a conforming request.
2241
- //
2242
- // Notifications are exempt: the revision explicitly leaves header
2243
- // requirements for notification POSTs undefined, so a missing
2244
- // `Mcp-Method` there is not a violation to invent.
2245
- if (clientVersion === SPEC_2026_07_28 && id !== undefined) {
2246
- const validation = validateRequestHeaders({
2247
- getHeader: (name) => c.req.header(name),
2248
- method: typeof method === "string" ? method : "",
2249
- params: isRecord(params) ? params : undefined,
2250
- bodyProtocolVersion: clientVersion,
2251
- mirroredParams: typeof params?.name === "string"
2252
- ? this.mirroredParams.get(params.name)
2253
- : undefined,
2254
- });
2255
- if (!validation.ok) {
2256
- return jsonRpcResponse(
2257
- {
2258
- jsonrpc: "2.0",
2259
- id,
2260
- error: {
2261
- code: MCP_HEADER_MISMATCH,
2262
- message: validation.message,
2263
- // AX: the caller has to fix the request, so what to fix
2264
- // travels as data. `problem` is an enum to switch on,
2265
- // `recovery` is one concrete action — neither requires
2266
- // parsing the English message.
2267
- data: validation.detail,
2268
- },
2269
- },
2270
- 400,
2271
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2272
- );
2273
- }
2274
- } else if (id !== undefined) {
2275
- // Pre-2026 peer: `Mcp-Method` / `Mcp-Name` did not exist yet, so they
2276
- // are not demanded. `MCP-Protocol-Version` DID — it was introduced in
2277
- // 2025-06-18, and the spec grants the omit-the-header grace only to
2278
- // clients older than that, which this server does not support
2279
- // (STATELESS_SUPPORTED_VERSIONS starts at 2025-06-18). So it stays
2280
- // required here, and must agree with the body when present.
2281
- //
2282
- // Notifications fall through untouched: the revision states outright
2283
- // that header requirements for notification POSTs are undefined, so
2284
- // there is no rule here to enforce and none to invent. Their `_meta`
2285
- // protocolVersion was already validated above.
2286
- const headerVersion = c.req.header("MCP-Protocol-Version");
2287
- if (headerVersion === undefined) {
2288
- return jsonRpcResponse(
2289
- {
2290
- jsonrpc: "2.0",
2291
- id,
2292
- error: {
2293
- code: MCP_HEADER_MISMATCH,
2294
- message:
2295
- "Missing required header 'MCP-Protocol-Version' (required since protocol version 2025-06-18)",
2296
- data: {
2297
- problem: "missing_header",
2298
- header: "MCP-Protocol-Version",
2299
- expected: clientVersion,
2300
- bodyField:
2301
- "params._meta['io.modelcontextprotocol/protocolVersion']",
2302
- recovery:
2303
- `Send the header 'MCP-Protocol-Version: ${clientVersion}' on every POST.`,
2304
- },
2305
- },
2306
- },
2307
- 400,
2308
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2309
- );
2310
- }
2311
- if (headerVersion !== clientVersion) {
2312
- return jsonRpcResponse(
2313
- {
2314
- jsonrpc: "2.0",
2315
- id,
2316
- error: {
2317
- // A header disagreeing with the body is HeaderMismatch, not
2318
- // InvalidParams: intermediaries routing on the header need
2319
- // to know the divergence was detected.
2320
- code: MCP_HEADER_MISMATCH,
2321
- message:
2322
- `MCP-Protocol-Version header "${headerVersion}" does not match _meta protocolVersion "${clientVersion}"`,
2323
- data: {
2324
- problem: "header_body_mismatch",
2325
- header: "MCP-Protocol-Version",
2326
- expected: clientVersion,
2327
- received: headerVersion,
2328
- bodyField:
2329
- "params._meta['io.modelcontextprotocol/protocolVersion']",
2330
- recovery:
2331
- `Set the header to "${clientVersion}", or change the body's _meta to "${headerVersion}". They must agree.`,
2332
- },
2333
- },
2334
- },
2335
- 400,
2336
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2337
- );
2338
- }
2339
- }
2340
-
2341
- statelessVersion = clientVersion;
2342
- // Spec 2026-07-28: echo negotiated version in every response header.
2343
- // c.header() accumulates headers — all subsequent c.json() calls inherit it.
2344
- c.header("MCP-Protocol-Version", statelessVersion);
2345
1919
  }
2346
1920
 
2347
- if (
2348
- method === "server/discover" &&
2349
- this.options.transport === "stateless"
2350
- ) {
1921
+ const statelessVersion: string = clientVersion;
1922
+ // Spec 2026-07-28: echo negotiated version in every response header.
1923
+ // c.header() accumulates headers — all subsequent c.json() calls inherit it.
1924
+ c.header("MCP-Protocol-Version", statelessVersion);
1925
+
1926
+ if (method === "server/discover") {
2351
1927
  return c.json({
2352
1928
  jsonrpc: "2.0",
2353
1929
  id,
@@ -2368,108 +1944,26 @@ export class McpApp {
2368
1944
  });
2369
1945
  }
2370
1946
 
2371
- // Initialize - create session and return session ID (now auth-verified)
1947
+ // Initialize — respond without creating a session or emitting Mcp-Session-Id.
1948
+ // statelessVersion is guaranteed defined here (version check above returned early otherwise).
2372
1949
  if (method === "initialize") {
2373
- // Track A: stateless V2 — respond without creating a session or emitting Mcp-Session-Id.
2374
- // statelessVersion is guaranteed defined here (per-request block above returned early otherwise).
2375
- if (this.options.transport === "stateless") {
2376
- return c.json({
2377
- jsonrpc: "2.0",
2378
- id,
2379
- result: this.stampResult({
2380
- protocolVersion: statelessVersion as string,
2381
- capabilities: this.buildServerCapabilities(),
2382
- serverInfo: {
2383
- name: this.options.name,
2384
- version: this.options.version,
2385
- },
2386
- ...(this.options.instructions
2387
- ? { instructions: this.options.instructions }
2388
- : {}),
2389
- }, statelessVersion),
2390
- });
2391
- // Note: c.json() inherits MCP-Protocol-Version header set above.
2392
- // No Mcp-Session-Id header emitted — stateless by design.
2393
- }
2394
-
2395
- // Per-IP rate limit on initialize to prevent session exhaustion attacks
2396
- const clientIp = getClientIpFromHeaders(c.req.raw.headers);
2397
- if (!this.initRateLimiter.checkLimit(clientIp)) {
2398
- return c.json({
2399
- jsonrpc: "2.0",
2400
- id,
2401
- error: {
2402
- code: -32000,
2403
- message: "Too many initialize requests. Try again later.",
2404
- },
2405
- }, 429);
2406
- }
2407
-
2408
- // Guard against session exhaustion
2409
- if (this.sessions.size >= McpApp.MAX_SESSIONS) {
2410
- this.cleanupSessions();
2411
- if (this.sessions.size >= McpApp.MAX_SESSIONS) {
2412
- return c.json({
2413
- jsonrpc: "2.0",
2414
- id,
2415
- error: { code: -32000, message: "Too many active sessions" },
2416
- }, 503);
2417
- }
2418
- }
2419
- const sessionId = generateSessionId();
2420
- const now = Date.now();
2421
- this.sessions.set(sessionId, { createdAt: now, lastActivity: now });
2422
- this.serverMetrics.recordSessionCreated();
2423
-
2424
- this.log(`New session created: ${sessionId}`);
2425
-
2426
- return new Response(
2427
- JSON.stringify({
2428
- jsonrpc: "2.0",
2429
- id,
2430
- result: {
2431
- protocolVersion: "2025-06-18",
2432
- capabilities: {
2433
- tools: {},
2434
- resources: this.resources.size > 0 ? {} : undefined,
2435
- },
2436
- serverInfo: {
2437
- name: this.options.name,
2438
- version: this.options.version,
2439
- },
2440
- ...(this.options.instructions
2441
- ? { instructions: this.options.instructions }
2442
- : {}),
2443
- },
2444
- }),
2445
- {
2446
- headers: {
2447
- "Content-Type": "application/json",
2448
- "Mcp-Session-Id": sessionId,
2449
- },
2450
- },
2451
- );
2452
- }
2453
-
2454
- // Session validation: all methods after initialize must provide a valid session.
2455
- // Skipped in stateless V2 mode (Track A) — no session concept.
2456
- if (this.options.transport !== "stateless" && reqSessionId) {
2457
- const session = this.sessions.get(reqSessionId);
2458
- if (!session) {
2459
- return c.json({
2460
- jsonrpc: "2.0",
2461
- id,
2462
- error: {
2463
- // Stateful path only (sessions do not exist in 2026-07-28), but
2464
- // -32001 is in the sub-range new implementations SHOULD NOT use,
2465
- // so it moves out alongside the auth codes.
2466
- code: -31404,
2467
- message: "Session not found or expired",
1950
+ return c.json({
1951
+ jsonrpc: "2.0",
1952
+ id,
1953
+ result: this.stampResult({
1954
+ protocolVersion: statelessVersion,
1955
+ capabilities: this.buildServerCapabilities(),
1956
+ serverInfo: {
1957
+ name: this.options.name,
1958
+ version: this.options.version,
2468
1959
  },
2469
- }, 404);
2470
- }
2471
- // Update last activity to prevent premature cleanup
2472
- session.lastActivity = Date.now();
1960
+ ...(this.options.instructions
1961
+ ? { instructions: this.options.instructions }
1962
+ : {}),
1963
+ }, statelessVersion),
1964
+ });
1965
+ // Note: c.json() inherits MCP-Protocol-Version header set above.
1966
+ // No Mcp-Session-Id header emitted — stateless by design.
2473
1967
  }
2474
1968
 
2475
1969
  // Tools call (delegates to middleware pipeline, which handles auth internally)
@@ -2502,9 +1996,7 @@ export class McpApp {
2502
1996
  {};
2503
1997
  const statelessClientMeta:
2504
1998
  | StatelessClientMeta
2505
- | undefined = this.options.transport === "stateless" &&
2506
- isRecord(params) &&
2507
- isRecord(params["_meta"])
1999
+ | undefined = isRecord(params) && isRecord(params["_meta"])
2508
2000
  ? {
2509
2001
  clientInfo: params["_meta"][STATELESS_CLIENT_INFO_KEY] as
2510
2002
  | Implementation
@@ -2520,11 +2012,8 @@ export class McpApp {
2520
2012
  // not members of it, unlike every other per-request field. Reading them
2521
2013
  // from `_meta` yields a silent undefined even when the client sent them.
2522
2014
  //
2523
- // Confined to a negotiated 2026-07-28: MRTR replaces the
2524
- // server-initiated request pattern that earlier revisions still use, so
2525
- // it has no meaning on the legacy path — and the client capabilities it
2526
- // needs only arrive per-request there.
2527
- const mrtrEnabled = statelessVersion === SPEC_2026_07_28;
2015
+ // MRTR is always enabled on 2026-07-28 (the only supported version).
2016
+ const mrtrEnabled = true;
2528
2017
 
2529
2018
  // Digest of the arguments AS RECEIVED, taken before the middleware
2530
2019
  // pipeline runs. Re-deriving it at seal time would hash whatever the
@@ -2559,8 +2048,7 @@ export class McpApp {
2559
2048
  },
2560
2049
  400,
2561
2050
  {
2562
- "MCP-Protocol-Version": statelessVersion ??
2563
- STATELESS_FALLBACK_VERSION,
2051
+ "MCP-Protocol-Version": statelessVersion,
2564
2052
  },
2565
2053
  );
2566
2054
  }
@@ -2587,7 +2075,7 @@ export class McpApp {
2587
2075
  const guardKey = needsKey
2588
2076
  ? await this.getMrtrKeySafe(
2589
2077
  id,
2590
- statelessVersion ?? STATELESS_FALLBACK_VERSION,
2078
+ statelessVersion,
2591
2079
  )
2592
2080
  : { key: null as CryptoKey | null };
2593
2081
  if ("error" in guardKey) return guardKey.error;
@@ -2612,8 +2100,7 @@ export class McpApp {
2612
2100
  },
2613
2101
  400,
2614
2102
  {
2615
- "MCP-Protocol-Version": statelessVersion ??
2616
- STATELESS_FALLBACK_VERSION,
2103
+ "MCP-Protocol-Version": statelessVersion,
2617
2104
  },
2618
2105
  );
2619
2106
  }
@@ -2635,7 +2122,7 @@ export class McpApp {
2635
2122
  if (principal === null) {
2636
2123
  return noPrincipalError(
2637
2124
  id,
2638
- statelessVersion ?? STATELESS_FALLBACK_VERSION,
2125
+ statelessVersion,
2639
2126
  );
2640
2127
  }
2641
2128
  const verdict = await verifyRequestState(echoedState, key, {
@@ -2661,6 +2148,77 @@ export class McpApp {
2661
2148
  400,
2662
2149
  );
2663
2150
  }
2151
+
2152
+ const replayStore = this.mrtrReplayStore;
2153
+ if (replayStore === null) {
2154
+ return jsonRpcResponse(
2155
+ {
2156
+ jsonrpc: "2.0",
2157
+ id,
2158
+ error: {
2159
+ code: ErrorCode.InternalError,
2160
+ message: "MRTR replay protection is unavailable",
2161
+ data: {
2162
+ problem: "mrtr_replay_store_unavailable",
2163
+ recovery:
2164
+ "Configure mrtr.signingKey with a working replay store and retry the full interaction.",
2165
+ },
2166
+ },
2167
+ },
2168
+ 500,
2169
+ { "MCP-Protocol-Version": statelessVersion },
2170
+ );
2171
+ }
2172
+
2173
+ let consumed: boolean;
2174
+ try {
2175
+ const storeResult = await replayStore.consume(
2176
+ verdict.payload.nonce,
2177
+ verdict.payload.exp,
2178
+ );
2179
+ if (storeResult !== true && storeResult !== false) {
2180
+ throw new Error(
2181
+ "mrtr.replayStore.consume() must return a boolean",
2182
+ );
2183
+ }
2184
+ consumed = storeResult;
2185
+ } catch {
2186
+ this.log(
2187
+ "[WARN] MRTR replay store unavailable; retry rejected before handler",
2188
+ );
2189
+ return jsonRpcResponse(
2190
+ {
2191
+ jsonrpc: "2.0",
2192
+ id,
2193
+ error: {
2194
+ code: ErrorCode.InternalError,
2195
+ message: "MRTR replay protection is unavailable",
2196
+ data: {
2197
+ problem: "mrtr_replay_store_unavailable",
2198
+ recovery:
2199
+ "Restore the shared replay store, then restart the interaction to obtain a fresh requestState.",
2200
+ },
2201
+ },
2202
+ },
2203
+ 500,
2204
+ { "MCP-Protocol-Version": statelessVersion },
2205
+ );
2206
+ }
2207
+ if (!consumed) {
2208
+ return jsonRpcResponse(
2209
+ {
2210
+ jsonrpc: "2.0",
2211
+ id,
2212
+ error: {
2213
+ code: JSONRPC_INVALID_PARAMS,
2214
+ message: "Invalid requestState: replayed",
2215
+ data: { reason: "replayed" },
2216
+ },
2217
+ },
2218
+ 400,
2219
+ { "MCP-Protocol-Version": statelessVersion },
2220
+ );
2221
+ }
2664
2222
  retryVerified = true;
2665
2223
  }
2666
2224
  }
@@ -2670,7 +2228,7 @@ export class McpApp {
2670
2228
  toolName,
2671
2229
  args,
2672
2230
  c.req.raw,
2673
- reqSessionId,
2231
+ undefined,
2674
2232
  httpAuthInfo,
2675
2233
  statelessClientMeta,
2676
2234
  {
@@ -2691,7 +2249,7 @@ export class McpApp {
2691
2249
  if (sealPrincipal === null) {
2692
2250
  return noPrincipalError(
2693
2251
  id,
2694
- statelessVersion ?? STATELESS_FALLBACK_VERSION,
2252
+ statelessVersion,
2695
2253
  );
2696
2254
  }
2697
2255
  const built = await this.buildInputRequiredResult(
@@ -2721,8 +2279,7 @@ export class McpApp {
2721
2279
  // path already answered 500 for exactly that.
2722
2280
  built.code === ErrorCode.InternalError ? 500 : 400,
2723
2281
  {
2724
- "MCP-Protocol-Version": statelessVersion ??
2725
- STATELESS_FALLBACK_VERSION,
2282
+ "MCP-Protocol-Version": statelessVersion,
2726
2283
  },
2727
2284
  );
2728
2285
  }
@@ -2732,26 +2289,6 @@ export class McpApp {
2732
2289
  // Tasks extension: the handler asked for a task handle instead of
2733
2290
  // a synchronous result.
2734
2291
  if (isAsyncTaskDescriptor(result)) {
2735
- if (statelessVersion !== SPEC_2026_07_28) {
2736
- // The handler asked for a task, but this peer cannot be handed
2737
- // one. Surfacing the server-side misconfiguration is better than
2738
- // silently degrading to a synchronous call whose duration is the
2739
- // reason the handler wanted a task in the first place.
2740
- return jsonRpcResponse(
2741
- {
2742
- jsonrpc: "2.0",
2743
- id,
2744
- error: {
2745
- code: ErrorCode.InternalError,
2746
- message:
2747
- `Tool "${toolName}" returned a task, but the client negotiated ${
2748
- statelessVersion ?? "a pre-2026 revision"
2749
- }; the Tasks extension requires 2026-07-28.`,
2750
- },
2751
- },
2752
- 400,
2753
- );
2754
- }
2755
2292
  const guard = this.requireTasksCapability(
2756
2293
  statelessClientMeta?.clientCapabilities,
2757
2294
  id,
@@ -2778,8 +2315,7 @@ export class McpApp {
2778
2315
  },
2779
2316
  503,
2780
2317
  {
2781
- "MCP-Protocol-Version": statelessVersion ??
2782
- STATELESS_FALLBACK_VERSION,
2318
+ "MCP-Protocol-Version": statelessVersion,
2783
2319
  },
2784
2320
  );
2785
2321
  }
@@ -2787,7 +2323,7 @@ export class McpApp {
2787
2323
  if (ownerPrincipal === null) {
2788
2324
  return noPrincipalError(
2789
2325
  id,
2790
- statelessVersion ?? STATELESS_FALLBACK_VERSION,
2326
+ statelessVersion,
2791
2327
  );
2792
2328
  }
2793
2329
  const owner = await taskOwnerKeyFor(
@@ -2799,7 +2335,7 @@ export class McpApp {
2799
2335
  if (owner === null) {
2800
2336
  return noOwnerKeyError(
2801
2337
  id,
2802
- statelessVersion ?? STATELESS_FALLBACK_VERSION,
2338
+ statelessVersion,
2803
2339
  );
2804
2340
  }
2805
2341
  // Re-checked, and wrapped: the guard above sits before two awaits
@@ -2838,8 +2374,7 @@ export class McpApp {
2838
2374
  },
2839
2375
  503,
2840
2376
  {
2841
- "MCP-Protocol-Version": statelessVersion ??
2842
- STATELESS_FALLBACK_VERSION,
2377
+ "MCP-Protocol-Version": statelessVersion,
2843
2378
  },
2844
2379
  );
2845
2380
  }
@@ -3050,10 +2585,7 @@ export class McpApp {
3050
2585
  // Replaces the removed HTTP GET stream and resources/subscribe. The
3051
2586
  // response IS the stream: a long-lived SSE body carrying only the
3052
2587
  // notification types the client opted into.
3053
- if (
3054
- method === "subscriptions/listen" && this.subscriptions !== null &&
3055
- statelessVersion === SPEC_2026_07_28
3056
- ) {
2588
+ if (method === "subscriptions/listen" && this.subscriptions !== null) {
3057
2589
  const registry = this.subscriptions;
3058
2590
 
3059
2591
  // A notification-shaped listen makes no sense: the response IS the
@@ -3199,8 +2731,7 @@ export class McpApp {
3199
2731
  // Tells nginx and friends not to buffer, without which events sit
3200
2732
  // in a proxy until the buffer fills.
3201
2733
  "X-Accel-Buffering": "no",
3202
- "MCP-Protocol-Version": statelessVersion ??
3203
- STATELESS_FALLBACK_VERSION,
2734
+ "MCP-Protocol-Version": statelessVersion,
3204
2735
  },
3205
2736
  });
3206
2737
  }
@@ -3212,13 +2743,11 @@ export class McpApp {
3212
2743
  // non-declaring client issuing tasks/get, tasks/update OR tasks/cancel.
3213
2744
  // Guarding creation alone would still let such a client poll and cancel
3214
2745
  // tasks it could never have been handed.
3215
- // Version-gated as well as capability-gated: a 2026-only extension must
3216
- // not be reachable by a peer that negotiated 2025-11-25, which the Tasks
3217
- // spec states as a MUST NOT. Falling through leaves it a 404, which is
3218
- // what an unimplemented method looks like from that peer's perspective.
2746
+ // Capability-gated: a non-declaring client must not reach tasks/*.
2747
+ // The version gate (STATELESS_SUPPORTED_VERSIONS) upstream of this block
2748
+ // already rejects any peer running a pre-2026 protocol version.
3219
2749
  if (
3220
2750
  this.taskStore !== null &&
3221
- statelessVersion === SPEC_2026_07_28 &&
3222
2751
  (method === "tasks/get" || method === "tasks/update" ||
3223
2752
  method === "tasks/cancel")
3224
2753
  ) {
@@ -3278,7 +2807,7 @@ export class McpApp {
3278
2807
  if (callerBase === null) {
3279
2808
  return noPrincipalError(
3280
2809
  id,
3281
- statelessVersion ?? STATELESS_FALLBACK_VERSION,
2810
+ statelessVersion,
3282
2811
  );
3283
2812
  }
3284
2813
  const caller = await taskOwnerKeyFor(
@@ -3290,7 +2819,7 @@ export class McpApp {
3290
2819
  if (caller === null) {
3291
2820
  return noOwnerKeyError(
3292
2821
  id,
3293
- statelessVersion ?? STATELESS_FALLBACK_VERSION,
2822
+ statelessVersion,
3294
2823
  );
3295
2824
  }
3296
2825
 
@@ -3377,29 +2906,9 @@ export class McpApp {
3377
2906
  });
3378
2907
  }
3379
2908
 
3380
- // `ping` and `logging/setLevel` were REMOVED by spec 2026-07-28 — not
3381
- // deprecated. 0.21.0 kept answering `ping` on the stateless path for
3382
- // backward compatibility; that reasoning does not survive the final
3383
- // spec, which requires 404 + -32601 for a method the server does not
3384
- // implement. That response is also how a client distinguishes a modern
3385
- // server from a legacy HTTP+SSE one, so answering `{}` actively misled
3386
- // the probe.
3387
- //
3388
- // Rather than special-casing these two, the stateless path simply does
3389
- // not handle them: they fall through to the generic method-not-found
3390
- // branch at the end, which returns 404 for *any* unimplemented RPC.
3391
- //
3392
- // The stateful path keeps both — its peers negotiated `2025-06-18`,
3393
- // where `logging/setLevel`'s stub is what capability negotiation
3394
- // expects. Deliberately unstamped: no 2026 envelope on that path.
3395
- if (this.options.transport !== "stateless") {
3396
- if (method === "ping") {
3397
- return c.json({ jsonrpc: "2.0", id, result: {} });
3398
- }
3399
- if (method === "logging/setLevel") {
3400
- return c.json({ jsonrpc: "2.0", id, result: {} });
3401
- }
3402
- }
2909
+ // `ping` and `logging/setLevel` were REMOVED by spec 2026-07-28.
2910
+ // They fall through to method-not-found below (404 + -32601), which is
2911
+ // how a client distinguishes a modern server from a legacy HTTP+SSE one.
3403
2912
  if (method === "prompts/list") {
3404
2913
  return c.json({
3405
2914
  jsonrpc: "2.0",
@@ -3448,28 +2957,17 @@ export class McpApp {
3448
2957
  // does not implement the requested RPC method, it MUST respond with
3449
2958
  // 404 Not Found and a JSON-RPC error with code -32601". The status is
3450
2959
  // load-bearing — a client probing an unknown URL uses exactly this
3451
- // response to tell a modern MCP endpoint from a legacy HTTP+SSE server,
3452
- // so answering 200 defeats the backward-compatibility probe.
2960
+ // response to tell a modern MCP endpoint from a legacy HTTP+SSE server.
3453
2961
  //
3454
- // This is the general rule that also covers the methods the spec
3455
- // removed (`ping`, `logging/setLevel`) and the ones not yet implemented
3456
- // (`subscriptions/listen`, Track G). The legacy stateful path keeps
3457
- // answering 200 — its peers negotiated a revision with no such rule.
3458
- if (this.options.transport === "stateless") {
3459
- return jsonRpcResponse(
3460
- {
3461
- jsonrpc: "2.0",
3462
- id,
3463
- error: { code: -32601, message: `Method not found: ${method}` },
3464
- },
3465
- 404,
3466
- );
3467
- }
3468
- return c.json({
3469
- jsonrpc: "2.0",
3470
- id,
3471
- error: { code: -32601, message: `Method not found: ${method}` },
3472
- });
2962
+ // This also covers the removed methods (`ping`, `logging/setLevel`).
2963
+ return jsonRpcResponse(
2964
+ {
2965
+ jsonrpc: "2.0",
2966
+ id,
2967
+ error: { code: -32601, message: `Method not found: ${method}` },
2968
+ },
2969
+ 404,
2970
+ );
3473
2971
  } catch (error) {
3474
2972
  this.log(
3475
2973
  `HTTP request error: ${
@@ -3491,8 +2989,7 @@ export class McpApp {
3491
2989
 
3492
2990
  // Embedded mode: skip serve(), surface the Hono fetch handler to the
3493
2991
  // caller and let them mount it inside their own framework (Fresh, Hono,
3494
- // Express, etc.). The session cleanup timer + post-init still runs so
3495
- // SSE clients and sessions are managed identically to the serve() path.
2992
+ // Express, etc.).
3496
2993
  if (options.embedded) {
3497
2994
  if (!options.embeddedHandlerCallback) {
3498
2995
  throw new Error(
@@ -3502,14 +2999,6 @@ export class McpApp {
3502
2999
  // deno-lint-ignore no-explicit-any
3503
3000
  options.embeddedHandlerCallback(app.fetch as any);
3504
3001
  this.started = true;
3505
- // Track A: no sessions in stateless mode — skip cleanup timer
3506
- if (this.options.transport !== "stateless") {
3507
- this.sessionCleanupTimer = setInterval(
3508
- () => this.cleanupSessions(),
3509
- McpApp.SESSION_CLEANUP_INTERVAL_MS,
3510
- );
3511
- unrefTimer(this.sessionCleanupTimer as unknown as number);
3512
- }
3513
3002
  this.log(
3514
3003
  `HTTP handler ready (embedded mode — no port bound, max concurrent: ${
3515
3004
  this.options.maxConcurrent ?? 10
@@ -3540,17 +3029,6 @@ export class McpApp {
3540
3029
 
3541
3030
  this.started = true;
3542
3031
 
3543
- // Start session cleanup timer (prevents unbounded memory growth).
3544
- // Track A: no sessions in stateless mode — skip timer to keep contract clean.
3545
- if (this.options.transport !== "stateless") {
3546
- this.sessionCleanupTimer = setInterval(
3547
- () => this.cleanupSessions(),
3548
- McpApp.SESSION_CLEANUP_INTERVAL_MS,
3549
- );
3550
- // Don't block Deno from exiting because of cleanup timer
3551
- unrefTimer(this.sessionCleanupTimer as unknown as number);
3552
- }
3553
-
3554
3032
  const rateLimitInfo = this.options.rateLimit
3555
3033
  ? `, rate limit: ${this.options.rateLimit.maxRequests}/${this.options.rateLimit.windowMs}ms`
3556
3034
  : "";
@@ -3594,13 +3072,12 @@ export class McpApp {
3594
3072
  *
3595
3073
  * The returned handler accepts a Web Standard {@link Request} and returns
3596
3074
  * a Web Standard {@link Response}. It exposes the same routes as
3597
- * {@link startHttp}: `POST /mcp`, `GET /mcp` (SSE), `GET /health`,
3598
- * `GET /metrics`, and `GET /.well-known/oauth-protected-resource`.
3075
+ * {@link startHttp}: `POST /mcp`, `GET /health`, `GET /metrics`, and
3076
+ * `GET /.well-known/oauth-protected-resource`. `GET /mcp` returns 405.
3599
3077
  *
3600
3078
  * Auth, multi-tenant middleware, scope checks, and rate limiting are all
3601
- * applied identically. The session cleanup timer and OTel hooks are
3602
- * started, so the server is fully live after this returns — just without
3603
- * its own listening socket.
3079
+ * applied identically. OTel hooks are started, so the server is fully
3080
+ * live after this returns — just without its own listening socket.
3604
3081
  *
3605
3082
  * Multi-tenant SaaS pattern: cache one `McpApp` per tenant
3606
3083
  * and call `getFetchHandler()` once per server, then dispatch each
@@ -3647,99 +3124,6 @@ export class McpApp {
3647
3124
  return captured;
3648
3125
  }
3649
3126
 
3650
- /**
3651
- * Send a JSON-RPC message to all SSE clients in a session
3652
- * Used for server-initiated notifications and requests
3653
- *
3654
- * @param sessionId - Session ID (or "anonymous" for clients without session)
3655
- * @param message - JSON-RPC message to send
3656
- */
3657
- /**
3658
- * Push a message to one session's SSE stream.
3659
- *
3660
- * @deprecated Legacy, stateful-only. Sessions do not exist in spec 2026-07-28,
3661
- * and the GET SSE stream this writes to returns 405 there — so on the stateless
3662
- * transport this silently reaches nobody. Use {@link sendNotification}, which
3663
- * routes to whichever channel the active transport actually has. Dies with the
3664
- * stateful path.
3665
- */
3666
- sendToSession(sessionId: string, message: Record<string, unknown>): void {
3667
- const clients = this.sseClients.get(sessionId);
3668
- if (!clients || clients.length === 0) {
3669
- this.log(`No SSE clients for session: ${sessionId}`);
3670
- return;
3671
- }
3672
-
3673
- const encoder = new TextEncoder();
3674
- const eventId = Date.now();
3675
- const data = `id: ${eventId}\ndata: ${JSON.stringify(message)}\n\n`;
3676
-
3677
- // Iterate in reverse so splice doesn't shift indices
3678
- for (let i = clients.length - 1; i >= 0; i--) {
3679
- const client = clients[i];
3680
- try {
3681
- client.controller.enqueue(encoder.encode(data));
3682
- client.lastEventId = eventId;
3683
- } catch {
3684
- // Stream is closed/broken — remove zombie client to prevent memory leak
3685
- clients.splice(i, 1);
3686
- this.log(`Removed dead SSE client from session: ${sessionId}`);
3687
- }
3688
- }
3689
-
3690
- // Clean up empty session entry
3691
- if (clients.length === 0) {
3692
- this.sseClients.delete(sessionId);
3693
- }
3694
- }
3695
-
3696
- /**
3697
- * Send a notification to all session-keyed SSE clients.
3698
- *
3699
- * @deprecated Legacy, stateful-only, for the same reason as
3700
- * {@link sendToSession}: on the stateless transport the session map is
3701
- * necessarily empty, so this reaches nobody and reports no error. Use
3702
- * {@link sendNotification} — it is the one verb that works on every transport,
3703
- * fanning out through `subscriptions/listen` where that is the live channel.
3704
- *
3705
- * @param method - Notification method name
3706
- * @param params - Notification parameters
3707
- */
3708
- broadcastNotification(
3709
- method: string,
3710
- params?: Record<string, unknown>,
3711
- ): void {
3712
- const message = {
3713
- jsonrpc: "2.0",
3714
- method,
3715
- params,
3716
- };
3717
-
3718
- for (const sessionId of this.sseClients.keys()) {
3719
- this.sendToSession(sessionId, message);
3720
- }
3721
- }
3722
-
3723
- /**
3724
- * Get number of active SSE connections
3725
- */
3726
- getSSEClientCount(): number {
3727
- let count = 0;
3728
- for (const clients of this.sseClients.values()) {
3729
- count += clients.length;
3730
- }
3731
- return count;
3732
- }
3733
-
3734
- /**
3735
- * Get sampling bridge (if enabled)
3736
- *
3737
- * @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
3738
- */
3739
- getSamplingBridge(): SamplingBridge | null {
3740
- return this.samplingBridge;
3741
- }
3742
-
3743
3127
  /**
3744
3128
  * Read the MCP Apps capability advertised by the connected client.
3745
3129
  *
@@ -3792,8 +3176,6 @@ export class McpApp {
3792
3176
  this.serverMetrics.setGauges({
3793
3177
  activeRequests: qm.inFlight,
3794
3178
  queuedRequests: qm.queued,
3795
- activeSessions: this.sessions.size,
3796
- sseClients: this.getSSEClientCount(),
3797
3179
  rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
3798
3180
  });
3799
3181
  return this.serverMetrics.getSnapshot();
@@ -3895,9 +3277,8 @@ export class McpApp {
3895
3277
  * Send a JSON-RPC notification to the connected transport.
3896
3278
  *
3897
3279
  * Routing depends on the transport:
3898
- * - **stateless HTTP**: fanned out to `subscriptions/listen` streams, and only
3899
- * to the subscribers that opted into that notification type.
3900
- * - **stateful HTTP**: broadcast to session-keyed SSE clients (legacy).
3280
+ * - **HTTP**: fanned out to `subscriptions/listen` streams, only to
3281
+ * subscribers that opted into that notification type.
3901
3282
  * - **stdio**: written to stdout via the SDK transport.
3902
3283
  *
3903
3284
  * @param method - Notification method (e.g. "notifications/tools/list_changed")
@@ -3909,12 +3290,7 @@ export class McpApp {
3909
3290
  ): void {
3910
3291
  if (!this.started) return;
3911
3292
 
3912
- // Stateless: route through the subscription registry.
3913
- //
3914
- // Without this branch the call reached broadcastNotification, which walks the
3915
- // session-keyed SSE map — always empty in stateless mode, since GET /mcp
3916
- // returns 405 and no session SSE stream can exist. The notification vanished
3917
- // with no error: a caller had every reason to believe it had been delivered.
3293
+ // Route through the subscription registry (subscriptions/listen streams).
3918
3294
  if (this.subscriptions !== null) {
3919
3295
  switch (method) {
3920
3296
  case "notifications/tools/list_changed":
@@ -3953,12 +3329,6 @@ export class McpApp {
3953
3329
  }
3954
3330
  }
3955
3331
 
3956
- // For legacy stateful HTTP mode, broadcast via session-keyed SSE
3957
- if (this.httpServer) {
3958
- this.broadcastNotification(method, params);
3959
- return;
3960
- }
3961
-
3962
3332
  // For stdio mode, send via SDK transport
3963
3333
  try {
3964
3334
  this.mcpServer.server.notification({ method, params });
@@ -4002,13 +3372,8 @@ export class McpApp {
4002
3372
  * Apply the spec-2026-07-28 result envelope when — and only when — the peer
4003
3373
  * negotiated that revision.
4004
3374
  *
4005
- * Gated on the **negotiated version**, not on the transport. An earlier draft
4006
- * used `transport === "stateless"` as a proxy for "modern peer", which is
4007
- * wrong: the stateless transport also accepts `2025-06-18` and `2025-11-25`
4008
- * (see `STATELESS_SUPPORTED_VERSIONS`), so that gate stamped a 2026 envelope
4009
- * onto responses to peers that had negotiated a revision predating it. The
4010
- * stateful path negotiates nothing per-request and advertises `2025-06-18`, so
4011
- * it passes `undefined` here and stays on the legacy shape.
3375
+ * Always applies on the stateless transport, which only accepts 2026-07-28.
3376
+ * Stdio mode passes `undefined` and stays on the legacy shape.
4012
3377
  *
4013
3378
  * Omitting the envelope for a genuinely legacy peer is safe in the other
4014
3379
  * direction too: the spec instructs clients to read a missing `resultType` as