@casys/mcp-server 0.19.0 → 0.21.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/package.json +2 -2
- package/src/auth/middleware.ts +38 -12
- package/src/auth/scope-middleware.ts +2 -2
- package/src/client-auth/client-id-metadata.ts +6 -2
- package/src/client-auth/provider.ts +12 -2
- package/src/mcp-app.ts +261 -19
- package/src/middleware/types.ts +11 -0
- package/src/sampling/sampling-bridge.ts +2 -0
- package/src/types.ts +36 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@casys/mcp-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.0",
|
|
4
4
|
"description": "Production-ready MCP server framework with concurrency control, auth, and observability",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "mod.ts",
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
},
|
|
12
12
|
"dependencies": {
|
|
13
13
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
14
|
-
"@modelcontextprotocol/ext-apps": "^1.7.
|
|
14
|
+
"@modelcontextprotocol/ext-apps": "^1.7.4",
|
|
15
15
|
"hono": "^4.0.0",
|
|
16
16
|
"ajv": "^8.17.1",
|
|
17
17
|
"jose": "^6.0.0",
|
package/src/auth/middleware.ts
CHANGED
|
@@ -12,6 +12,12 @@ import type { AuthInfo } from "./types.js";
|
|
|
12
12
|
import type { Middleware } from "../middleware/types.js";
|
|
13
13
|
import { isOtelEnabled, recordAuthEvent } from "../observability/otel.js";
|
|
14
14
|
|
|
15
|
+
const JSONRPC_FORBIDDEN = -32002;
|
|
16
|
+
|
|
17
|
+
function escapeAuthenticateParam(s: string): string {
|
|
18
|
+
return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
19
|
+
}
|
|
20
|
+
|
|
15
21
|
/**
|
|
16
22
|
* Authentication error with structured information
|
|
17
23
|
* for generating proper HTTP error responses.
|
|
@@ -61,11 +67,14 @@ export function createUnauthorizedResponse(
|
|
|
61
67
|
error?: string,
|
|
62
68
|
errorDescription?: string,
|
|
63
69
|
): Response {
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
70
|
+
const parts = [
|
|
71
|
+
`Bearer resource_metadata="${escapeAuthenticateParam(resourceMetadataUrl)}"`,
|
|
72
|
+
];
|
|
73
|
+
if (error) parts.push(`error="${escapeAuthenticateParam(error)}"`);
|
|
67
74
|
if (errorDescription) {
|
|
68
|
-
parts.push(
|
|
75
|
+
parts.push(
|
|
76
|
+
`error_description="${escapeAuthenticateParam(errorDescription)}"`,
|
|
77
|
+
);
|
|
69
78
|
}
|
|
70
79
|
|
|
71
80
|
return new Response(
|
|
@@ -88,20 +97,36 @@ export function createUnauthorizedResponse(
|
|
|
88
97
|
* Create a 403 Forbidden response for insufficient scopes.
|
|
89
98
|
*
|
|
90
99
|
* @param requiredScopes - Scopes that were required but missing
|
|
100
|
+
* @param resourceMetadataUrl - URL to the Protected Resource Metadata endpoint
|
|
91
101
|
*/
|
|
92
|
-
export function createForbiddenResponse(
|
|
102
|
+
export function createForbiddenResponse(
|
|
103
|
+
requiredScopes: string[],
|
|
104
|
+
resourceMetadataUrl: string,
|
|
105
|
+
): Response {
|
|
106
|
+
const requiredScopesDescription = requiredScopes.join(", ");
|
|
107
|
+
const parts = [
|
|
108
|
+
`Bearer resource_metadata="${escapeAuthenticateParam(resourceMetadataUrl)}"`,
|
|
109
|
+
`error="insufficient_scope"`,
|
|
110
|
+
`error_description="${
|
|
111
|
+
escapeAuthenticateParam(requiredScopesDescription)
|
|
112
|
+
}"`,
|
|
113
|
+
];
|
|
114
|
+
|
|
93
115
|
return new Response(
|
|
94
116
|
JSON.stringify({
|
|
95
117
|
jsonrpc: "2.0",
|
|
96
118
|
id: null,
|
|
97
119
|
error: {
|
|
98
|
-
code:
|
|
120
|
+
code: JSONRPC_FORBIDDEN,
|
|
99
121
|
message: `Forbidden: requires scopes ${requiredScopes.join(", ")}`,
|
|
100
122
|
},
|
|
101
123
|
}),
|
|
102
124
|
{
|
|
103
125
|
status: 403,
|
|
104
|
-
headers: {
|
|
126
|
+
headers: {
|
|
127
|
+
"Content-Type": "application/json",
|
|
128
|
+
"WWW-Authenticate": parts.join(", "),
|
|
129
|
+
},
|
|
105
130
|
},
|
|
106
131
|
);
|
|
107
132
|
}
|
|
@@ -150,18 +175,19 @@ export function createAuthMiddleware(provider: AuthProvider): Middleware {
|
|
|
150
175
|
return next();
|
|
151
176
|
}
|
|
152
177
|
|
|
178
|
+
// 0.15.0+: provider's getResourceMetadata() always returns a valid
|
|
179
|
+
// absolute URL in resource_metadata_url (type system guarantees it).
|
|
180
|
+
// No derivation needed at the middleware level anymore.
|
|
181
|
+
const metadataUrl = provider.getResourceMetadata().resource_metadata_url;
|
|
182
|
+
|
|
153
183
|
// Already authenticated by the HTTP-level gate (verifyHttpAuth).
|
|
154
184
|
// Skip the redundant verifyToken call to avoid JWKS race conditions
|
|
155
185
|
// when concurrent requests arrive on a cold cache.
|
|
156
186
|
if (ctx.authInfo) {
|
|
187
|
+
ctx.resourceMetadataUrl = metadataUrl;
|
|
157
188
|
return next();
|
|
158
189
|
}
|
|
159
190
|
|
|
160
|
-
// 0.15.0+: provider's getResourceMetadata() always returns a valid
|
|
161
|
-
// absolute URL in resource_metadata_url (type system guarantees it).
|
|
162
|
-
// No derivation needed at the middleware level anymore.
|
|
163
|
-
const metadataUrl = provider.getResourceMetadata().resource_metadata_url;
|
|
164
|
-
|
|
165
191
|
const token = extractBearerToken(ctx.request);
|
|
166
192
|
if (!token) {
|
|
167
193
|
if (isOtelEnabled()) {
|
|
@@ -48,8 +48,8 @@ export function createScopeMiddleware(
|
|
|
48
48
|
const missingScopes = requiredScopes.filter((s) =>
|
|
49
49
|
!authInfo.scopes.includes(s)
|
|
50
50
|
);
|
|
51
|
-
//
|
|
52
|
-
//
|
|
51
|
+
// Used by 403 responses to advertise protected resource metadata in
|
|
52
|
+
// WWW-Authenticate; auth middleware populates it for HTTP requests.
|
|
53
53
|
const metadataUrl = (ctx.resourceMetadataUrl as string | undefined) ?? "";
|
|
54
54
|
throw new AuthError("insufficient_scope", metadataUrl, missingScopes);
|
|
55
55
|
}
|
|
@@ -29,9 +29,11 @@ export interface ClientIdMetadataDocument {
|
|
|
29
29
|
client_id: string;
|
|
30
30
|
client_name: string;
|
|
31
31
|
redirect_uris: string[];
|
|
32
|
-
grant_types: ["authorization_code"];
|
|
32
|
+
grant_types: ["authorization_code", "refresh_token"];
|
|
33
33
|
response_types: ["code"];
|
|
34
34
|
token_endpoint_auth_method: "none";
|
|
35
|
+
/** RFC 7591 application type. Always "native" for loopback CLI/desktop clients. */
|
|
36
|
+
application_type: "native" | "web";
|
|
35
37
|
scope?: string;
|
|
36
38
|
client_uri?: string;
|
|
37
39
|
logo_uri?: string;
|
|
@@ -118,9 +120,10 @@ export function buildClientIdMetadataDocument(
|
|
|
118
120
|
client_id: clientRegistration.clientIdMetadataUrl,
|
|
119
121
|
client_name: config.clientName!,
|
|
120
122
|
redirect_uris: [clientRegistration.redirectUri],
|
|
121
|
-
grant_types: ["authorization_code"],
|
|
123
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
122
124
|
response_types: ["code"],
|
|
123
125
|
token_endpoint_auth_method: "none",
|
|
126
|
+
application_type: "native",
|
|
124
127
|
} as ClientIdMetadataDocument;
|
|
125
128
|
|
|
126
129
|
if (config.scopes?.length) {
|
|
@@ -230,6 +233,7 @@ const RESERVED_METADATA_KEYS = new Set([
|
|
|
230
233
|
"grant_types",
|
|
231
234
|
"response_types",
|
|
232
235
|
"token_endpoint_auth_method",
|
|
236
|
+
"application_type",
|
|
233
237
|
]);
|
|
234
238
|
|
|
235
239
|
function validateExtraMetadataKeys(metadata: unknown): void {
|
|
@@ -68,9 +68,10 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
|
68
68
|
return {
|
|
69
69
|
client_name: this.config.clientName ?? "PML Client",
|
|
70
70
|
redirect_uris: [String(this.redirectUrl)],
|
|
71
|
-
grant_types: ["authorization_code"],
|
|
71
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
72
72
|
response_types: ["code"],
|
|
73
73
|
token_endpoint_auth_method: "none", // public client, PKCE only
|
|
74
|
+
application_type: "native", // loopback CLI/desktop — prevents AS rejection of http://127.0.0.1 redirects
|
|
74
75
|
};
|
|
75
76
|
}
|
|
76
77
|
|
|
@@ -100,9 +101,18 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
|
100
101
|
}
|
|
101
102
|
|
|
102
103
|
async saveTokens(tokens: OAuthTokens): Promise<void> {
|
|
104
|
+
// Sequential guard only: keep an existing refresh_token when a later save omits it.
|
|
105
|
+
// This get/set is not atomic; concurrent saves for one serverUrl are unsupported
|
|
106
|
+
// because refresh is serialized by the caller.
|
|
107
|
+
const stored = await this.config.tokenStore.get(this.serverUrl);
|
|
108
|
+
const tokensToStore = tokens.refresh_token === undefined &&
|
|
109
|
+
stored?.tokens.refresh_token !== undefined
|
|
110
|
+
? { ...tokens, refresh_token: stored.tokens.refresh_token }
|
|
111
|
+
: tokens;
|
|
112
|
+
|
|
103
113
|
await this.config.tokenStore.set(this.serverUrl, {
|
|
104
114
|
serverUrl: this.serverUrl,
|
|
105
|
-
tokens,
|
|
115
|
+
tokens: tokensToStore,
|
|
106
116
|
obtainedAt: Date.now(),
|
|
107
117
|
});
|
|
108
118
|
}
|
package/src/mcp-app.ts
CHANGED
|
@@ -15,6 +15,9 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
|
|
15
15
|
import {
|
|
16
16
|
type CallToolRequest,
|
|
17
17
|
CallToolRequestSchema,
|
|
18
|
+
type ClientCapabilities,
|
|
19
|
+
ErrorCode,
|
|
20
|
+
type Implementation,
|
|
18
21
|
ListResourcesRequestSchema,
|
|
19
22
|
ListToolsRequestSchema,
|
|
20
23
|
type ReadResourceRequest,
|
|
@@ -166,6 +169,46 @@ async function readBodyWithLimit(
|
|
|
166
169
|
return body;
|
|
167
170
|
}
|
|
168
171
|
|
|
172
|
+
// ── Track A (spec 2026-07-28) — Stateless transport constants ───────────────
|
|
173
|
+
|
|
174
|
+
/** Namespaced protocolVersion key in params._meta (spec 2026-07-28) */
|
|
175
|
+
const STATELESS_PROTO_KEY = "io.modelcontextprotocol/protocolVersion";
|
|
176
|
+
|
|
177
|
+
/** Namespaced clientInfo key in params._meta (SEP-2575 stateless transport) */
|
|
178
|
+
const STATELESS_CLIENT_INFO_KEY = "io.modelcontextprotocol/clientInfo";
|
|
179
|
+
|
|
180
|
+
/** Namespaced clientCapabilities key in params._meta (SEP-2575 stateless transport) */
|
|
181
|
+
const STATELESS_CLIENT_CAPABILITIES_KEY =
|
|
182
|
+
"io.modelcontextprotocol/clientCapabilities";
|
|
183
|
+
|
|
184
|
+
/** Protocol versions accepted by this server in stateless mode */
|
|
185
|
+
const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
|
|
186
|
+
"2026-07-28",
|
|
187
|
+
"2025-06-18",
|
|
188
|
+
"2025-11-25",
|
|
189
|
+
];
|
|
190
|
+
|
|
191
|
+
/** Version echoed in MCP-Protocol-Version header on error responses (server's stable baseline) */
|
|
192
|
+
const STATELESS_FALLBACK_VERSION = "2025-06-18";
|
|
193
|
+
|
|
194
|
+
const JSONRPC_INVALID_PARAMS = ErrorCode.InvalidParams;
|
|
195
|
+
const MCP_UNSUPPORTED_PROTOCOL_VERSION = -32004;
|
|
196
|
+
|
|
197
|
+
interface StatelessClientMeta {
|
|
198
|
+
readonly clientInfo?: Implementation;
|
|
199
|
+
readonly clientCapabilities?: ClientCapabilities;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Narrow type-guard: returns true iff `v` is a plain object (not array, not null).
|
|
204
|
+
* Used to safely extract fields from JSON-RPC `params` without unsafe casts.
|
|
205
|
+
*/
|
|
206
|
+
function isRecord(v: unknown): v is Record<string, unknown> {
|
|
207
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
211
|
+
|
|
169
212
|
/**
|
|
170
213
|
* McpApp provides a high-performance MCP server
|
|
171
214
|
*
|
|
@@ -282,6 +325,9 @@ export class McpApp {
|
|
|
282
325
|
|
|
283
326
|
// Optional sampling support
|
|
284
327
|
if (options.enableSampling && options.samplingClient) {
|
|
328
|
+
this.log(
|
|
329
|
+
"[DEPRECATED] Sampling is deprecated (MCP 2026-07-28) and will be removed after 2027-07-28.",
|
|
330
|
+
);
|
|
285
331
|
this.samplingBridge = new SamplingBridge(options.samplingClient);
|
|
286
332
|
}
|
|
287
333
|
|
|
@@ -608,6 +654,10 @@ export class McpApp {
|
|
|
608
654
|
? { sessionId: ctx.sessionId }
|
|
609
655
|
: {}),
|
|
610
656
|
...(ctx.authInfo ? { authInfo: ctx.authInfo as AuthInfo } : {}),
|
|
657
|
+
...(ctx.clientInfo !== undefined ? { clientInfo: ctx.clientInfo } : {}),
|
|
658
|
+
...(ctx.clientCapabilities !== undefined
|
|
659
|
+
? { clientCapabilities: ctx.clientCapabilities }
|
|
660
|
+
: {}),
|
|
611
661
|
}));
|
|
612
662
|
});
|
|
613
663
|
}
|
|
@@ -628,6 +678,7 @@ export class McpApp {
|
|
|
628
678
|
request?: Request,
|
|
629
679
|
sessionId?: string,
|
|
630
680
|
preVerifiedAuthInfo?: AuthInfo,
|
|
681
|
+
clientMeta?: StatelessClientMeta,
|
|
631
682
|
): Promise<MiddlewareResult> {
|
|
632
683
|
if (!this.middlewareRunner) {
|
|
633
684
|
throw new Error(
|
|
@@ -644,6 +695,12 @@ export class McpApp {
|
|
|
644
695
|
// middleware skips the redundant verifyToken call (avoids JWKS
|
|
645
696
|
// race conditions on concurrent cold-cache requests).
|
|
646
697
|
authInfo: preVerifiedAuthInfo,
|
|
698
|
+
...(clientMeta?.clientInfo !== undefined
|
|
699
|
+
? { clientInfo: clientMeta.clientInfo }
|
|
700
|
+
: {}),
|
|
701
|
+
...(clientMeta?.clientCapabilities !== undefined
|
|
702
|
+
? { clientCapabilities: clientMeta.clientCapabilities }
|
|
703
|
+
: {}),
|
|
647
704
|
};
|
|
648
705
|
|
|
649
706
|
// OTel span + metrics
|
|
@@ -1143,7 +1200,11 @@ export class McpApp {
|
|
|
1143
1200
|
"mcp-protocol-version",
|
|
1144
1201
|
"last-event-id",
|
|
1145
1202
|
],
|
|
1146
|
-
exposeHeaders: [
|
|
1203
|
+
exposeHeaders: [
|
|
1204
|
+
"Content-Length",
|
|
1205
|
+
"mcp-session-id",
|
|
1206
|
+
"mcp-protocol-version",
|
|
1207
|
+
],
|
|
1147
1208
|
maxAge: 600,
|
|
1148
1209
|
}),
|
|
1149
1210
|
);
|
|
@@ -1232,6 +1293,7 @@ export class McpApp {
|
|
|
1232
1293
|
const checkHttpRateLimit = async (
|
|
1233
1294
|
request: Request,
|
|
1234
1295
|
sessionId?: string,
|
|
1296
|
+
overrideHeaders?: Headers, // Track A: sanitized headers for stateless mode (no mcp-session-id)
|
|
1235
1297
|
): Promise<{ allowed: boolean; retryAfterMs: number }> => {
|
|
1236
1298
|
if (!httpRateLimiter || !httpRateLimit) {
|
|
1237
1299
|
return { allowed: true, retryAfterMs: 0 };
|
|
@@ -1242,7 +1304,7 @@ export class McpApp {
|
|
|
1242
1304
|
ip,
|
|
1243
1305
|
method: request.method,
|
|
1244
1306
|
path: new URL(request.url).pathname,
|
|
1245
|
-
headers: request.headers,
|
|
1307
|
+
headers: overrideHeaders ?? request.headers,
|
|
1246
1308
|
sessionId,
|
|
1247
1309
|
};
|
|
1248
1310
|
const key = httpRateLimit.keyExtractor?.(context) ?? ip;
|
|
@@ -1297,6 +1359,11 @@ export class McpApp {
|
|
|
1297
1359
|
// MCP endpoint - GET opens SSE stream for server→client messages (Streamable HTTP spec)
|
|
1298
1360
|
// deno-lint-ignore no-explicit-any
|
|
1299
1361
|
const handleMcpGet = async (c: any) => {
|
|
1362
|
+
// Track A: stateless V2 — SSE channel not applicable (Track B replaces it)
|
|
1363
|
+
if (this.options.transport === "stateless") {
|
|
1364
|
+
return c.text("Method Not Allowed", 405);
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1300
1367
|
const accept = c.req.header("accept") ?? "";
|
|
1301
1368
|
const sessionId = c.req.header("mcp-session-id");
|
|
1302
1369
|
const lastEventId = c.req.header("last-event-id");
|
|
@@ -1398,12 +1465,31 @@ export class McpApp {
|
|
|
1398
1465
|
header: (name: string) => string | undefined;
|
|
1399
1466
|
};
|
|
1400
1467
|
json: (data: unknown, status?: number) => Response;
|
|
1468
|
+
/** Accumulate a response header (Hono Context API — Track A: MCP-Protocol-Version) */
|
|
1469
|
+
header: (name: string, value: string) => void;
|
|
1401
1470
|
},
|
|
1402
1471
|
) => {
|
|
1403
1472
|
let requestId: string | number | null = null;
|
|
1404
1473
|
try {
|
|
1405
|
-
|
|
1406
|
-
|
|
1474
|
+
// Track A: in stateless mode, ignore Mcp-Session-Id so it cannot be used
|
|
1475
|
+
// as a rate-limit key (session bypass attack surface removed).
|
|
1476
|
+
const reqSessionId = this.options.transport === "stateless"
|
|
1477
|
+
? undefined
|
|
1478
|
+
: c.req.header("mcp-session-id");
|
|
1479
|
+
// Track A: strip mcp-session-id from headers passed to rate-limit context
|
|
1480
|
+
// so a keyExtractor cannot use rotating session IDs to bypass IP-level limits.
|
|
1481
|
+
const rlHeaders = this.options.transport === "stateless"
|
|
1482
|
+
? (() => {
|
|
1483
|
+
const h = new Headers(c.req.raw.headers);
|
|
1484
|
+
h.delete("mcp-session-id");
|
|
1485
|
+
return h;
|
|
1486
|
+
})()
|
|
1487
|
+
: undefined;
|
|
1488
|
+
const rateLimit = await checkHttpRateLimit(
|
|
1489
|
+
c.req.raw,
|
|
1490
|
+
reqSessionId,
|
|
1491
|
+
rlHeaders,
|
|
1492
|
+
);
|
|
1407
1493
|
if (!rateLimit.allowed) {
|
|
1408
1494
|
const retryAfter = Math.max(
|
|
1409
1495
|
1,
|
|
@@ -1466,8 +1552,132 @@ export class McpApp {
|
|
|
1466
1552
|
httpAuthInfo = authResult.authInfo;
|
|
1467
1553
|
}
|
|
1468
1554
|
|
|
1555
|
+
// Track A: per-request protocolVersion validation in stateless mode.
|
|
1556
|
+
// Must run BEFORE any method dispatch so every call (not just initialize)
|
|
1557
|
+
// is validated. Sets MCP-Protocol-Version header on all subsequent responses
|
|
1558
|
+
// via Hono's c.header() accumulation.
|
|
1559
|
+
// Key location: params._meta[STATELESS_PROTO_KEY] (SEP-2575 Final).
|
|
1560
|
+
// Tolerant mode: MCP-Protocol-Version may be absent for backward compatibility;
|
|
1561
|
+
// when present it must match the _meta version.
|
|
1562
|
+
let statelessVersion: string | undefined;
|
|
1563
|
+
if (this.options.transport === "stateless") {
|
|
1564
|
+
const clientVersion = isRecord(params) && isRecord(params["_meta"])
|
|
1565
|
+
? params["_meta"][STATELESS_PROTO_KEY]
|
|
1566
|
+
: undefined;
|
|
1567
|
+
|
|
1568
|
+
if (typeof clientVersion !== "string") {
|
|
1569
|
+
// Header uses fallback version — no negotiated version available yet
|
|
1570
|
+
return jsonRpcResponse(
|
|
1571
|
+
{
|
|
1572
|
+
jsonrpc: "2.0",
|
|
1573
|
+
id,
|
|
1574
|
+
error: {
|
|
1575
|
+
code: JSONRPC_INVALID_PARAMS,
|
|
1576
|
+
message: `Missing required field '${STATELESS_PROTO_KEY}'`,
|
|
1577
|
+
},
|
|
1578
|
+
},
|
|
1579
|
+
400,
|
|
1580
|
+
{ "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
|
|
1581
|
+
);
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
if (!STATELESS_SUPPORTED_VERSIONS.includes(clientVersion)) {
|
|
1585
|
+
// AX: data carries machine-readable supported/requested for agent recovery
|
|
1586
|
+
return jsonRpcResponse(
|
|
1587
|
+
{
|
|
1588
|
+
jsonrpc: "2.0",
|
|
1589
|
+
id,
|
|
1590
|
+
error: {
|
|
1591
|
+
code: MCP_UNSUPPORTED_PROTOCOL_VERSION,
|
|
1592
|
+
message: `Unsupported protocolVersion: "${clientVersion}"`,
|
|
1593
|
+
data: {
|
|
1594
|
+
supported: [...STATELESS_SUPPORTED_VERSIONS],
|
|
1595
|
+
requested: clientVersion,
|
|
1596
|
+
},
|
|
1597
|
+
},
|
|
1598
|
+
},
|
|
1599
|
+
400,
|
|
1600
|
+
{ "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
|
|
1601
|
+
);
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
const headerVersion = c.req.header("MCP-Protocol-Version");
|
|
1605
|
+
if (
|
|
1606
|
+
headerVersion !== undefined &&
|
|
1607
|
+
headerVersion !== clientVersion
|
|
1608
|
+
) {
|
|
1609
|
+
return jsonRpcResponse(
|
|
1610
|
+
{
|
|
1611
|
+
jsonrpc: "2.0",
|
|
1612
|
+
id,
|
|
1613
|
+
error: {
|
|
1614
|
+
code: JSONRPC_INVALID_PARAMS,
|
|
1615
|
+
message:
|
|
1616
|
+
`MCP-Protocol-Version header "${headerVersion}" does not match _meta protocolVersion "${clientVersion}"`,
|
|
1617
|
+
},
|
|
1618
|
+
},
|
|
1619
|
+
400,
|
|
1620
|
+
{ "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
|
|
1621
|
+
);
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
statelessVersion = clientVersion;
|
|
1625
|
+
// Spec 2026-07-28: echo negotiated version in every response header.
|
|
1626
|
+
// c.header() accumulates headers — all subsequent c.json() calls inherit it.
|
|
1627
|
+
c.header("MCP-Protocol-Version", statelessVersion);
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
if (
|
|
1631
|
+
method === "server/discover" &&
|
|
1632
|
+
this.options.transport === "stateless"
|
|
1633
|
+
) {
|
|
1634
|
+
return c.json({
|
|
1635
|
+
jsonrpc: "2.0",
|
|
1636
|
+
id,
|
|
1637
|
+
result: {
|
|
1638
|
+
supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
|
|
1639
|
+
capabilities: {
|
|
1640
|
+
tools: {},
|
|
1641
|
+
resources: this.resources.size > 0 ? {} : undefined,
|
|
1642
|
+
},
|
|
1643
|
+
serverInfo: {
|
|
1644
|
+
name: this.options.name,
|
|
1645
|
+
version: this.options.version,
|
|
1646
|
+
},
|
|
1647
|
+
...(this.options.instructions
|
|
1648
|
+
? { instructions: this.options.instructions }
|
|
1649
|
+
: {}),
|
|
1650
|
+
},
|
|
1651
|
+
});
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1469
1654
|
// Initialize - create session and return session ID (now auth-verified)
|
|
1470
1655
|
if (method === "initialize") {
|
|
1656
|
+
// Track A: stateless V2 — respond without creating a session or emitting Mcp-Session-Id.
|
|
1657
|
+
// statelessVersion is guaranteed defined here (per-request block above returned early otherwise).
|
|
1658
|
+
if (this.options.transport === "stateless") {
|
|
1659
|
+
return c.json({
|
|
1660
|
+
jsonrpc: "2.0",
|
|
1661
|
+
id,
|
|
1662
|
+
result: {
|
|
1663
|
+
protocolVersion: statelessVersion as string,
|
|
1664
|
+
capabilities: {
|
|
1665
|
+
tools: {},
|
|
1666
|
+
resources: this.resources.size > 0 ? {} : undefined,
|
|
1667
|
+
},
|
|
1668
|
+
serverInfo: {
|
|
1669
|
+
name: this.options.name,
|
|
1670
|
+
version: this.options.version,
|
|
1671
|
+
},
|
|
1672
|
+
...(this.options.instructions
|
|
1673
|
+
? { instructions: this.options.instructions }
|
|
1674
|
+
: {}),
|
|
1675
|
+
},
|
|
1676
|
+
});
|
|
1677
|
+
// Note: c.json() inherits MCP-Protocol-Version header set above.
|
|
1678
|
+
// No Mcp-Session-Id header emitted — stateless by design.
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1471
1681
|
// Per-IP rate limit on initialize to prevent session exhaustion attacks
|
|
1472
1682
|
const clientIp = getClientIpFromHeaders(c.req.raw.headers);
|
|
1473
1683
|
if (!this.initRateLimiter.checkLimit(clientIp)) {
|
|
@@ -1527,8 +1737,9 @@ export class McpApp {
|
|
|
1527
1737
|
);
|
|
1528
1738
|
}
|
|
1529
1739
|
|
|
1530
|
-
// Session validation: all methods after initialize must provide a valid session
|
|
1531
|
-
|
|
1740
|
+
// Session validation: all methods after initialize must provide a valid session.
|
|
1741
|
+
// Skipped in stateless V2 mode (Track A) — no session concept.
|
|
1742
|
+
if (this.options.transport !== "stateless" && reqSessionId) {
|
|
1532
1743
|
const session = this.sessions.get(reqSessionId);
|
|
1533
1744
|
if (!session) {
|
|
1534
1745
|
return c.json({
|
|
@@ -1545,6 +1756,20 @@ export class McpApp {
|
|
|
1545
1756
|
if (method === "tools/call" && params?.name) {
|
|
1546
1757
|
const toolName = params.name as string;
|
|
1547
1758
|
const args = (params.arguments as Record<string, unknown>) || {};
|
|
1759
|
+
const statelessClientMeta:
|
|
1760
|
+
| StatelessClientMeta
|
|
1761
|
+
| undefined = this.options.transport === "stateless" &&
|
|
1762
|
+
isRecord(params) &&
|
|
1763
|
+
isRecord(params["_meta"])
|
|
1764
|
+
? {
|
|
1765
|
+
clientInfo: params["_meta"][STATELESS_CLIENT_INFO_KEY] as
|
|
1766
|
+
| Implementation
|
|
1767
|
+
| undefined,
|
|
1768
|
+
clientCapabilities: params["_meta"][
|
|
1769
|
+
STATELESS_CLIENT_CAPABILITIES_KEY
|
|
1770
|
+
] as ClientCapabilities | undefined,
|
|
1771
|
+
}
|
|
1772
|
+
: undefined;
|
|
1548
1773
|
|
|
1549
1774
|
try {
|
|
1550
1775
|
const result = await this.executeToolCall(
|
|
@@ -1553,6 +1778,7 @@ export class McpApp {
|
|
|
1553
1778
|
c.req.raw,
|
|
1554
1779
|
reqSessionId,
|
|
1555
1780
|
httpAuthInfo,
|
|
1781
|
+
statelessClientMeta,
|
|
1556
1782
|
);
|
|
1557
1783
|
return c.json({
|
|
1558
1784
|
jsonrpc: "2.0",
|
|
@@ -1572,7 +1798,10 @@ export class McpApp {
|
|
|
1572
1798
|
);
|
|
1573
1799
|
}
|
|
1574
1800
|
if (error.code === "insufficient_scope") {
|
|
1575
|
-
return createForbiddenResponse(
|
|
1801
|
+
return createForbiddenResponse(
|
|
1802
|
+
error.requiredScopes ?? [],
|
|
1803
|
+
error.resourceMetadataUrl,
|
|
1804
|
+
);
|
|
1576
1805
|
}
|
|
1577
1806
|
}
|
|
1578
1807
|
|
|
@@ -1680,12 +1909,17 @@ export class McpApp {
|
|
|
1680
1909
|
}
|
|
1681
1910
|
|
|
1682
1911
|
// MCP protocol methods we don't implement — return empty results
|
|
1912
|
+
// ping: SEP-2575 removes ping in stateless mode, but we deliberately keep
|
|
1913
|
+
// answering it for backward compatibility. A SEP-conformant client won't send
|
|
1914
|
+
// it, and a stale client using ping for liveness keeps working. (Decision:
|
|
1915
|
+
// tolerant over strict, consistent with the rest of the stateless conformance work.)
|
|
1683
1916
|
if (method === "ping") {
|
|
1684
1917
|
return c.json({ jsonrpc: "2.0", id, result: {} });
|
|
1685
1918
|
}
|
|
1686
1919
|
if (method === "prompts/list") {
|
|
1687
1920
|
return c.json({ jsonrpc: "2.0", id, result: { prompts: [] } });
|
|
1688
1921
|
}
|
|
1922
|
+
// @deprecated (MCP 2026-07-28)
|
|
1689
1923
|
if (method === "logging/setLevel") {
|
|
1690
1924
|
return c.json({ jsonrpc: "2.0", id, result: {} });
|
|
1691
1925
|
}
|
|
@@ -1752,11 +1986,14 @@ export class McpApp {
|
|
|
1752
1986
|
// deno-lint-ignore no-explicit-any
|
|
1753
1987
|
options.embeddedHandlerCallback(app.fetch as any);
|
|
1754
1988
|
this.started = true;
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1989
|
+
// Track A: no sessions in stateless mode — skip cleanup timer
|
|
1990
|
+
if (this.options.transport !== "stateless") {
|
|
1991
|
+
this.sessionCleanupTimer = setInterval(
|
|
1992
|
+
() => this.cleanupSessions(),
|
|
1993
|
+
McpApp.SESSION_CLEANUP_INTERVAL_MS,
|
|
1994
|
+
);
|
|
1995
|
+
unrefTimer(this.sessionCleanupTimer as unknown as number);
|
|
1996
|
+
}
|
|
1760
1997
|
this.log(
|
|
1761
1998
|
`HTTP handler ready (embedded mode — no port bound, max concurrent: ${
|
|
1762
1999
|
this.options.maxConcurrent ?? 10
|
|
@@ -1787,13 +2024,16 @@ export class McpApp {
|
|
|
1787
2024
|
|
|
1788
2025
|
this.started = true;
|
|
1789
2026
|
|
|
1790
|
-
// Start session cleanup timer (prevents unbounded memory growth)
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
2027
|
+
// Start session cleanup timer (prevents unbounded memory growth).
|
|
2028
|
+
// Track A: no sessions in stateless mode — skip timer to keep contract clean.
|
|
2029
|
+
if (this.options.transport !== "stateless") {
|
|
2030
|
+
this.sessionCleanupTimer = setInterval(
|
|
2031
|
+
() => this.cleanupSessions(),
|
|
2032
|
+
McpApp.SESSION_CLEANUP_INTERVAL_MS,
|
|
2033
|
+
);
|
|
2034
|
+
// Don't block Deno from exiting because of cleanup timer
|
|
2035
|
+
unrefTimer(this.sessionCleanupTimer as unknown as number);
|
|
2036
|
+
}
|
|
1797
2037
|
|
|
1798
2038
|
const rateLimitInfo = this.options.rateLimit
|
|
1799
2039
|
? `, rate limit: ${this.options.rateLimit.maxRequests}/${this.options.rateLimit.windowMs}ms`
|
|
@@ -1962,6 +2202,8 @@ export class McpApp {
|
|
|
1962
2202
|
|
|
1963
2203
|
/**
|
|
1964
2204
|
* Get sampling bridge (if enabled)
|
|
2205
|
+
*
|
|
2206
|
+
* @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
|
|
1965
2207
|
*/
|
|
1966
2208
|
getSamplingBridge(): SamplingBridge | null {
|
|
1967
2209
|
return this.samplingBridge;
|
package/src/middleware/types.ts
CHANGED
|
@@ -7,6 +7,11 @@
|
|
|
7
7
|
* @module lib/server/middleware/types
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
+
import type {
|
|
11
|
+
ClientCapabilities,
|
|
12
|
+
Implementation,
|
|
13
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
14
|
+
|
|
10
15
|
/**
|
|
11
16
|
* Context passed through the middleware pipeline.
|
|
12
17
|
* Each middleware can read and enrich the context.
|
|
@@ -24,6 +29,12 @@ export interface MiddlewareContext {
|
|
|
24
29
|
/** Session ID (only present for HTTP transport) */
|
|
25
30
|
sessionId?: string;
|
|
26
31
|
|
|
32
|
+
/** Client implementation metadata (stateless HTTP transport, when provided) */
|
|
33
|
+
clientInfo?: Implementation;
|
|
34
|
+
|
|
35
|
+
/** Client capabilities metadata (stateless HTTP transport, when provided) */
|
|
36
|
+
clientCapabilities?: ClientCapabilities;
|
|
37
|
+
|
|
27
38
|
/** Extensible by middlewares (e.g., authInfo added by auth middleware) */
|
|
28
39
|
[key: string]: unknown;
|
|
29
40
|
}
|
|
@@ -24,6 +24,8 @@ import type {
|
|
|
24
24
|
* - Promise-based async/await API
|
|
25
25
|
* - Support for both Anthropic and OpenAI sampling
|
|
26
26
|
*
|
|
27
|
+
* @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
|
|
28
|
+
*
|
|
27
29
|
* @example
|
|
28
30
|
* ```typescript
|
|
29
31
|
* const bridge = new SamplingBridge(samplingClient);
|
package/src/types.ts
CHANGED
|
@@ -8,6 +8,10 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import type { McpUiToolMeta as McpUiToolMetaBase } from "@modelcontextprotocol/ext-apps";
|
|
11
|
+
import type {
|
|
12
|
+
ClientCapabilities,
|
|
13
|
+
Implementation,
|
|
14
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
11
15
|
|
|
12
16
|
/**
|
|
13
17
|
* Rate limit configuration
|
|
@@ -75,7 +79,10 @@ export interface McpAppOptions {
|
|
|
75
79
|
*/
|
|
76
80
|
validateSchema?: boolean;
|
|
77
81
|
|
|
78
|
-
/**
|
|
82
|
+
/**
|
|
83
|
+
* Enable sampling support for agentic tools (default: false)
|
|
84
|
+
* @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
|
|
85
|
+
*/
|
|
79
86
|
enableSampling?: boolean;
|
|
80
87
|
|
|
81
88
|
/**
|
|
@@ -84,7 +91,10 @@ export interface McpAppOptions {
|
|
|
84
91
|
*/
|
|
85
92
|
instructions?: string;
|
|
86
93
|
|
|
87
|
-
/**
|
|
94
|
+
/**
|
|
95
|
+
* Sampling client implementation (required if enableSampling is true)
|
|
96
|
+
* @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
|
|
97
|
+
*/
|
|
88
98
|
samplingClient?: SamplingClient;
|
|
89
99
|
|
|
90
100
|
/** Custom logger function (default: console.error) */
|
|
@@ -132,6 +142,22 @@ export interface McpAppOptions {
|
|
|
132
142
|
* that discovers child servers after the stdio handshake).
|
|
133
143
|
*/
|
|
134
144
|
expectResources?: boolean;
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* HTTP transport mode (Track A — spec 2026-07-28).
|
|
148
|
+
*
|
|
149
|
+
* - `"stateful"` (DEFAULT): legacy session-based transport, retro-compatible
|
|
150
|
+
* with spec 2025-06-18. Requires an `initialize` handshake before any
|
|
151
|
+
* other method; emits and validates `Mcp-Session-Id` headers.
|
|
152
|
+
* - `"stateless"`: per-request transport, spec 2026-07-28. No handshake, no
|
|
153
|
+
* `Mcp-Session-Id`. `protocolVersion` is read from
|
|
154
|
+
* `params._meta["io.modelcontextprotocol/protocolVersion"]` on every
|
|
155
|
+
* request. `GET /mcp` returns 405 (Track B will replace the SSE channel).
|
|
156
|
+
*
|
|
157
|
+
* Default: `"stateful"`.
|
|
158
|
+
*/
|
|
159
|
+
// Track A — transport mode, défaut "stateful"
|
|
160
|
+
transport?: "stateful" | "stateless";
|
|
135
161
|
}
|
|
136
162
|
|
|
137
163
|
// ============================================
|
|
@@ -445,6 +471,8 @@ export interface ToolHandlerContext {
|
|
|
445
471
|
readonly request?: Request;
|
|
446
472
|
readonly sessionId?: string;
|
|
447
473
|
readonly authInfo?: import("./auth/types.js").AuthInfo;
|
|
474
|
+
readonly clientInfo?: Implementation;
|
|
475
|
+
readonly clientCapabilities?: ClientCapabilities;
|
|
448
476
|
}
|
|
449
477
|
|
|
450
478
|
export type ToolHandler = (
|
|
@@ -481,6 +509,8 @@ export type ToolErrorMapper = (
|
|
|
481
509
|
/**
|
|
482
510
|
* Sampling client interface for bidirectional LLM delegation
|
|
483
511
|
* Compatible with the agentic sampling protocol (SEP-1577)
|
|
512
|
+
*
|
|
513
|
+
* @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
|
|
484
514
|
*/
|
|
485
515
|
export interface SamplingClient {
|
|
486
516
|
/**
|
|
@@ -494,6 +524,8 @@ export interface SamplingClient {
|
|
|
494
524
|
/**
|
|
495
525
|
* Parameters for sampling request
|
|
496
526
|
* Compatible with MCP sampling protocol
|
|
527
|
+
*
|
|
528
|
+
* @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
|
|
497
529
|
*/
|
|
498
530
|
export interface SamplingParams {
|
|
499
531
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
@@ -515,6 +547,8 @@ export interface SamplingParams {
|
|
|
515
547
|
/**
|
|
516
548
|
* Result from sampling request
|
|
517
549
|
* Compatible with MCP sampling protocol
|
|
550
|
+
*
|
|
551
|
+
* @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
|
|
518
552
|
*/
|
|
519
553
|
export interface SamplingResult {
|
|
520
554
|
content: Array<{
|