keryx 0.35.3 → 0.36.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.
@@ -29,4 +29,10 @@ export const configServerMcp = {
29
29
  ), // 30 days, in seconds
30
30
  oauthTrustProxy: await loadFromEnvIfSet("MCP_OAUTH_TRUST_PROXY", false),
31
31
  markdownDepthLimit: await loadFromEnvIfSet("MCP_MARKDOWN_DEPTH_LIMIT", 5),
32
+ // TTL (seconds) for the shared MCP session registry in Redis. Every MCP
33
+ // request refreshes it, so this is an idle timeout: a session is reclaimed
34
+ // once no node has served a request for it within this window. Because the
35
+ // registry is shared, any node in a cluster can serve any session until it
36
+ // expires. Defaults to 24 hours.
37
+ sessionTtl: await loadFromEnvIfSet("MCP_SESSION_TTL", 60 * 60 * 24),
32
38
  };
@@ -1,5 +1,6 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
3
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
3
4
  import { randomUUID } from "crypto";
4
5
  import { api, logger } from "../api";
5
6
  import { Initializer } from "../classes/Initializer";
@@ -13,13 +14,19 @@ import {
13
14
  isOriginAllowed,
14
15
  } from "../util/http";
15
16
  import {
17
+ adoptMcpSession,
16
18
  createMcpServer,
19
+ forgetMcpSession,
17
20
  formatToolName,
18
21
  handleTransportRequest,
19
22
  type McpAuthInfo,
20
23
  mcpJsonResponse,
21
24
  parseToolName,
25
+ readMcpSessionRecord,
26
+ refreshMcpSessionTtl,
22
27
  sanitizeSchemaForMcp,
28
+ terminateMcpSession,
29
+ writeMcpSessionRecord,
23
30
  } from "../util/mcpServer";
24
31
  import type { PubSubMessage } from "./pubsub";
25
32
 
@@ -50,6 +57,24 @@ export type OnMcpDisconnectHook = (sessionId: string) => Promise<void> | void;
50
57
 
51
58
  const namespace = "mcp";
52
59
 
