@casys/mcp-server 0.23.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/README.md +13 -22
- package/mod.ts +0 -3
- package/package.json +1 -1
- package/src/http/body.ts +72 -0
- package/src/http/request-guards.ts +137 -0
- package/src/http/wire.ts +41 -0
- package/src/mcp-app.ts +251 -984
- package/src/observability/metrics.ts +0 -42
- package/src/types.ts +20 -32
- package/src/validation/schema-validator.ts +56 -0
- package/src/sampling/sampling-bridge.ts +0 -193
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
|
-
*
|
|
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";
|
|
@@ -102,6 +101,20 @@ import {
|
|
|
102
101
|
} from "./subscriptions/subscription-registry.js";
|
|
103
102
|
import { ServerMetrics } from "./observability/metrics.js";
|
|
104
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";
|
|
105
118
|
|
|
106
119
|
/**
|
|
107
120
|
* Tool definition with handler
|
|
@@ -118,84 +131,6 @@ interface RegisteredResourceInfo {
|
|
|
118
131
|
handler: ResourceHandler;
|
|
119
132
|
}
|
|
120
133
|
|
|
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
134
|
// ── Track A (spec 2026-07-28) — Stateless transport constants ───────────────
|
|
200
135
|
|
|
201
136
|
/** Namespaced protocolVersion key in params._meta (spec 2026-07-28) */
|
|
@@ -211,8 +146,6 @@ const STATELESS_CLIENT_CAPABILITIES_KEY =
|
|
|
211
146
|
/** Protocol versions accepted by this server in stateless mode */
|
|
212
147
|
const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
|
|
213
148
|
"2026-07-28",
|
|
214
|
-
"2025-06-18",
|
|
215
|
-
"2025-11-25",
|
|
216
149
|
];
|
|
217
150
|
|
|
218
151
|
/** Namespaced serverInfo key in a result's _meta (spec 2026-07-28, SHOULD) */
|
|
@@ -238,8 +171,8 @@ const SPEC_2026_07_28 = "2026-07-28";
|
|
|
238
171
|
*/
|
|
239
172
|
const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
|
|
240
173
|
|
|
241
|
-
/** Version echoed in MCP-Protocol-Version header on error responses (server's
|
|
242
|
-
const STATELESS_FALLBACK_VERSION = "
|
|
174
|
+
/** Version echoed in MCP-Protocol-Version header on error responses (server's only accepted version) */
|
|
175
|
+
const STATELESS_FALLBACK_VERSION = "2026-07-28";
|
|
243
176
|
|
|
244
177
|
const JSONRPC_INVALID_PARAMS = ErrorCode.InvalidParams;
|
|
245
178
|
|
|
@@ -305,155 +238,6 @@ function readLogLevel(meta: Record<string, unknown>): McpLogLevel | undefined {
|
|
|
305
238
|
: undefined;
|
|
306
239
|
}
|
|
307
240
|
|
|
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
241
|
/**
|
|
458
242
|
* Validate the client-owned subscriptions/listen filter before it reaches the
|
|
459
243
|
* registry. The registry deliberately works with a typed SubscriptionFilter;
|
|
@@ -568,7 +352,6 @@ function canonicaliseWireResult(
|
|
|
568
352
|
* - Wraps official @modelcontextprotocol/sdk
|
|
569
353
|
* - Concurrency limiting (default: 10 max concurrent)
|
|
570
354
|
* - Multiple backpressure strategies (sleep/queue/reject)
|
|
571
|
-
* - Optional bidirectional sampling support
|
|
572
355
|
* - Metrics for monitoring
|
|
573
356
|
* - Graceful shutdown
|
|
574
357
|
*
|
|
@@ -600,7 +383,6 @@ export class McpApp {
|
|
|
600
383
|
private requestQueue: RequestQueue;
|
|
601
384
|
private rateLimiter: RateLimiter | null = null;
|
|
602
385
|
private schemaValidator: SchemaValidator | null = null;
|
|
603
|
-
private samplingBridge: SamplingBridge | null = null;
|
|
604
386
|
private tools = new Map<string, ToolWithHandler>();
|
|
605
387
|
|
|
606
388
|
/**
|
|
@@ -633,11 +415,10 @@ export class McpApp {
|
|
|
633
415
|
private stopping = false;
|
|
634
416
|
|
|
635
417
|
/**
|
|
636
|
-
* Live `subscriptions/listen` streams
|
|
418
|
+
* Live `subscriptions/listen` streams.
|
|
637
419
|
*
|
|
638
|
-
*
|
|
639
|
-
*
|
|
640
|
-
* machinery, which this replaces once that path is retired.
|
|
420
|
+
* Initialized unconditionally in startHttp(); null before the server starts
|
|
421
|
+
* or in stdio mode.
|
|
641
422
|
*/
|
|
642
423
|
private subscriptions: SubscriptionRegistry | null = null;
|
|
643
424
|
|
|
@@ -686,28 +467,21 @@ export class McpApp {
|
|
|
686
467
|
// Observability
|
|
687
468
|
private serverMetrics = new ServerMetrics();
|
|
688
469
|
|
|
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
470
|
constructor(options: McpAppOptions) {
|
|
708
471
|
this.options = options;
|
|
709
472
|
this.name = options.name;
|
|
710
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
|
+
|
|
711
485
|
const ttlMs = options.cache?.ttlMs ?? 0;
|
|
712
486
|
if (!Number.isInteger(ttlMs) || ttlMs < 0) {
|
|
713
487
|
throw new Error(
|
|
@@ -773,27 +547,6 @@ export class McpApp {
|
|
|
773
547
|
this.schemaValidator = new SchemaValidator();
|
|
774
548
|
}
|
|
775
549
|
|
|
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
550
|
// Setup MCP protocol handlers
|
|
798
551
|
this.setupHandlers();
|
|
799
552
|
|
|
@@ -1240,8 +993,6 @@ export class McpApp {
|
|
|
1240
993
|
this.serverMetrics.setGauges({
|
|
1241
994
|
activeRequests: queueMetrics.inFlight,
|
|
1242
995
|
queuedRequests: queueMetrics.queued,
|
|
1243
|
-
activeSessions: this.sessions.size,
|
|
1244
|
-
sseClients: this.getSSEClientCount(),
|
|
1245
996
|
rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
|
|
1246
997
|
});
|
|
1247
998
|
|
|
@@ -1547,42 +1298,6 @@ export class McpApp {
|
|
|
1547
1298
|
this.log(`Tools available: ${this.tools.size}`);
|
|
1548
1299
|
}
|
|
1549
1300
|
|
|
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
1301
|
/**
|
|
1587
1302
|
* Restore the invariants a running server relies on.
|
|
1588
1303
|
*
|
|
@@ -1632,29 +1347,6 @@ export class McpApp {
|
|
|
1632
1347
|
return;
|
|
1633
1348
|
}
|
|
1634
1349
|
|
|
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
1350
|
// Stop HTTP server if running
|
|
1659
1351
|
if (this.httpServer) {
|
|
1660
1352
|
await this.httpServer.shutdown();
|
|
@@ -1739,14 +1431,10 @@ export class McpApp {
|
|
|
1739
1431
|
const hostname = options.hostname ?? "0.0.0.0";
|
|
1740
1432
|
this.prepareForStart();
|
|
1741
1433
|
|
|
1742
|
-
if (this.
|
|
1434
|
+
if (this.subscriptions === null) {
|
|
1743
1435
|
this.subscriptions = new SubscriptionRegistry({
|
|
1744
1436
|
serverInfo: { name: this.options.name, version: this.options.version },
|
|
1745
1437
|
});
|
|
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
1438
|
this.subscriptions.startKeepAlive(
|
|
1751
1439
|
setInterval,
|
|
1752
1440
|
(id) => unrefTimer(id as unknown as number),
|
|
@@ -1789,9 +1477,7 @@ export class McpApp {
|
|
|
1789
1477
|
"Content-Type",
|
|
1790
1478
|
"Accept",
|
|
1791
1479
|
"Authorization",
|
|
1792
|
-
"mcp-session-id",
|
|
1793
1480
|
"mcp-protocol-version",
|
|
1794
|
-
"last-event-id",
|
|
1795
1481
|
// Spec 2026-07-28 request-metadata headers. Omitting them broke
|
|
1796
1482
|
// browser clients outright: the preflight rejects the actual request
|
|
1797
1483
|
// before the server ever sees it, so a conforming client could not
|
|
@@ -1811,7 +1497,6 @@ export class McpApp {
|
|
|
1811
1497
|
],
|
|
1812
1498
|
exposeHeaders: [
|
|
1813
1499
|
"Content-Length",
|
|
1814
|
-
"mcp-session-id",
|
|
1815
1500
|
"mcp-protocol-version",
|
|
1816
1501
|
],
|
|
1817
1502
|
maxAge: 600,
|
|
@@ -1837,8 +1522,6 @@ export class McpApp {
|
|
|
1837
1522
|
this.serverMetrics.setGauges({
|
|
1838
1523
|
activeRequests: qm.inFlight,
|
|
1839
1524
|
queuedRequests: qm.queued,
|
|
1840
|
-
activeSessions: this.sessions.size,
|
|
1841
|
-
sseClients: this.getSSEClientCount(),
|
|
1842
1525
|
rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
|
|
1843
1526
|
});
|
|
1844
1527
|
return new Response(this.serverMetrics.toPrometheusFormat(), {
|
|
@@ -1951,105 +1634,18 @@ export class McpApp {
|
|
|
1951
1634
|
}
|
|
1952
1635
|
}
|
|
1953
1636
|
|
|
1954
|
-
//
|
|
1955
|
-
//
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
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
|
-
|
|
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.
|
|
2049
1643
|
// deno-lint-ignore no-explicit-any
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
app.get("/",
|
|
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);
|
|
2053
1649
|
|
|
2054
1650
|
// MCP endpoint - POST handles JSON-RPC
|
|
2055
1651
|
const handleMcpPost = async (
|
|
@@ -2066,23 +1662,16 @@ export class McpApp {
|
|
|
2066
1662
|
) => {
|
|
2067
1663
|
let requestId: string | number | null = null;
|
|
2068
1664
|
try {
|
|
2069
|
-
//
|
|
2070
|
-
//
|
|
2071
|
-
const
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
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;
|
|
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
|
+
})();
|
|
2083
1672
|
const rateLimit = await checkHttpRateLimit(
|
|
2084
1673
|
c.req.raw,
|
|
2085
|
-
|
|
1674
|
+
undefined,
|
|
2086
1675
|
rlHeaders,
|
|
2087
1676
|
);
|
|
2088
1677
|
if (!rateLimit.allowed) {
|
|
@@ -2147,207 +1736,167 @@ export class McpApp {
|
|
|
2147
1736
|
httpAuthInfo = authResult.authInfo;
|
|
2148
1737
|
}
|
|
2149
1738
|
|
|
2150
|
-
//
|
|
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).
|
|
2151
1777
|
// Must run BEFORE any method dispatch so every call (not just initialize)
|
|
2152
1778
|
// is validated. Sets MCP-Protocol-Version header on all subsequent responses
|
|
2153
1779
|
// via Hono's c.header() accumulation.
|
|
2154
1780
|
// Key location: params._meta[STATELESS_PROTO_KEY] (SEP-2575 Final).
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
if (this.options.transport === "stateless") {
|
|
2159
|
-
const clientVersion = isRecord(params) && isRecord(params["_meta"])
|
|
2160
|
-
? params["_meta"][STATELESS_PROTO_KEY]
|
|
2161
|
-
: undefined;
|
|
1781
|
+
const clientVersion = isRecord(params) && isRecord(params["_meta"])
|
|
1782
|
+
? params["_meta"][STATELESS_PROTO_KEY]
|
|
1783
|
+
: undefined;
|
|
2162
1784
|
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
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,
|
|
2186
1827
|
},
|
|
2187
1828
|
},
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
1829
|
+
},
|
|
1830
|
+
400,
|
|
1831
|
+
{ "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
|
|
1832
|
+
);
|
|
1833
|
+
}
|
|
2192
1834
|
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
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.",
|
|
2206
1850
|
},
|
|
2207
1851
|
},
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
1852
|
+
},
|
|
1853
|
+
400,
|
|
1854
|
+
{ "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
|
|
1855
|
+
);
|
|
1856
|
+
}
|
|
2212
1857
|
|
|
2213
|
-
|
|
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) {
|
|
2214
1874
|
return jsonRpcResponse(
|
|
2215
1875
|
{
|
|
2216
1876
|
jsonrpc: "2.0",
|
|
2217
1877
|
id,
|
|
2218
1878
|
error: {
|
|
2219
|
-
code:
|
|
2220
|
-
message:
|
|
2221
|
-
|
|
2222
|
-
data
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
recovery:
|
|
2227
|
-
"Send a ClientCapabilities object; `{}` is valid and means no capabilities declared.",
|
|
2228
|
-
},
|
|
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,
|
|
2229
1886
|
},
|
|
2230
1887
|
},
|
|
2231
1888
|
400,
|
|
2232
1889
|
{ "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
|
|
2233
1890
|
);
|
|
2234
1891
|
}
|
|
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
1892
|
}
|
|
2346
1893
|
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
)
|
|
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);
|
|
1898
|
+
|
|
1899
|
+
if (method === "server/discover") {
|
|
2351
1900
|
return c.json({
|
|
2352
1901
|
jsonrpc: "2.0",
|
|
2353
1902
|
id,
|
|
@@ -2368,108 +1917,26 @@ export class McpApp {
|
|
|
2368
1917
|
});
|
|
2369
1918
|
}
|
|
2370
1919
|
|
|
2371
|
-
// Initialize
|
|
1920
|
+
// Initialize — respond without creating a session or emitting Mcp-Session-Id.
|
|
1921
|
+
// statelessVersion is guaranteed defined here (version check above returned early otherwise).
|
|
2372
1922
|
if (method === "initialize") {
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
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",
|
|
1923
|
+
return c.json({
|
|
1924
|
+
jsonrpc: "2.0",
|
|
1925
|
+
id,
|
|
1926
|
+
result: this.stampResult({
|
|
1927
|
+
protocolVersion: statelessVersion,
|
|
1928
|
+
capabilities: this.buildServerCapabilities(),
|
|
1929
|
+
serverInfo: {
|
|
1930
|
+
name: this.options.name,
|
|
1931
|
+
version: this.options.version,
|
|
2468
1932
|
},
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
1933
|
+
...(this.options.instructions
|
|
1934
|
+
? { instructions: this.options.instructions }
|
|
1935
|
+
: {}),
|
|
1936
|
+
}, statelessVersion),
|
|
1937
|
+
});
|
|
1938
|
+
// Note: c.json() inherits MCP-Protocol-Version header set above.
|
|
1939
|
+
// No Mcp-Session-Id header emitted — stateless by design.
|
|
2473
1940
|
}
|
|
2474
1941
|
|
|
2475
1942
|
// Tools call (delegates to middleware pipeline, which handles auth internally)
|
|
@@ -2502,9 +1969,7 @@ export class McpApp {
|
|
|
2502
1969
|
{};
|
|
2503
1970
|
const statelessClientMeta:
|
|
2504
1971
|
| StatelessClientMeta
|
|
2505
|
-
| undefined =
|
|
2506
|
-
isRecord(params) &&
|
|
2507
|
-
isRecord(params["_meta"])
|
|
1972
|
+
| undefined = isRecord(params) && isRecord(params["_meta"])
|
|
2508
1973
|
? {
|
|
2509
1974
|
clientInfo: params["_meta"][STATELESS_CLIENT_INFO_KEY] as
|
|
2510
1975
|
| Implementation
|
|
@@ -2520,11 +1985,8 @@ export class McpApp {
|
|
|
2520
1985
|
// not members of it, unlike every other per-request field. Reading them
|
|
2521
1986
|
// from `_meta` yields a silent undefined even when the client sent them.
|
|
2522
1987
|
//
|
|
2523
|
-
//
|
|
2524
|
-
|
|
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;
|
|
1988
|
+
// MRTR is always enabled on 2026-07-28 (the only supported version).
|
|
1989
|
+
const mrtrEnabled = true;
|
|
2528
1990
|
|
|
2529
1991
|
// Digest of the arguments AS RECEIVED, taken before the middleware
|
|
2530
1992
|
// pipeline runs. Re-deriving it at seal time would hash whatever the
|
|
@@ -2559,8 +2021,7 @@ export class McpApp {
|
|
|
2559
2021
|
},
|
|
2560
2022
|
400,
|
|
2561
2023
|
{
|
|
2562
|
-
"MCP-Protocol-Version": statelessVersion
|
|
2563
|
-
STATELESS_FALLBACK_VERSION,
|
|
2024
|
+
"MCP-Protocol-Version": statelessVersion,
|
|
2564
2025
|
},
|
|
2565
2026
|
);
|
|
2566
2027
|
}
|
|
@@ -2587,7 +2048,7 @@ export class McpApp {
|
|
|
2587
2048
|
const guardKey = needsKey
|
|
2588
2049
|
? await this.getMrtrKeySafe(
|
|
2589
2050
|
id,
|
|
2590
|
-
statelessVersion
|
|
2051
|
+
statelessVersion,
|
|
2591
2052
|
)
|
|
2592
2053
|
: { key: null as CryptoKey | null };
|
|
2593
2054
|
if ("error" in guardKey) return guardKey.error;
|
|
@@ -2612,8 +2073,7 @@ export class McpApp {
|
|
|
2612
2073
|
},
|
|
2613
2074
|
400,
|
|
2614
2075
|
{
|
|
2615
|
-
"MCP-Protocol-Version": statelessVersion
|
|
2616
|
-
STATELESS_FALLBACK_VERSION,
|
|
2076
|
+
"MCP-Protocol-Version": statelessVersion,
|
|
2617
2077
|
},
|
|
2618
2078
|
);
|
|
2619
2079
|
}
|
|
@@ -2635,7 +2095,7 @@ export class McpApp {
|
|
|
2635
2095
|
if (principal === null) {
|
|
2636
2096
|
return noPrincipalError(
|
|
2637
2097
|
id,
|
|
2638
|
-
statelessVersion
|
|
2098
|
+
statelessVersion,
|
|
2639
2099
|
);
|
|
2640
2100
|
}
|
|
2641
2101
|
const verdict = await verifyRequestState(echoedState, key, {
|
|
@@ -2670,7 +2130,7 @@ export class McpApp {
|
|
|
2670
2130
|
toolName,
|
|
2671
2131
|
args,
|
|
2672
2132
|
c.req.raw,
|
|
2673
|
-
|
|
2133
|
+
undefined,
|
|
2674
2134
|
httpAuthInfo,
|
|
2675
2135
|
statelessClientMeta,
|
|
2676
2136
|
{
|
|
@@ -2691,7 +2151,7 @@ export class McpApp {
|
|
|
2691
2151
|
if (sealPrincipal === null) {
|
|
2692
2152
|
return noPrincipalError(
|
|
2693
2153
|
id,
|
|
2694
|
-
statelessVersion
|
|
2154
|
+
statelessVersion,
|
|
2695
2155
|
);
|
|
2696
2156
|
}
|
|
2697
2157
|
const built = await this.buildInputRequiredResult(
|
|
@@ -2721,8 +2181,7 @@ export class McpApp {
|
|
|
2721
2181
|
// path already answered 500 for exactly that.
|
|
2722
2182
|
built.code === ErrorCode.InternalError ? 500 : 400,
|
|
2723
2183
|
{
|
|
2724
|
-
"MCP-Protocol-Version": statelessVersion
|
|
2725
|
-
STATELESS_FALLBACK_VERSION,
|
|
2184
|
+
"MCP-Protocol-Version": statelessVersion,
|
|
2726
2185
|
},
|
|
2727
2186
|
);
|
|
2728
2187
|
}
|
|
@@ -2732,26 +2191,6 @@ export class McpApp {
|
|
|
2732
2191
|
// Tasks extension: the handler asked for a task handle instead of
|
|
2733
2192
|
// a synchronous result.
|
|
2734
2193
|
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
2194
|
const guard = this.requireTasksCapability(
|
|
2756
2195
|
statelessClientMeta?.clientCapabilities,
|
|
2757
2196
|
id,
|
|
@@ -2778,8 +2217,7 @@ export class McpApp {
|
|
|
2778
2217
|
},
|
|
2779
2218
|
503,
|
|
2780
2219
|
{
|
|
2781
|
-
"MCP-Protocol-Version": statelessVersion
|
|
2782
|
-
STATELESS_FALLBACK_VERSION,
|
|
2220
|
+
"MCP-Protocol-Version": statelessVersion,
|
|
2783
2221
|
},
|
|
2784
2222
|
);
|
|
2785
2223
|
}
|
|
@@ -2787,7 +2225,7 @@ export class McpApp {
|
|
|
2787
2225
|
if (ownerPrincipal === null) {
|
|
2788
2226
|
return noPrincipalError(
|
|
2789
2227
|
id,
|
|
2790
|
-
statelessVersion
|
|
2228
|
+
statelessVersion,
|
|
2791
2229
|
);
|
|
2792
2230
|
}
|
|
2793
2231
|
const owner = await taskOwnerKeyFor(
|
|
@@ -2799,7 +2237,7 @@ export class McpApp {
|
|
|
2799
2237
|
if (owner === null) {
|
|
2800
2238
|
return noOwnerKeyError(
|
|
2801
2239
|
id,
|
|
2802
|
-
statelessVersion
|
|
2240
|
+
statelessVersion,
|
|
2803
2241
|
);
|
|
2804
2242
|
}
|
|
2805
2243
|
// Re-checked, and wrapped: the guard above sits before two awaits
|
|
@@ -2838,8 +2276,7 @@ export class McpApp {
|
|
|
2838
2276
|
},
|
|
2839
2277
|
503,
|
|
2840
2278
|
{
|
|
2841
|
-
"MCP-Protocol-Version": statelessVersion
|
|
2842
|
-
STATELESS_FALLBACK_VERSION,
|
|
2279
|
+
"MCP-Protocol-Version": statelessVersion,
|
|
2843
2280
|
},
|
|
2844
2281
|
);
|
|
2845
2282
|
}
|
|
@@ -3050,10 +2487,7 @@ export class McpApp {
|
|
|
3050
2487
|
// Replaces the removed HTTP GET stream and resources/subscribe. The
|
|
3051
2488
|
// response IS the stream: a long-lived SSE body carrying only the
|
|
3052
2489
|
// notification types the client opted into.
|
|
3053
|
-
if (
|
|
3054
|
-
method === "subscriptions/listen" && this.subscriptions !== null &&
|
|
3055
|
-
statelessVersion === SPEC_2026_07_28
|
|
3056
|
-
) {
|
|
2490
|
+
if (method === "subscriptions/listen" && this.subscriptions !== null) {
|
|
3057
2491
|
const registry = this.subscriptions;
|
|
3058
2492
|
|
|
3059
2493
|
// A notification-shaped listen makes no sense: the response IS the
|
|
@@ -3199,8 +2633,7 @@ export class McpApp {
|
|
|
3199
2633
|
// Tells nginx and friends not to buffer, without which events sit
|
|
3200
2634
|
// in a proxy until the buffer fills.
|
|
3201
2635
|
"X-Accel-Buffering": "no",
|
|
3202
|
-
"MCP-Protocol-Version": statelessVersion
|
|
3203
|
-
STATELESS_FALLBACK_VERSION,
|
|
2636
|
+
"MCP-Protocol-Version": statelessVersion,
|
|
3204
2637
|
},
|
|
3205
2638
|
});
|
|
3206
2639
|
}
|
|
@@ -3212,13 +2645,11 @@ export class McpApp {
|
|
|
3212
2645
|
// non-declaring client issuing tasks/get, tasks/update OR tasks/cancel.
|
|
3213
2646
|
// Guarding creation alone would still let such a client poll and cancel
|
|
3214
2647
|
// tasks it could never have been handed.
|
|
3215
|
-
//
|
|
3216
|
-
//
|
|
3217
|
-
//
|
|
3218
|
-
// what an unimplemented method looks like from that peer's perspective.
|
|
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.
|
|
3219
2651
|
if (
|
|
3220
2652
|
this.taskStore !== null &&
|
|
3221
|
-
statelessVersion === SPEC_2026_07_28 &&
|
|
3222
2653
|
(method === "tasks/get" || method === "tasks/update" ||
|
|
3223
2654
|
method === "tasks/cancel")
|
|
3224
2655
|
) {
|
|
@@ -3278,7 +2709,7 @@ export class McpApp {
|
|
|
3278
2709
|
if (callerBase === null) {
|
|
3279
2710
|
return noPrincipalError(
|
|
3280
2711
|
id,
|
|
3281
|
-
statelessVersion
|
|
2712
|
+
statelessVersion,
|
|
3282
2713
|
);
|
|
3283
2714
|
}
|
|
3284
2715
|
const caller = await taskOwnerKeyFor(
|
|
@@ -3290,7 +2721,7 @@ export class McpApp {
|
|
|
3290
2721
|
if (caller === null) {
|
|
3291
2722
|
return noOwnerKeyError(
|
|
3292
2723
|
id,
|
|
3293
|
-
statelessVersion
|
|
2724
|
+
statelessVersion,
|
|
3294
2725
|
);
|
|
3295
2726
|
}
|
|
3296
2727
|
|
|
@@ -3377,29 +2808,9 @@ export class McpApp {
|
|
|
3377
2808
|
});
|
|
3378
2809
|
}
|
|
3379
2810
|
|
|
3380
|
-
// `ping` and `logging/setLevel` were REMOVED by spec 2026-07-28
|
|
3381
|
-
//
|
|
3382
|
-
//
|
|
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
|
-
}
|
|
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.
|
|
3403
2814
|
if (method === "prompts/list") {
|
|
3404
2815
|
return c.json({
|
|
3405
2816
|
jsonrpc: "2.0",
|
|
@@ -3448,28 +2859,17 @@ export class McpApp {
|
|
|
3448
2859
|
// does not implement the requested RPC method, it MUST respond with
|
|
3449
2860
|
// 404 Not Found and a JSON-RPC error with code -32601". The status is
|
|
3450
2861
|
// 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.
|
|
2862
|
+
// response to tell a modern MCP endpoint from a legacy HTTP+SSE server.
|
|
3453
2863
|
//
|
|
3454
|
-
// This
|
|
3455
|
-
|
|
3456
|
-
|
|
3457
|
-
|
|
3458
|
-
|
|
3459
|
-
|
|
3460
|
-
|
|
3461
|
-
|
|
3462
|
-
|
|
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
|
-
});
|
|
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
|
+
);
|
|
3473
2873
|
} catch (error) {
|
|
3474
2874
|
this.log(
|
|
3475
2875
|
`HTTP request error: ${
|
|
@@ -3491,8 +2891,7 @@ export class McpApp {
|
|
|
3491
2891
|
|
|
3492
2892
|
// Embedded mode: skip serve(), surface the Hono fetch handler to the
|
|
3493
2893
|
// caller and let them mount it inside their own framework (Fresh, Hono,
|
|
3494
|
-
// Express, etc.).
|
|
3495
|
-
// SSE clients and sessions are managed identically to the serve() path.
|
|
2894
|
+
// Express, etc.).
|
|
3496
2895
|
if (options.embedded) {
|
|
3497
2896
|
if (!options.embeddedHandlerCallback) {
|
|
3498
2897
|
throw new Error(
|
|
@@ -3502,14 +2901,6 @@ export class McpApp {
|
|
|
3502
2901
|
// deno-lint-ignore no-explicit-any
|
|
3503
2902
|
options.embeddedHandlerCallback(app.fetch as any);
|
|
3504
2903
|
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
2904
|
this.log(
|
|
3514
2905
|
`HTTP handler ready (embedded mode — no port bound, max concurrent: ${
|
|
3515
2906
|
this.options.maxConcurrent ?? 10
|
|
@@ -3540,17 +2931,6 @@ export class McpApp {
|
|
|
3540
2931
|
|
|
3541
2932
|
this.started = true;
|
|
3542
2933
|
|
|
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
2934
|
const rateLimitInfo = this.options.rateLimit
|
|
3555
2935
|
? `, rate limit: ${this.options.rateLimit.maxRequests}/${this.options.rateLimit.windowMs}ms`
|
|
3556
2936
|
: "";
|
|
@@ -3594,13 +2974,12 @@ export class McpApp {
|
|
|
3594
2974
|
*
|
|
3595
2975
|
* The returned handler accepts a Web Standard {@link Request} and returns
|
|
3596
2976
|
* a Web Standard {@link Response}. It exposes the same routes as
|
|
3597
|
-
* {@link startHttp}: `POST /mcp`, `GET /
|
|
3598
|
-
* `GET
|
|
2977
|
+
* {@link startHttp}: `POST /mcp`, `GET /health`, `GET /metrics`, and
|
|
2978
|
+
* `GET /.well-known/oauth-protected-resource`. `GET /mcp` returns 405.
|
|
3599
2979
|
*
|
|
3600
2980
|
* Auth, multi-tenant middleware, scope checks, and rate limiting are all
|
|
3601
|
-
* applied identically.
|
|
3602
|
-
*
|
|
3603
|
-
* 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.
|
|
3604
2983
|
*
|
|
3605
2984
|
* Multi-tenant SaaS pattern: cache one `McpApp` per tenant
|
|
3606
2985
|
* and call `getFetchHandler()` once per server, then dispatch each
|
|
@@ -3647,99 +3026,6 @@ export class McpApp {
|
|
|
3647
3026
|
return captured;
|
|
3648
3027
|
}
|
|
3649
3028
|
|
|
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
3029
|
/**
|
|
3744
3030
|
* Read the MCP Apps capability advertised by the connected client.
|
|
3745
3031
|
*
|
|
@@ -3792,8 +3078,6 @@ export class McpApp {
|
|
|
3792
3078
|
this.serverMetrics.setGauges({
|
|
3793
3079
|
activeRequests: qm.inFlight,
|
|
3794
3080
|
queuedRequests: qm.queued,
|
|
3795
|
-
activeSessions: this.sessions.size,
|
|
3796
|
-
sseClients: this.getSSEClientCount(),
|
|
3797
3081
|
rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
|
|
3798
3082
|
});
|
|
3799
3083
|
return this.serverMetrics.getSnapshot();
|
|
@@ -3895,9 +3179,8 @@ export class McpApp {
|
|
|
3895
3179
|
* Send a JSON-RPC notification to the connected transport.
|
|
3896
3180
|
*
|
|
3897
3181
|
* Routing depends on the transport:
|
|
3898
|
-
* - **
|
|
3899
|
-
*
|
|
3900
|
-
* - **stateful HTTP**: broadcast to session-keyed SSE clients (legacy).
|
|
3182
|
+
* - **HTTP**: fanned out to `subscriptions/listen` streams, only to
|
|
3183
|
+
* subscribers that opted into that notification type.
|
|
3901
3184
|
* - **stdio**: written to stdout via the SDK transport.
|
|
3902
3185
|
*
|
|
3903
3186
|
* @param method - Notification method (e.g. "notifications/tools/list_changed")
|
|
@@ -3909,12 +3192,7 @@ export class McpApp {
|
|
|
3909
3192
|
): void {
|
|
3910
3193
|
if (!this.started) return;
|
|
3911
3194
|
|
|
3912
|
-
//
|
|
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.
|
|
3195
|
+
// Route through the subscription registry (subscriptions/listen streams).
|
|
3918
3196
|
if (this.subscriptions !== null) {
|
|
3919
3197
|
switch (method) {
|
|
3920
3198
|
case "notifications/tools/list_changed":
|
|
@@ -3953,12 +3231,6 @@ export class McpApp {
|
|
|
3953
3231
|
}
|
|
3954
3232
|
}
|
|
3955
3233
|
|
|
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
3234
|
// For stdio mode, send via SDK transport
|
|
3963
3235
|
try {
|
|
3964
3236
|
this.mcpServer.server.notification({ method, params });
|
|
@@ -4002,13 +3274,8 @@ export class McpApp {
|
|
|
4002
3274
|
* Apply the spec-2026-07-28 result envelope when — and only when — the peer
|
|
4003
3275
|
* negotiated that revision.
|
|
4004
3276
|
*
|
|
4005
|
-
*
|
|
4006
|
-
*
|
|
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.
|
|
3277
|
+
* Always applies on the stateless transport, which only accepts 2026-07-28.
|
|
3278
|
+
* Stdio mode passes `undefined` and stays on the legacy shape.
|
|
4012
3279
|
*
|
|
4013
3280
|
* Omitting the envelope for a genuinely legacy peer is safe in the other
|
|
4014
3281
|
* direction too: the spec instructs clients to read a missing `resultType` as
|