@casys/mcp-server 0.18.0 → 0.20.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/mod.ts +24 -0
- package/package.json +2 -2
- package/src/auth/as-metadata-proxy.ts +27 -11
- package/src/client-auth/callback-server.ts +79 -43
- package/src/client-auth/client-id-metadata.ts +260 -0
- package/src/client-auth/connect.ts +26 -2
- package/src/client-auth/mod.ts +44 -0
- package/src/client-auth/provider.ts +45 -8
- package/src/client-auth/token-store/file-store.ts +23 -32
- package/src/client-auth/types.ts +33 -4
- package/src/mcp-app.ts +165 -18
- package/src/runtime/runtime.ts +111 -7
- package/src/runtime/types.ts +41 -1
- package/src/sampling/sampling-bridge.ts +2 -0
- package/src/types.ts +30 -2
|
@@ -15,6 +15,12 @@ import type {
|
|
|
15
15
|
} from "@modelcontextprotocol/sdk/shared/auth.js";
|
|
16
16
|
import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
17
17
|
import type { OAuthClientConfig } from "./types.js";
|
|
18
|
+
import {
|
|
19
|
+
CimdConfigError,
|
|
20
|
+
isCimdConfig,
|
|
21
|
+
resolveClientMode,
|
|
22
|
+
validateCimdClientConfig,
|
|
23
|
+
} from "./client-id-metadata.js";
|
|
18
24
|
|
|
19
25
|
export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
20
26
|
private serverUrl: string;
|
|
@@ -24,16 +30,37 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
|
24
30
|
private _redirectUrl: string | undefined;
|
|
25
31
|
|
|
26
32
|
constructor(serverUrl: string, config: OAuthClientConfig) {
|
|
33
|
+
const mode = resolveClientMode(config);
|
|
34
|
+
if (mode === "client_id_metadata") {
|
|
35
|
+
validateCimdClientConfig(config);
|
|
36
|
+
}
|
|
27
37
|
this.serverUrl = serverUrl;
|
|
28
38
|
this.config = config;
|
|
29
39
|
}
|
|
30
40
|
|
|
31
41
|
get redirectUrl(): string | URL {
|
|
42
|
+
if (isCimdConfig(this.config)) {
|
|
43
|
+
return this.config.clientRegistration.redirectUri;
|
|
44
|
+
}
|
|
32
45
|
return this._redirectUrl ?? "http://localhost:0/callback";
|
|
33
46
|
}
|
|
34
47
|
|
|
35
48
|
/** Set the redirect URL (called after CallbackServer binds to a port). */
|
|
36
49
|
setRedirectUrl(url: string): void {
|
|
50
|
+
if (isCimdConfig(this.config)) {
|
|
51
|
+
if (url !== this.config.clientRegistration.redirectUri) {
|
|
52
|
+
throw new CimdConfigError(
|
|
53
|
+
"cimd_redirect_mismatch",
|
|
54
|
+
"CIMD redirectUrl cannot differ from configured redirectUri",
|
|
55
|
+
{
|
|
56
|
+
redirectUrl: url,
|
|
57
|
+
configuredRedirectUri: this.config.clientRegistration.redirectUri,
|
|
58
|
+
},
|
|
59
|
+
"Use clientRegistration.redirectUri as the runtime redirect URL.",
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
37
64
|
this._redirectUrl = url;
|
|
38
65
|
}
|
|
39
66
|
|
|
@@ -44,19 +71,28 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
|
44
71
|
grant_types: ["authorization_code"],
|
|
45
72
|
response_types: ["code"],
|
|
46
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
|
|
47
75
|
};
|
|
48
76
|
}
|
|
49
77
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
78
|
+
clientInformation(): Promise<OAuthClientInformationMixed | undefined> {
|
|
79
|
+
if (isCimdConfig(this.config)) {
|
|
80
|
+
return Promise.resolve({
|
|
81
|
+
client_id: this.config.clientRegistration.clientIdMetadataUrl,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
return Promise.resolve(
|
|
85
|
+
this._clientInfo ?? {
|
|
86
|
+
client_id: this.config.clientId,
|
|
87
|
+
},
|
|
88
|
+
);
|
|
54
89
|
}
|
|
55
90
|
|
|
56
|
-
|
|
91
|
+
saveClientInformation(
|
|
57
92
|
info: OAuthClientInformationMixed,
|
|
58
93
|
): Promise<void> {
|
|
59
94
|
this._clientInfo = info;
|
|
95
|
+
return Promise.resolve();
|
|
60
96
|
}
|
|
61
97
|
|
|
62
98
|
async tokens(): Promise<OAuthTokens | undefined> {
|
|
@@ -76,12 +112,13 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
|
76
112
|
await this.config.openBrowser(authorizationUrl.toString());
|
|
77
113
|
}
|
|
78
114
|
|
|
79
|
-
|
|
115
|
+
saveCodeVerifier(codeVerifier: string): Promise<void> {
|
|
80
116
|
this._codeVerifier = codeVerifier;
|
|
117
|
+
return Promise.resolve();
|
|
81
118
|
}
|
|
82
119
|
|
|
83
|
-
|
|
84
|
-
return this._codeVerifier;
|
|
120
|
+
codeVerifier(): Promise<string> {
|
|
121
|
+
return Promise.resolve(this._codeVerifier);
|
|
85
122
|
}
|
|
86
123
|
|
|
87
124
|
async invalidateCredentials(
|
|
@@ -8,6 +8,13 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import type { StoredCredentials, TokenStore } from "../types.js";
|
|
11
|
+
import {
|
|
12
|
+
mkdir,
|
|
13
|
+
readDir,
|
|
14
|
+
readTextFile,
|
|
15
|
+
remove,
|
|
16
|
+
writeTextFile,
|
|
17
|
+
} from "../../runtime/runtime.js";
|
|
11
18
|
|
|
12
19
|
async function sha256hex(input: string): Promise<string> {
|
|
13
20
|
const data = new TextEncoder().encode(input);
|
|
@@ -26,57 +33,41 @@ export class FileTokenStore implements TokenStore {
|
|
|
26
33
|
}
|
|
27
34
|
|
|
28
35
|
private async ensureDir(): Promise<void> {
|
|
29
|
-
await
|
|
36
|
+
await mkdir(this.baseDir, { recursive: true, mode: 0o700 });
|
|
30
37
|
}
|
|
31
38
|
|
|
32
39
|
async get(serverUrl: string): Promise<StoredCredentials | null> {
|
|
33
40
|
const path = await this.filePath(serverUrl);
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
return JSON.parse(content) as StoredCredentials;
|
|
37
|
-
} catch (e) {
|
|
38
|
-
if (e instanceof Deno.errors.NotFound) return null;
|
|
39
|
-
throw e;
|
|
40
|
-
}
|
|
41
|
+
const content = await readTextFile(path);
|
|
42
|
+
return content === null ? null : JSON.parse(content) as StoredCredentials;
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
async set(serverUrl: string, credentials: StoredCredentials): Promise<void> {
|
|
44
46
|
await this.ensureDir();
|
|
45
47
|
const path = await this.filePath(serverUrl);
|
|
46
48
|
const content = JSON.stringify(credentials, null, 2);
|
|
47
|
-
await
|
|
49
|
+
await writeTextFile(path, content, { mode: 0o600 });
|
|
48
50
|
}
|
|
49
51
|
|
|
50
52
|
async delete(serverUrl: string): Promise<void> {
|
|
51
53
|
const path = await this.filePath(serverUrl);
|
|
52
|
-
|
|
53
|
-
await Deno.remove(path);
|
|
54
|
-
} catch (e) {
|
|
55
|
-
if (e instanceof Deno.errors.NotFound) return;
|
|
56
|
-
throw e;
|
|
57
|
-
}
|
|
54
|
+
await remove(path);
|
|
58
55
|
}
|
|
59
56
|
|
|
60
57
|
async list(): Promise<string[]> {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
} catch {
|
|
72
|
-
// Corrupted file, skip
|
|
73
|
-
}
|
|
58
|
+
const urls: string[] = [];
|
|
59
|
+
for (const name of await readDir(this.baseDir)) {
|
|
60
|
+
if (name.endsWith(".json")) {
|
|
61
|
+
try {
|
|
62
|
+
const content = await readTextFile(`${this.baseDir}/${name}`);
|
|
63
|
+
if (content === null) continue;
|
|
64
|
+
const creds = JSON.parse(content) as StoredCredentials;
|
|
65
|
+
urls.push(creds.serverUrl);
|
|
66
|
+
} catch {
|
|
67
|
+
// Corrupted file, skip
|
|
74
68
|
}
|
|
75
69
|
}
|
|
76
|
-
return urls;
|
|
77
|
-
} catch (e) {
|
|
78
|
-
if (e instanceof Deno.errors.NotFound) return [];
|
|
79
|
-
throw e;
|
|
80
70
|
}
|
|
71
|
+
return urls;
|
|
81
72
|
}
|
|
82
73
|
}
|
package/src/client-auth/types.ts
CHANGED
|
@@ -34,10 +34,8 @@ export interface TokenStore {
|
|
|
34
34
|
list(): Promise<string[]>;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
/**
|
|
38
|
-
export interface
|
|
39
|
-
/** OAuth Client ID (public — embedded in consumer binary) */
|
|
40
|
-
clientId: string;
|
|
37
|
+
/** Fields shared by all OAuth client registration modes. */
|
|
38
|
+
export interface OAuthClientConfigBase {
|
|
41
39
|
/** Client name shown in consent screen */
|
|
42
40
|
clientName?: string;
|
|
43
41
|
/** Scopes to request (space-separated in OAuth, array here) */
|
|
@@ -51,3 +49,34 @@ export interface OAuthClientConfig {
|
|
|
51
49
|
/** Timeout for user to complete OAuth flow (ms, default: 120_000) */
|
|
52
50
|
authTimeout?: number;
|
|
53
51
|
}
|
|
52
|
+
|
|
53
|
+
/** Static OAuth client registration (default, backwards-compatible mode). */
|
|
54
|
+
export interface StaticClientConfig extends OAuthClientConfigBase {
|
|
55
|
+
/** OAuth Client ID (public — embedded in consumer binary) */
|
|
56
|
+
clientId: string;
|
|
57
|
+
/** Absence of clientRegistration selects static client-id behavior. */
|
|
58
|
+
clientRegistration?: undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** CIMD client registration (explicit opt-in). */
|
|
62
|
+
export interface CimdClientConfig extends OAuthClientConfigBase {
|
|
63
|
+
/** In CIMD mode, client_id is derived from clientIdMetadataUrl. */
|
|
64
|
+
clientId?: never;
|
|
65
|
+
clientRegistration: {
|
|
66
|
+
method: "client_id_metadata";
|
|
67
|
+
/** HTTPS URL of the hosted Client ID Metadata Document; also the client_id. */
|
|
68
|
+
clientIdMetadataUrl: string;
|
|
69
|
+
/** Runtime redirect URI published in the metadata document. */
|
|
70
|
+
redirectUri: string;
|
|
71
|
+
/** Optional display and extension metadata for the hosted document. */
|
|
72
|
+
metadata?: {
|
|
73
|
+
client_uri?: string;
|
|
74
|
+
logo_uri?: string;
|
|
75
|
+
contacts?: string[];
|
|
76
|
+
extra?: Record<string, unknown>;
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Configuration for creating an OAuthClientProvider */
|
|
82
|
+
export type OAuthClientConfig = StaticClientConfig | CimdClientConfig;
|
package/src/mcp-app.ts
CHANGED
|
@@ -166,6 +166,31 @@ async function readBodyWithLimit(
|
|
|
166
166
|
return body;
|
|
167
167
|
}
|
|
168
168
|
|
|
169
|
+
// ── Track A (spec 2026-07-28) — Stateless transport constants ───────────────
|
|
170
|
+
|
|
171
|
+
/** Namespaced protocolVersion key in params._meta (spec 2026-07-28) */
|
|
172
|
+
const STATELESS_PROTO_KEY = "io.modelcontextprotocol/protocolVersion";
|
|
173
|
+
|
|
174
|
+
/** Protocol versions accepted by this server in stateless mode */
|
|
175
|
+
const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
|
|
176
|
+
"2026-07-28",
|
|
177
|
+
"2025-06-18",
|
|
178
|
+
"2025-11-25",
|
|
179
|
+
];
|
|
180
|
+
|
|
181
|
+
/** Version echoed in MCP-Protocol-Version header on error responses (server's stable baseline) */
|
|
182
|
+
const STATELESS_FALLBACK_VERSION = "2025-06-18";
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Narrow type-guard: returns true iff `v` is a plain object (not array, not null).
|
|
186
|
+
* Used to safely extract fields from JSON-RPC `params` without unsafe casts.
|
|
187
|
+
*/
|
|
188
|
+
function isRecord(v: unknown): v is Record<string, unknown> {
|
|
189
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
193
|
+
|
|
169
194
|
/**
|
|
170
195
|
* McpApp provides a high-performance MCP server
|
|
171
196
|
*
|
|
@@ -282,6 +307,9 @@ export class McpApp {
|
|
|
282
307
|
|
|
283
308
|
// Optional sampling support
|
|
284
309
|
if (options.enableSampling && options.samplingClient) {
|
|
310
|
+
this.log(
|
|
311
|
+
"[DEPRECATED] Sampling is deprecated (MCP 2026-07-28) and will be removed after 2027-07-28.",
|
|
312
|
+
);
|
|
285
313
|
this.samplingBridge = new SamplingBridge(options.samplingClient);
|
|
286
314
|
}
|
|
287
315
|
|
|
@@ -1143,7 +1171,11 @@ export class McpApp {
|
|
|
1143
1171
|
"mcp-protocol-version",
|
|
1144
1172
|
"last-event-id",
|
|
1145
1173
|
],
|
|
1146
|
-
exposeHeaders: [
|
|
1174
|
+
exposeHeaders: [
|
|
1175
|
+
"Content-Length",
|
|
1176
|
+
"mcp-session-id",
|
|
1177
|
+
"mcp-protocol-version",
|
|
1178
|
+
],
|
|
1147
1179
|
maxAge: 600,
|
|
1148
1180
|
}),
|
|
1149
1181
|
);
|
|
@@ -1232,6 +1264,7 @@ export class McpApp {
|
|
|
1232
1264
|
const checkHttpRateLimit = async (
|
|
1233
1265
|
request: Request,
|
|
1234
1266
|
sessionId?: string,
|
|
1267
|
+
overrideHeaders?: Headers, // Track A: sanitized headers for stateless mode (no mcp-session-id)
|
|
1235
1268
|
): Promise<{ allowed: boolean; retryAfterMs: number }> => {
|
|
1236
1269
|
if (!httpRateLimiter || !httpRateLimit) {
|
|
1237
1270
|
return { allowed: true, retryAfterMs: 0 };
|
|
@@ -1242,7 +1275,7 @@ export class McpApp {
|
|
|
1242
1275
|
ip,
|
|
1243
1276
|
method: request.method,
|
|
1244
1277
|
path: new URL(request.url).pathname,
|
|
1245
|
-
headers: request.headers,
|
|
1278
|
+
headers: overrideHeaders ?? request.headers,
|
|
1246
1279
|
sessionId,
|
|
1247
1280
|
};
|
|
1248
1281
|
const key = httpRateLimit.keyExtractor?.(context) ?? ip;
|
|
@@ -1297,6 +1330,11 @@ export class McpApp {
|
|
|
1297
1330
|
// MCP endpoint - GET opens SSE stream for server→client messages (Streamable HTTP spec)
|
|
1298
1331
|
// deno-lint-ignore no-explicit-any
|
|
1299
1332
|
const handleMcpGet = async (c: any) => {
|
|
1333
|
+
// Track A: stateless V2 — SSE channel not applicable (Track B replaces it)
|
|
1334
|
+
if (this.options.transport === "stateless") {
|
|
1335
|
+
return c.text("Method Not Allowed", 405);
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1300
1338
|
const accept = c.req.header("accept") ?? "";
|
|
1301
1339
|
const sessionId = c.req.header("mcp-session-id");
|
|
1302
1340
|
const lastEventId = c.req.header("last-event-id");
|
|
@@ -1398,12 +1436,31 @@ export class McpApp {
|
|
|
1398
1436
|
header: (name: string) => string | undefined;
|
|
1399
1437
|
};
|
|
1400
1438
|
json: (data: unknown, status?: number) => Response;
|
|
1439
|
+
/** Accumulate a response header (Hono Context API — Track A: MCP-Protocol-Version) */
|
|
1440
|
+
header: (name: string, value: string) => void;
|
|
1401
1441
|
},
|
|
1402
1442
|
) => {
|
|
1403
1443
|
let requestId: string | number | null = null;
|
|
1404
1444
|
try {
|
|
1405
|
-
|
|
1406
|
-
|
|
1445
|
+
// Track A: in stateless mode, ignore Mcp-Session-Id so it cannot be used
|
|
1446
|
+
// as a rate-limit key (session bypass attack surface removed).
|
|
1447
|
+
const reqSessionId = this.options.transport === "stateless"
|
|
1448
|
+
? undefined
|
|
1449
|
+
: c.req.header("mcp-session-id");
|
|
1450
|
+
// Track A: strip mcp-session-id from headers passed to rate-limit context
|
|
1451
|
+
// so a keyExtractor cannot use rotating session IDs to bypass IP-level limits.
|
|
1452
|
+
const rlHeaders = this.options.transport === "stateless"
|
|
1453
|
+
? (() => {
|
|
1454
|
+
const h = new Headers(c.req.raw.headers);
|
|
1455
|
+
h.delete("mcp-session-id");
|
|
1456
|
+
return h;
|
|
1457
|
+
})()
|
|
1458
|
+
: undefined;
|
|
1459
|
+
const rateLimit = await checkHttpRateLimit(
|
|
1460
|
+
c.req.raw,
|
|
1461
|
+
reqSessionId,
|
|
1462
|
+
rlHeaders,
|
|
1463
|
+
);
|
|
1407
1464
|
if (!rateLimit.allowed) {
|
|
1408
1465
|
const retryAfter = Math.max(
|
|
1409
1466
|
1,
|
|
@@ -1466,8 +1523,88 @@ export class McpApp {
|
|
|
1466
1523
|
httpAuthInfo = authResult.authInfo;
|
|
1467
1524
|
}
|
|
1468
1525
|
|
|
1526
|
+
// Track A: per-request protocolVersion validation in stateless mode.
|
|
1527
|
+
// Must run BEFORE any method dispatch so every call (not just initialize)
|
|
1528
|
+
// is validated. Sets MCP-Protocol-Version header on all subsequent responses
|
|
1529
|
+
// via Hono's c.header() accumulation.
|
|
1530
|
+
// Key location: params._meta[STATELESS_PROTO_KEY] (spec 2026-07-28, confirmed).
|
|
1531
|
+
// TODO(spec-2026-07-28, valider en interop MCP Inspector): MCP-Protocol-Version
|
|
1532
|
+
// request header comparison to body version not enforced until spec text is final.
|
|
1533
|
+
let statelessVersion: string | undefined;
|
|
1534
|
+
if (this.options.transport === "stateless") {
|
|
1535
|
+
const clientVersion = isRecord(params) && isRecord(params["_meta"])
|
|
1536
|
+
? params["_meta"][STATELESS_PROTO_KEY]
|
|
1537
|
+
: undefined;
|
|
1538
|
+
|
|
1539
|
+
if (typeof clientVersion !== "string") {
|
|
1540
|
+
// Header uses fallback version — no negotiated version available yet
|
|
1541
|
+
return jsonRpcResponse(
|
|
1542
|
+
{
|
|
1543
|
+
jsonrpc: "2.0",
|
|
1544
|
+
id,
|
|
1545
|
+
error: {
|
|
1546
|
+
code: -32020,
|
|
1547
|
+
message: `Missing required field '${STATELESS_PROTO_KEY}'`,
|
|
1548
|
+
},
|
|
1549
|
+
},
|
|
1550
|
+
400,
|
|
1551
|
+
{ "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
|
|
1552
|
+
);
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
if (!STATELESS_SUPPORTED_VERSIONS.includes(clientVersion)) {
|
|
1556
|
+
// AX: data carries machine-readable supported/requested for agent recovery
|
|
1557
|
+
return jsonRpcResponse(
|
|
1558
|
+
{
|
|
1559
|
+
jsonrpc: "2.0",
|
|
1560
|
+
id,
|
|
1561
|
+
error: {
|
|
1562
|
+
code: -32022,
|
|
1563
|
+
message: `Unsupported protocolVersion: "${clientVersion}"`,
|
|
1564
|
+
data: {
|
|
1565
|
+
supported: [...STATELESS_SUPPORTED_VERSIONS],
|
|
1566
|
+
requested: clientVersion,
|
|
1567
|
+
},
|
|
1568
|
+
},
|
|
1569
|
+
},
|
|
1570
|
+
400,
|
|
1571
|
+
{ "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
|
|
1572
|
+
);
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
statelessVersion = clientVersion;
|
|
1576
|
+
// Spec 2026-07-28: echo negotiated version in every response header.
|
|
1577
|
+
// c.header() accumulates headers — all subsequent c.json() calls inherit it.
|
|
1578
|
+
c.header("MCP-Protocol-Version", statelessVersion);
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1469
1581
|
// Initialize - create session and return session ID (now auth-verified)
|
|
1470
1582
|
if (method === "initialize") {
|
|
1583
|
+
// Track A: stateless V2 — respond without creating a session or emitting Mcp-Session-Id.
|
|
1584
|
+
// statelessVersion is guaranteed defined here (per-request block above returned early otherwise).
|
|
1585
|
+
if (this.options.transport === "stateless") {
|
|
1586
|
+
return c.json({
|
|
1587
|
+
jsonrpc: "2.0",
|
|
1588
|
+
id,
|
|
1589
|
+
result: {
|
|
1590
|
+
protocolVersion: statelessVersion as string,
|
|
1591
|
+
capabilities: {
|
|
1592
|
+
tools: {},
|
|
1593
|
+
resources: this.resources.size > 0 ? {} : undefined,
|
|
1594
|
+
},
|
|
1595
|
+
serverInfo: {
|
|
1596
|
+
name: this.options.name,
|
|
1597
|
+
version: this.options.version,
|
|
1598
|
+
},
|
|
1599
|
+
...(this.options.instructions
|
|
1600
|
+
? { instructions: this.options.instructions }
|
|
1601
|
+
: {}),
|
|
1602
|
+
},
|
|
1603
|
+
});
|
|
1604
|
+
// Note: c.json() inherits MCP-Protocol-Version header set above.
|
|
1605
|
+
// No Mcp-Session-Id header emitted — stateless by design.
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1471
1608
|
// Per-IP rate limit on initialize to prevent session exhaustion attacks
|
|
1472
1609
|
const clientIp = getClientIpFromHeaders(c.req.raw.headers);
|
|
1473
1610
|
if (!this.initRateLimiter.checkLimit(clientIp)) {
|
|
@@ -1527,8 +1664,9 @@ export class McpApp {
|
|
|
1527
1664
|
);
|
|
1528
1665
|
}
|
|
1529
1666
|
|
|
1530
|
-
// Session validation: all methods after initialize must provide a valid session
|
|
1531
|
-
|
|
1667
|
+
// Session validation: all methods after initialize must provide a valid session.
|
|
1668
|
+
// Skipped in stateless V2 mode (Track A) — no session concept.
|
|
1669
|
+
if (this.options.transport !== "stateless" && reqSessionId) {
|
|
1532
1670
|
const session = this.sessions.get(reqSessionId);
|
|
1533
1671
|
if (!session) {
|
|
1534
1672
|
return c.json({
|
|
@@ -1686,6 +1824,7 @@ export class McpApp {
|
|
|
1686
1824
|
if (method === "prompts/list") {
|
|
1687
1825
|
return c.json({ jsonrpc: "2.0", id, result: { prompts: [] } });
|
|
1688
1826
|
}
|
|
1827
|
+
// @deprecated (MCP 2026-07-28)
|
|
1689
1828
|
if (method === "logging/setLevel") {
|
|
1690
1829
|
return c.json({ jsonrpc: "2.0", id, result: {} });
|
|
1691
1830
|
}
|
|
@@ -1752,11 +1891,14 @@ export class McpApp {
|
|
|
1752
1891
|
// deno-lint-ignore no-explicit-any
|
|
1753
1892
|
options.embeddedHandlerCallback(app.fetch as any);
|
|
1754
1893
|
this.started = true;
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1894
|
+
// Track A: no sessions in stateless mode — skip cleanup timer
|
|
1895
|
+
if (this.options.transport !== "stateless") {
|
|
1896
|
+
this.sessionCleanupTimer = setInterval(
|
|
1897
|
+
() => this.cleanupSessions(),
|
|
1898
|
+
McpApp.SESSION_CLEANUP_INTERVAL_MS,
|
|
1899
|
+
);
|
|
1900
|
+
unrefTimer(this.sessionCleanupTimer as unknown as number);
|
|
1901
|
+
}
|
|
1760
1902
|
this.log(
|
|
1761
1903
|
`HTTP handler ready (embedded mode — no port bound, max concurrent: ${
|
|
1762
1904
|
this.options.maxConcurrent ?? 10
|
|
@@ -1787,13 +1929,16 @@ export class McpApp {
|
|
|
1787
1929
|
|
|
1788
1930
|
this.started = true;
|
|
1789
1931
|
|
|
1790
|
-
// Start session cleanup timer (prevents unbounded memory growth)
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1932
|
+
// Start session cleanup timer (prevents unbounded memory growth).
|
|
1933
|
+
// Track A: no sessions in stateless mode — skip timer to keep contract clean.
|
|
1934
|
+
if (this.options.transport !== "stateless") {
|
|
1935
|
+
this.sessionCleanupTimer = setInterval(
|
|
1936
|
+
() => this.cleanupSessions(),
|
|
1937
|
+
McpApp.SESSION_CLEANUP_INTERVAL_MS,
|
|
1938
|
+
);
|
|
1939
|
+
// Don't block Deno from exiting because of cleanup timer
|
|
1940
|
+
unrefTimer(this.sessionCleanupTimer as unknown as number);
|
|
1941
|
+
}
|
|
1797
1942
|
|
|
1798
1943
|
const rateLimitInfo = this.options.rateLimit
|
|
1799
1944
|
? `, rate limit: ${this.options.rateLimit.maxRequests}/${this.options.rateLimit.windowMs}ms`
|
|
@@ -1962,6 +2107,8 @@ export class McpApp {
|
|
|
1962
2107
|
|
|
1963
2108
|
/**
|
|
1964
2109
|
* Get sampling bridge (if enabled)
|
|
2110
|
+
*
|
|
2111
|
+
* @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
|
|
1965
2112
|
*/
|
|
1966
2113
|
getSamplingBridge(): SamplingBridge | null {
|
|
1967
2114
|
return this.samplingBridge;
|
package/src/runtime/runtime.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// deno-lint-ignore-file no-process-global
|
|
1
|
+
// deno-lint-ignore-file no-process-global
|
|
2
2
|
/**
|
|
3
3
|
* Runtime adapter — Node.js implementation
|
|
4
4
|
*
|
|
@@ -9,7 +9,14 @@
|
|
|
9
9
|
* @module lib/server/runtime.node
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import {
|
|
12
|
+
import { Buffer } from "node:buffer";
|
|
13
|
+
import {
|
|
14
|
+
mkdir as nodeMkdir,
|
|
15
|
+
readdir,
|
|
16
|
+
readFile,
|
|
17
|
+
rm,
|
|
18
|
+
writeFile,
|
|
19
|
+
} from "node:fs/promises";
|
|
13
20
|
import { createServer } from "node:http";
|
|
14
21
|
import type {
|
|
15
22
|
FetchHandler,
|
|
@@ -52,6 +59,55 @@ export async function readTextFile(path: string): Promise<string | null> {
|
|
|
52
59
|
}
|
|
53
60
|
}
|
|
54
61
|
|
|
62
|
+
/**
|
|
63
|
+
* Write a UTF-8 text file.
|
|
64
|
+
*/
|
|
65
|
+
export async function writeTextFile(
|
|
66
|
+
path: string,
|
|
67
|
+
content: string,
|
|
68
|
+
opts?: { mode?: number },
|
|
69
|
+
): Promise<void> {
|
|
70
|
+
await writeFile(path, content, { mode: opts?.mode });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Create a directory.
|
|
75
|
+
*/
|
|
76
|
+
export async function mkdir(
|
|
77
|
+
path: string,
|
|
78
|
+
opts?: { recursive?: boolean; mode?: number },
|
|
79
|
+
): Promise<void> {
|
|
80
|
+
await nodeMkdir(path, { recursive: opts?.recursive, mode: opts?.mode });
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Remove a file or empty directory. No-op if absent.
|
|
85
|
+
*/
|
|
86
|
+
export async function remove(path: string): Promise<void> {
|
|
87
|
+
try {
|
|
88
|
+
await rm(path);
|
|
89
|
+
} catch (err: unknown) {
|
|
90
|
+
if (isNodeNotFound(err)) {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
throw err;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Read directory entry names. Returns [] if absent.
|
|
99
|
+
*/
|
|
100
|
+
export async function readDir(path: string): Promise<string[]> {
|
|
101
|
+
try {
|
|
102
|
+
return await readdir(path);
|
|
103
|
+
} catch (err: unknown) {
|
|
104
|
+
if (isNodeNotFound(err)) {
|
|
105
|
+
return [];
|
|
106
|
+
}
|
|
107
|
+
throw err;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
55
111
|
/**
|
|
56
112
|
* Start an HTTP server with a fetch-style handler.
|
|
57
113
|
* Uses node:http with a Request/Response adapter (compatible with Hono).
|
|
@@ -149,16 +205,36 @@ export function serve(
|
|
|
149
205
|
}
|
|
150
206
|
});
|
|
151
207
|
|
|
208
|
+
server.on("error", (err) => {
|
|
209
|
+
if (options.onError) {
|
|
210
|
+
options.onError(err);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
setTimeout(() => {
|
|
214
|
+
throw err;
|
|
215
|
+
}, 0);
|
|
216
|
+
});
|
|
217
|
+
|
|
152
218
|
server.listen(options.port, hostname, () => {
|
|
153
219
|
if (options.onListen) {
|
|
154
|
-
|
|
220
|
+
const address = server.address();
|
|
221
|
+
const port = typeof address === "object" && address !== null
|
|
222
|
+
? address.port
|
|
223
|
+
: options.port;
|
|
224
|
+
options.onListen({ hostname, port });
|
|
155
225
|
}
|
|
156
226
|
});
|
|
157
227
|
|
|
158
228
|
return {
|
|
159
229
|
shutdown: () =>
|
|
160
230
|
new Promise<void>((resolve, reject) => {
|
|
161
|
-
server.close((err) =>
|
|
231
|
+
server.close((err) => {
|
|
232
|
+
if (err && !isNodeServerNotRunning(err)) {
|
|
233
|
+
reject(err);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
resolve();
|
|
237
|
+
});
|
|
162
238
|
}),
|
|
163
239
|
};
|
|
164
240
|
}
|
|
@@ -182,7 +258,16 @@ export function unrefTimer(id: number): void {
|
|
|
182
258
|
}
|
|
183
259
|
|
|
184
260
|
/** Compile-time contract check — ensures this module satisfies RuntimePort */
|
|
185
|
-
void ({
|
|
261
|
+
void ({
|
|
262
|
+
env,
|
|
263
|
+
readTextFile,
|
|
264
|
+
writeTextFile,
|
|
265
|
+
mkdir,
|
|
266
|
+
remove,
|
|
267
|
+
readDir,
|
|
268
|
+
serve,
|
|
269
|
+
unrefTimer,
|
|
270
|
+
} satisfies RuntimePort);
|
|
186
271
|
|
|
187
272
|
// ─── Internal helpers ────────────────────────────────────
|
|
188
273
|
|
|
@@ -190,7 +275,7 @@ void ({ env, readTextFile, serve, unrefTimer } satisfies RuntimePort);
|
|
|
190
275
|
function collectBody(
|
|
191
276
|
req: import("node:http").IncomingMessage,
|
|
192
277
|
maxBytes: number | null,
|
|
193
|
-
): Promise<
|
|
278
|
+
): Promise<ArrayBuffer> {
|
|
194
279
|
return new Promise((resolve, reject) => {
|
|
195
280
|
const chunks: Buffer[] = [];
|
|
196
281
|
let total = 0;
|
|
@@ -208,7 +293,13 @@ function collectBody(
|
|
|
208
293
|
});
|
|
209
294
|
req.on("end", () => {
|
|
210
295
|
if (!rejected) {
|
|
211
|
-
|
|
296
|
+
const body = Buffer.concat(chunks);
|
|
297
|
+
resolve(
|
|
298
|
+
body.buffer.slice(
|
|
299
|
+
body.byteOffset,
|
|
300
|
+
body.byteOffset + body.byteLength,
|
|
301
|
+
),
|
|
302
|
+
);
|
|
212
303
|
}
|
|
213
304
|
});
|
|
214
305
|
req.on("error", (err) => {
|
|
@@ -218,3 +309,16 @@ function collectBody(
|
|
|
218
309
|
});
|
|
219
310
|
});
|
|
220
311
|
}
|
|
312
|
+
|
|
313
|
+
function isNodeNotFound(err: unknown): boolean {
|
|
314
|
+
return Boolean(
|
|
315
|
+
err && typeof err === "object" && "code" in err && err.code === "ENOENT",
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function isNodeServerNotRunning(err: unknown): boolean {
|
|
320
|
+
return Boolean(
|
|
321
|
+
err && typeof err === "object" && "code" in err &&
|
|
322
|
+
err.code === "ERR_SERVER_NOT_RUNNING",
|
|
323
|
+
);
|
|
324
|
+
}
|