60
+ /**
61
+ * Pull the negotiated `protocolVersion` out of an `initialize` request body
62
+ * (single message or batch) so it can be stored in the shared session registry
63
+ * and replayed when the session is adopted on another node.
64
+ */
65
+ function extractInitProtocolVersion(body: unknown): string | undefined {
66
+ const messages = Array.isArray(body) ? body : [body];
67
+ for (const message of messages) {
68
+ if (isInitializeRequest(message)) {
69
+ const protocolVersion = (
70
+ message as { params?: { protocolVersion?: unknown } }
71
+ ).params?.protocolVersion;
72
+ if (typeof protocolVersion === "string") return protocolVersion;
73
+ }
74
+ }
75
+ return undefined;
76
+ }
77
+
53
78
  declare module "keryx" {
54
79
  export interface API {
55
80
  [namespace]: Awaited<ReturnType<McpInitializer["initialize"]>>;
@@ -217,6 +242,28 @@ export class McpInitializer extends Initializer {
217
242
  const sessionId = req.headers.get("mcp-session-id");
218
243
 
219
244
  if (method === "POST" && !sessionId) {
245
+ // Only an `initialize` request may create a new session. Any other
246
+ // request without a session id is a protocol error → 400. We must gate
247
+ // here rather than delegating, otherwise a non-initialize POST spins up
248
+ // an McpServer that never initializes and leaks into `mcpServers`.
249
+ let body: unknown;
250
+ try {
251
+ body = await req.clone().json();
252
+ } catch {
253
+ return mcpJsonResponse({ error: "Invalid JSON" }, 400, corsHeaders);
254
+ }
255
+ const isInit = Array.isArray(body)
256
+ ? body.some(isInitializeRequest)
257
+ : isInitializeRequest(body);
258
+ if (!isInit) {
259
+ return mcpJsonResponse(
260
+ { error: "Mcp-Session-Id header required" },
261
+ 400,
262
+ corsHeaders,
263
+ );
264
+ }
265
+ const protocolVersion = extractInitProtocolVersion(body);
266
+
220
267
  // New session — create a new McpServer + transport
221
268
  const mcpServer = createMcpServer();
222
269
  mcpServers.push(mcpServer);
@@ -226,29 +273,26 @@ export class McpInitializer extends Initializer {
226
273
  sessionIdGenerator: () => randomUUID(),
227
274
  enableJsonResponse: true,
228
275
  onsessioninitialized: async (sid) => {
276
+ // Publish to the shared registry first so any node in the cluster
277
+ // can validate/adopt the session, then register locally + fire
278
+ // onConnect (once, on this originating node only).
279
+ await writeMcpSessionRecord(sid, {
280
+ clientId: sessionClientId,
281
+ protocolVersion,
282
+ createdAt: Date.now(),
283
+ });
229
284
  transports.set(sid, { transport, clientId: sessionClientId });
230
285
  for (const hook of api.hooks.mcp.onConnectHooks) {
231
286
  await hook(sid);
232
287
  }
233
288
  },
234
- onsessionclosed: (sid) => {
235
- transports.delete(sid);
236
- const idx = mcpServers.indexOf(mcpServer);
237
- if (idx !== -1) mcpServers.splice(idx, 1);
238
- },
289
+ // Fires on explicit client DELETE: terminate the session cluster-wide.
290
+ onsessionclosed: (sid) => terminateMcpSession(sid, mcpServer),
239
291
  });
240
-
241
- transport.onclose = async () => {
242
- const sid = transport.sessionId;
243
- if (sid) {
244
- transports.delete(sid);
245
- for (const hook of api.hooks.mcp.onDisconnectHooks) {
246
- await hook(sid);
247
- }
248
- }
249
- const idx = mcpServers.indexOf(mcpServer);
250
- if (idx !== -1) mcpServers.splice(idx, 1);
251
- };
292
+ // Fires on any close (incl. server shutdown): local cleanup only, so a
293
+ // node bouncing never removes a session other nodes may still serve.
294
+ transport.onclose = () =>
295
+ forgetMcpSession(transport.sessionId, mcpServer);
252
296
 
253
297
  await mcpServer.connect(transport);
254
298
 
@@ -259,8 +303,18 @@ export class McpInitializer extends Initializer {
259
303
  }
260
304
 
261
305
  if (sessionId) {
262
- const session = transports.get(sessionId);
263
- if (!session) {
306
+ // The shared Redis registry — not the node-local map — is the source of
307
+ // truth for session existence and ownership, so a request that a load
308
+ // balancer routes to any node resolves consistently.
309
+ const record = await readMcpSessionRecord(sessionId);
310
+ if (!record) {
311
+ // Unknown/expired session → 404 (the client's cue to re-`initialize`).
312
+ // Evict any stale local transport so it can never bypass this gate.
313
+ const stale = transports.get(sessionId);
314
+ if (stale) {
315
+ transports.delete(sessionId);
316
+ void stale.transport.close();
317
+ }
264
318
  return mcpJsonResponse(
265
319
  { error: "Session not found" },
266
320
  404,
@@ -268,7 +322,7 @@ export class McpInitializer extends Initializer {
268
322
  );
269
323
  }
270
324
 
271
- if (session.clientId !== authInfo.clientId) {
325
+ if (record.clientId !== authInfo.clientId) {
272
326
  return mcpJsonResponse(
273
327
  { error: "Token does not match session" },
274
328
  403,
@@ -276,15 +330,23 @@ export class McpInitializer extends Initializer {
276
330
  );
277
331
  }
278
332
 
333
+ // Use the live local transport, or adopt the session onto this node by
334
+ // re-materializing it from the shared record.
335
+ let transport = transports.get(sessionId)?.transport;
336
+ if (!transport) {
337
+ transport = await adoptMcpSession(
338
+ sessionId,
339
+ record.clientId,
340
+ record.protocolVersion,
341
+ );
342
+ }
343
+
344
+ await refreshMcpSessionTtl(sessionId);
345
+
279
346
  for (const hook of api.hooks.mcp.onMessageHooks) {
280
347
  await hook(sessionId);
281
348
  }
282
- return handleTransportRequest(
283
- session.transport,
284
- req,
285
- authInfo,
286
- corsHeaders,
287
- );
349
+ return handleTransportRequest(transport, req, authInfo, corsHeaders);
288
350
  }
289
351
 
290
352
  // GET/DELETE without session ID
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keryx",
3
- "version": "0.35.3",
3
+ "version": "0.36.1",
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/util/mcpServer.ts CHANGED
@@ -2,11 +2,13 @@ import {
2
2
  McpServer,
3
3
  ResourceTemplate,
4
4
  } from "@modelcontextprotocol/sdk/server/mcp.js";
5
- import type { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
5
+ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
6
6
  import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
7
- import type {
8
- ServerNotification,
9
- ServerRequest,
7
+ import {
8
+ DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
9
+ type ServerNotification,
10
+ type ServerRequest,
11
+ SUPPORTED_PROTOCOL_VERSIONS,
10
12
  } from "@modelcontextprotocol/sdk/types.js";
11
13
  import { randomUUID } from "crypto";
12
14
  import * as z4mini from "zod/v4-mini";
@@ -123,6 +125,238 @@ export function mcpJsonResponse(
123
125
  });
124
126
  }
125
127
 
128
+ /**
129
+ * A record in the shared (Redis-backed) MCP session registry. This is the
130
+ * cluster-wide source of truth for whether a Streamable HTTP session exists and
131
+ * which OAuth client owns it. The live transport/`McpServer` objects are
132
+ * node-local (like a WebSocket socket) and are re-materialized on demand via
133
+ * {@link adoptMcpSession} when a request lands on a node that doesn't hold them.
134
+ */
135
+ export interface McpSessionRecord {
136
+ /** OAuth client id bound to the session; enforced on every request (403 on mismatch). */
137
+ clientId: string;
138
+ /** Protocol version negotiated at `initialize`, replayed when adopting on another node. */
139
+ protocolVersion?: string;
140
+ /** Creation timestamp (ms since epoch). */
141
+ createdAt: number;
142
+ }
143
+
144
+ /** Redis key for a session registry record. */
145
+ export function mcpSessionKey(sessionId: string): string {
146
+ return `mcp:session:${sessionId}`;
147
+ }
148
+
149
+ /**
150
+ * Write (or overwrite) a session registry record with the configured TTL.
151
+ * Called once, on the node that runs the real `initialize` handshake.
152
+ *
153
+ * @param sessionId - The transport session id (`Mcp-Session-Id`).
154
+ * @param record - The record to persist.
155
+ */
156
+ export async function writeMcpSessionRecord(
157
+ sessionId: string,
158
+ record: McpSessionRecord,
159
+ ): Promise<void> {
160
+ await api.redis.redis.set(
161
+ mcpSessionKey(sessionId),
162
+ JSON.stringify(record),
163
+ "EX",
164
+ config.server.mcp.sessionTtl,
165
+ );
166
+ }
167
+
168
+ /**
169
+ * Read a session registry record. Returns `null` when the session is unknown or
170
+ * expired — the caller must treat that as a 404 (the client's cue to re-`initialize`).
171
+ *
172
+ * @param sessionId - The transport session id (`Mcp-Session-Id`).
173
+ */
174
+ export async function readMcpSessionRecord(
175
+ sessionId: string,
176
+ ): Promise<McpSessionRecord | null> {
177
+ const raw = await api.redis.redis.get(mcpSessionKey(sessionId));
178
+ return raw ? (JSON.parse(raw) as McpSessionRecord) : null;
179
+ }
180
+
181
+ /**
182
+ * Refresh the TTL on a session registry record. Called on every request so the
183
+ * TTL behaves as an idle timeout across the cluster.
184
+ *
185
+ * @param sessionId - The transport session id (`Mcp-Session-Id`).
186
+ */
187
+ export async function refreshMcpSessionTtl(sessionId: string): Promise<void> {
188
+ await api.redis.redis.expire(
189
+ mcpSessionKey(sessionId),
190
+ config.server.mcp.sessionTtl,
191
+ );
192
+ }
193
+
194
+ /**
195
+ * Delete a session registry record.
196
+ *
197
+ * @param sessionId - The transport session id (`Mcp-Session-Id`).
198
+ * @returns The number of keys removed (`1` if this call actually deleted the
199
+ * record, `0` if it was already gone) — used to fire `onDisconnect` hooks
200
+ * exactly once across the cluster.
201
+ */
202
+ export async function deleteMcpSessionRecord(
203
+ sessionId: string,
204
+ ): Promise<number> {
205
+ return api.redis.redis.del(mcpSessionKey(sessionId));
206
+ }
207
+
208
+ /**
209
+ * Local teardown of an MCP session: drop the transport and its `McpServer` from
210
+ * this node's in-memory maps. Does NOT touch the shared Redis registry, because
211
+ * this also runs on server shutdown (`transport.close()` → `onclose`), where the
212
+ * session may still be live and adoptable on other nodes.
213
+ *
214
+ * @param sessionId - The transport session id, or `undefined` if never initialized.
215
+ * @param mcpServer - The `McpServer` bound to the closing transport.
216
+ */
217
+ export function forgetMcpSession(
218
+ sessionId: string | undefined,
219
+ mcpServer: McpServer,
220
+ ): void {
221
+ if (sessionId) api.mcp.transports.delete(sessionId);
222
+ const idx = api.mcp.mcpServers.indexOf(mcpServer);
223
+ if (idx !== -1) api.mcp.mcpServers.splice(idx, 1);
224
+ }
225
+
226
+ /**
227
+ * Full teardown triggered by an explicit client `DELETE` (`onsessionclosed`):
228
+ * drop local state, delete the shared Redis record (so every node then 404s),
229
+ * and — exactly once across the cluster, gated on the delete actually removing
230
+ * the key — run the `onDisconnect` hooks.
231
+ *
232
+ * @param sessionId - The transport session id being terminated.
233
+ * @param mcpServer - The `McpServer` bound to the closing transport.
234
+ */
235
+ export async function terminateMcpSession(
236
+ sessionId: string,
237
+ mcpServer: McpServer,
238
+ ): Promise<void> {
239
+ forgetMcpSession(sessionId, mcpServer);
240
+ const removed = await deleteMcpSessionRecord(sessionId);
241
+ if (removed === 1) {
242
+ for (const hook of api.hooks.mcp.onDisconnectHooks) {
243
+ await hook(sessionId);
244
+ }
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Drive a synthetic `initialize` request through a freshly-created transport so
250
+ * it enters `{ sessionId, initialized: true }` state without a real client
251
+ * round-trip. The initialize response is discarded; awaiting it guarantees the
252
+ * connected `McpServer` finished its handshake before the caller dispatches the
253
+ * real request. Uses only the SDK's public `handleRequest` API.
254
+ *
255
+ * @param transport - A connected transport whose `sessionIdGenerator` returns the target session id.
256
+ * @param protocolVersion - The version negotiated on the originating node, if known.
257
+ */
258
+ async function driveSyntheticInitialize(
259
+ transport: WebStandardStreamableHTTPServerTransport,
260
+ protocolVersion: string | undefined,
261
+ ): Promise<void> {
262
+ const negotiatedVersion =
263
+ protocolVersion &&
264
+ (SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(protocolVersion)
265
+ ? protocolVersion
266
+ : DEFAULT_NEGOTIATED_PROTOCOL_VERSION;
267
+
268
+ const initBody = {
269
+ jsonrpc: "2.0" as const,
270
+ id: `keryx-adopt-${randomUUID()}`,
271
+ method: "initialize",
272
+ params: {
273
+ protocolVersion: negotiatedVersion,
274
+ capabilities: {},
275
+ clientInfo: { name: "keryx-adopt", version: pkg.version },
276
+ },
277
+ };
278
+
279
+ // Accept must list both content types and Content-Type must be JSON, or the
280
+ // SDK rejects the POST before it ever inspects the (pre-parsed) body.
281
+ const req = new Request("http://keryx.internal/mcp", {
282
+ method: "POST",
283
+ headers: {
284
+ "Content-Type": "application/json",
285
+ Accept: "application/json, text/event-stream",
286
+ },
287
+ });
288
+
289
+ await transport.handleRequest(req, { parsedBody: initBody });
290
+ }
291
+
292
+ /** In-flight adoptions, keyed by session id, so concurrent requests for the same
293
+ * not-yet-local session share one transport instead of racing to build several. */
294
+ const adoptionsInFlight = new Map<
295
+ string,
296
+ Promise<WebStandardStreamableHTTPServerTransport>
297
+ >();
298
+
299
+ /**
300
+ * Re-materialize a session that exists in the shared registry but has no live
301
+ * transport on this node (e.g. a load balancer routed a later request to a
302
+ * different node than the one that ran `initialize`). Creates a fresh
303
+ * `McpServer` + transport bound to `sessionId`, drives a synthetic `initialize`
304
+ * to bring it to initialized state, registers it locally, and returns it ready
305
+ * to serve the real request.
306
+ *
307
+ * Adopted transports intentionally do NOT re-run `onConnect` hooks or re-write
308
+ * the Redis record — those already happened on the originating node. They DO
309
+ * wire teardown so a `DELETE` routed here still terminates the session cluster-wide.
310
+ *
311
+ * @param sessionId - The transport session id to adopt.
312
+ * @param clientId - The OAuth client id that owns the session (from the registry record).
313
+ * @param protocolVersion - The negotiated protocol version from the registry record, if any.
314
+ * @returns The connected, initialized transport (also registered in `api.mcp.transports`).
315
+ */
316
+ export async function adoptMcpSession(
317
+ sessionId: string,
318
+ clientId: string,
319
+ protocolVersion: string | undefined,
320
+ ): Promise<WebStandardStreamableHTTPServerTransport> {
321
+ const inFlight = adoptionsInFlight.get(sessionId);
322
+ if (inFlight) return inFlight;
323
+
324
+ const promise = (async () => {
325
+ const mcpServer = createMcpServer();
326
+ api.mcp.mcpServers.push(mcpServer);
327
+ try {
328
+ const transport = new WebStandardStreamableHTTPServerTransport({
329
+ sessionIdGenerator: () => sessionId,
330
+ enableJsonResponse: true,
331
+ // Local registration only — no hooks, no registry write (see doc above).
332
+ onsessioninitialized: (sid) => {
333
+ api.mcp.transports.set(sid, { transport, clientId });
334
+ },
335
+ onsessionclosed: (sid) => terminateMcpSession(sid, mcpServer),
336
+ });
337
+ transport.onclose = () =>
338
+ forgetMcpSession(transport.sessionId, mcpServer);
339
+
340
+ await mcpServer.connect(transport);
341
+ await driveSyntheticInitialize(transport, protocolVersion);
342
+ return transport;
343
+ } catch (e) {
344
+ // Adoption failed partway (e.g. the synthetic initialize errored) — drop
345
+ // the McpServer we optimistically registered so it can't linger in the
346
+ // broadcast list nor leave a half-initialized transport behind.
347
+ forgetMcpSession(sessionId, mcpServer);
348
+ throw e;
349
+ }
350
+ })();
351
+
352
+ adoptionsInFlight.set(sessionId, promise);
353
+ try {
354
+ return await promise;
355
+ } finally {
356
+ adoptionsInFlight.delete(sessionId);
357
+ }
358
+ }
359
+
126
360
  /**
127
361
  * Create a new McpServer instance with all actions registered as tools, resources, and prompts.
128
362
  * Each MCP session gets its own McpServer (the SDK requires 1:1 mapping).