keryx 0.40.0 → 0.40.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/initializers/mcp.ts +73 -14
- package/package.json +1 -1
- package/util/mcpServer.ts +87 -1
package/initializers/mcp.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
2
|
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
isInitializeRequest,
|
|
5
|
+
LATEST_PROTOCOL_VERSION,
|
|
6
|
+
SUPPORTED_PROTOCOL_VERSIONS,
|
|
7
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
4
8
|
import { randomUUID } from "crypto";
|
|
5
9
|
import { api, logger } from "../api";
|
|
6
10
|
import { Initializer } from "../classes/Initializer";
|
|
@@ -21,14 +25,17 @@ import {
|
|
|
21
25
|
formatToolName,
|
|
22
26
|
handleTransportRequest,
|
|
23
27
|
isMcpSessionAuthorizedForChannel,
|
|
28
|
+
MCP_JSONRPC_ERROR,
|
|
24
29
|
type McpAuthInfo,
|
|
25
30
|
type McpSessionAuth,
|
|
26
31
|
mcpJsonResponse,
|
|
32
|
+
mcpJsonRpcErrorResponse,
|
|
27
33
|
parseToolName,
|
|
28
34
|
readMcpSessionRecord,
|
|
29
35
|
refreshMcpSessionTtl,
|
|
30
36
|
sanitizeSchemaForMcp,
|
|
31
37
|
terminateMcpSession,
|
|
38
|
+
validateJsonRpcPayload,
|
|
32
39
|
writeMcpSessionRecord,
|
|
33
40
|
} from "../util/mcpServer";
|
|
34
41
|
import type { PubSubMessage } from "./pubsub";
|
|
@@ -61,18 +68,34 @@ export type OnMcpDisconnectHook = (sessionId: string) => Promise<void> | void;
|
|
|
61
68
|
const namespace = "mcp";
|
|
62
69
|
|
|
63
70
|
/**
|
|
64
|
-
*
|
|
65
|
-
*
|
|
71
|
+
* Resolve the protocol version an `initialize` request body (single message or
|
|
72
|
+
* batch) actually negotiates, so it can be stored in the shared session registry
|
|
66
73
|
* and replayed when the session is adopted on another node.
|
|
74
|
+
*
|
|
75
|
+
* This is the *negotiated* version, not the requested one: a client on a newer
|
|
76
|
+
* spec revision than the SDK supports (e.g. `2026-07-28`) is answered with the
|
|
77
|
+
* newest version the server does support, exactly as the SDK's `initialize`
|
|
78
|
+
* handler does. Persisting the raw request instead would leave the registry
|
|
79
|
+
* holding a version no node can replay, and the session would silently fall back
|
|
80
|
+
* to the 2025-03-26 default the first time it was adopted elsewhere.
|
|
81
|
+
*
|
|
82
|
+
* @param body - The parsed POST body.
|
|
83
|
+
* @returns The negotiated version, or `undefined` when the body contains no
|
|
84
|
+
* `initialize` request.
|
|
67
85
|
*/
|
|
68
|
-
function
|
|
86
|
+
function negotiateInitProtocolVersion(body: unknown): string | undefined {
|
|
69
87
|
const messages = Array.isArray(body) ? body : [body];
|
|
70
88
|
for (const message of messages) {
|
|
71
89
|
if (isInitializeRequest(message)) {
|
|
72
90
|
const protocolVersion = (
|
|
73
91
|
message as { params?: { protocolVersion?: unknown } }
|
|
74
92
|
).params?.protocolVersion;
|
|
75
|
-
if (typeof protocolVersion
|
|
93
|
+
if (typeof protocolVersion !== "string") continue;
|
|
94
|
+
return (SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(
|
|
95
|
+
protocolVersion,
|
|
96
|
+
)
|
|
97
|
+
? protocolVersion
|
|
98
|
+
: LATEST_PROTOCOL_VERSION;
|
|
76
99
|
}
|
|
77
100
|
}
|
|
78
101
|
return undefined;
|
|
@@ -273,17 +296,41 @@ export class McpInitializer extends Initializer {
|
|
|
273
296
|
|
|
274
297
|
const sessionId = req.headers.get("mcp-session-id");
|
|
275
298
|
|
|
299
|
+
// Validate the JSON-RPC envelope of every POST before it reaches a
|
|
300
|
+
// transport. The SDK transport answers both "not JSON" and "not a
|
|
301
|
+
// JSON-RPC message" with `-32700 Parse error`; JSON-RPC 2.0 reserves that
|
|
302
|
+
// code for unparseable input and requires `-32600 Invalid Request` for a
|
|
303
|
+
// payload that parses but isn't a valid message. Parsing here also means
|
|
304
|
+
// the body is read exactly once — the result is handed to the transport as
|
|
305
|
+
// `parsedBody`.
|
|
306
|
+
let body: unknown;
|
|
307
|
+
if (method === "POST") {
|
|
308
|
+
try {
|
|
309
|
+
body = await req.json();
|
|
310
|
+
} catch {
|
|
311
|
+
return mcpJsonRpcErrorResponse(
|
|
312
|
+
MCP_JSONRPC_ERROR.PARSE_ERROR,
|
|
313
|
+
"Parse error: body is not valid JSON",
|
|
314
|
+
400,
|
|
315
|
+
corsHeaders,
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
const invalid = validateJsonRpcPayload(body);
|
|
319
|
+
if (invalid) {
|
|
320
|
+
return mcpJsonRpcErrorResponse(
|
|
321
|
+
invalid.code,
|
|
322
|
+
invalid.message,
|
|
323
|
+
400,
|
|
324
|
+
corsHeaders,
|
|
325
|
+
);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
276
329
|
if (method === "POST" && !sessionId) {
|
|
277
330
|
// Only an `initialize` request may create a new session. Any other
|
|
278
331
|
// request without a session id is a protocol error → 400. We must gate
|
|
279
332
|
// here rather than delegating, otherwise a non-initialize POST spins up
|
|
280
333
|
// an McpServer that never initializes and leaks into `mcpServers`.
|
|
281
|
-
let body: unknown;
|
|
282
|
-
try {
|
|
283
|
-
body = await req.clone().json();
|
|
284
|
-
} catch {
|
|
285
|
-
return mcpJsonResponse({ error: "Invalid JSON" }, 400, corsHeaders);
|
|
286
|
-
}
|
|
287
334
|
const isInit = Array.isArray(body)
|
|
288
335
|
? body.some(isInitializeRequest)
|
|
289
336
|
: isInitializeRequest(body);
|
|
@@ -294,7 +341,7 @@ export class McpInitializer extends Initializer {
|
|
|
294
341
|
corsHeaders,
|
|
295
342
|
);
|
|
296
343
|
}
|
|
297
|
-
const protocolVersion =
|
|
344
|
+
const protocolVersion = negotiateInitProtocolVersion(body);
|
|
298
345
|
|
|
299
346
|
// New session — create a new McpServer + transport
|
|
300
347
|
const mcpServer = createMcpServer();
|
|
@@ -338,7 +385,13 @@ export class McpInitializer extends Initializer {
|
|
|
338
385
|
for (const hook of api.hooks.mcp.onMessageHooks) {
|
|
339
386
|
await hook(undefined);
|
|
340
387
|
}
|
|
341
|
-
return handleTransportRequest(
|
|
388
|
+
return handleTransportRequest(
|
|
389
|
+
transport,
|
|
390
|
+
req,
|
|
391
|
+
authInfo,
|
|
392
|
+
corsHeaders,
|
|
393
|
+
body,
|
|
394
|
+
);
|
|
342
395
|
}
|
|
343
396
|
|
|
344
397
|
if (sessionId) {
|
|
@@ -386,7 +439,13 @@ export class McpInitializer extends Initializer {
|
|
|
386
439
|
for (const hook of api.hooks.mcp.onMessageHooks) {
|
|
387
440
|
await hook(sessionId);
|
|
388
441
|
}
|
|
389
|
-
return handleTransportRequest(
|
|
442
|
+
return handleTransportRequest(
|
|
443
|
+
transport,
|
|
444
|
+
req,
|
|
445
|
+
authInfo,
|
|
446
|
+
corsHeaders,
|
|
447
|
+
body,
|
|
448
|
+
);
|
|
390
449
|
}
|
|
391
450
|
|
|
392
451
|
// GET/DELETE without session ID
|
package/package.json
CHANGED
package/util/mcpServer.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/
|
|
|
6
6
|
import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
7
7
|
import {
|
|
8
8
|
DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
|
|
9
|
+
JSONRPCMessageSchema,
|
|
9
10
|
type ServerNotification,
|
|
10
11
|
type ServerRequest,
|
|
11
12
|
SUPPORTED_PROTOCOL_VERSIONS,
|
|
@@ -137,15 +138,27 @@ export async function isMcpSessionAuthorizedForChannel(
|
|
|
137
138
|
/**
|
|
138
139
|
* Forward a request to an MCP transport and return the response with CORS headers.
|
|
139
140
|
* Handles the try/catch + error response pattern shared by new-session and existing-session paths.
|
|
141
|
+
*
|
|
142
|
+
* @param transport - The session's Streamable HTTP transport.
|
|
143
|
+
* @param req - The inbound MCP request.
|
|
144
|
+
* @param authInfo - Verified bearer-token context for the request, if any.
|
|
145
|
+
* @param corsHeaders - CORS headers to append to whatever the transport returns.
|
|
146
|
+
* @param parsedBody - The already-parsed POST body, so the transport doesn't
|
|
147
|
+
* re-read (and re-parse) a stream Keryx has already consumed while validating
|
|
148
|
+
* the JSON-RPC envelope. Omit for GET/DELETE.
|
|
140
149
|
*/
|
|
141
150
|
export async function handleTransportRequest(
|
|
142
151
|
transport: WebStandardStreamableHTTPServerTransport,
|
|
143
152
|
req: Request,
|
|
144
153
|
authInfo: McpAuthInfo | undefined,
|
|
145
154
|
corsHeaders: Record<string, string>,
|
|
155
|
+
parsedBody?: unknown,
|
|
146
156
|
): Promise<Response> {
|
|
147
157
|
try {
|
|
148
|
-
const response = await transport.handleRequest(req, {
|
|
158
|
+
const response = await transport.handleRequest(req, {
|
|
159
|
+
authInfo,
|
|
160
|
+
parsedBody,
|
|
161
|
+
});
|
|
149
162
|
return appendHeaders(response, corsHeaders);
|
|
150
163
|
} catch (e) {
|
|
151
164
|
logger.error(`MCP transport error: ${e}`);
|
|
@@ -181,6 +194,79 @@ export function mcpJsonResponse(
|
|
|
181
194
|
});
|
|
182
195
|
}
|
|
183
196
|
|
|
197
|
+
/**
|
|
198
|
+
* The JSON-RPC 2.0 error codes the MCP endpoint returns for a POST body it
|
|
199
|
+
* refuses to dispatch. `PARSE_ERROR` means the body was not JSON at all;
|
|
200
|
+
* `INVALID_REQUEST` means it was JSON but not a well-formed JSON-RPC message.
|
|
201
|
+
* The distinction matters: the MCP SDK transport reports both as `PARSE_ERROR`,
|
|
202
|
+
* which conformance checkers flag, so Keryx validates the envelope itself
|
|
203
|
+
* before handing the body to the transport.
|
|
204
|
+
*/
|
|
205
|
+
export const MCP_JSONRPC_ERROR = {
|
|
206
|
+
PARSE_ERROR: -32700,
|
|
207
|
+
INVALID_REQUEST: -32600,
|
|
208
|
+
} as const;
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Build a JSON-RPC *error response* for a message that could never be
|
|
212
|
+
* dispatched. `id` is always `null`: JSON-RPC 2.0 requires a null id when the
|
|
213
|
+
* request's id can't be determined, and the Streamable HTTP transport spec says
|
|
214
|
+
* the body of a rejected POST may carry an error response with no id.
|
|
215
|
+
*
|
|
216
|
+
* @param code - JSON-RPC error code (see {@link MCP_JSONRPC_ERROR}).
|
|
217
|
+
* @param message - Human-readable explanation, surfaced to the client verbatim.
|
|
218
|
+
* @param status - HTTP status to pair with it (400 for malformed input).
|
|
219
|
+
* @param corsHeaders - CORS headers for the MCP endpoint.
|
|
220
|
+
*/
|
|
221
|
+
export function mcpJsonRpcErrorResponse(
|
|
222
|
+
code: number,
|
|
223
|
+
message: string,
|
|
224
|
+
status: number,
|
|
225
|
+
corsHeaders: Record<string, string>,
|
|
226
|
+
): Response {
|
|
227
|
+
return mcpJsonResponse(
|
|
228
|
+
{ jsonrpc: "2.0", error: { code, message }, id: null },
|
|
229
|
+
status,
|
|
230
|
+
corsHeaders,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Validate a parsed MCP POST body against the JSON-RPC message schema, so a
|
|
236
|
+
* structurally invalid message is rejected as `-32600 Invalid Request` rather
|
|
237
|
+
* than being mislabeled a parse error by the transport.
|
|
238
|
+
*
|
|
239
|
+
* Accepts a single request, notification, or response — and, for clients still
|
|
240
|
+
* on protocol 2025-03-26, a non-empty array of them. Every element of an array
|
|
241
|
+
* must be well-formed; one bad message rejects the whole POST, matching how the
|
|
242
|
+
* transport dispatches batches.
|
|
243
|
+
*
|
|
244
|
+
* @param body - The already-parsed JSON body of the POST.
|
|
245
|
+
* @returns `undefined` when the body is well-formed, otherwise the JSON-RPC
|
|
246
|
+
* `code`/`message` pair to return with HTTP 400.
|
|
247
|
+
*/
|
|
248
|
+
export function validateJsonRpcPayload(
|
|
249
|
+
body: unknown,
|
|
250
|
+
): { code: number; message: string } | undefined {
|
|
251
|
+
const messages = Array.isArray(body) ? body : [body];
|
|
252
|
+
if (messages.length === 0) {
|
|
253
|
+
return {
|
|
254
|
+
code: MCP_JSONRPC_ERROR.INVALID_REQUEST,
|
|
255
|
+
message: "Invalid Request: JSON-RPC batch must not be empty",
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
for (const message of messages) {
|
|
259
|
+
if (!JSONRPCMessageSchema.safeParse(message).success) {
|
|
260
|
+
return {
|
|
261
|
+
code: MCP_JSONRPC_ERROR.INVALID_REQUEST,
|
|
262
|
+
message:
|
|
263
|
+
"Invalid Request: body must be a JSON-RPC request, notification, or response",
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
|
|
184
270
|
/**
|
|
185
271
|
* A record in the shared (Redis-backed) MCP session registry. This is the
|
|
186
272
|
* cluster-wide source of truth for whether a Streamable HTTP session exists and
|