keryx 0.47.0 → 0.48.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/classes/Action.ts CHANGED
@@ -97,6 +97,15 @@ export type McpActionConfig = {
97
97
  * via `ui` implies a tool unless `tool` is explicitly `false`.
98
98
  */
99
99
  tool?: boolean;
100
+ /**
101
+ * Allow anonymous MCP clients to use this action. Only takes effect when the
102
+ * server runs with `MCP_AUTH_MODE=optional`: a client without a bearer token
103
+ * may then call this tool, read this resource or prompt, or load this MCP App
104
+ * UI. Anonymous calls to non-public actions get a 401 challenge so the client
105
+ * can authenticate. Has no effect in the default `required` mode, and never
106
+ * changes HTTP/WebSocket access — that is still governed by `middleware`.
107
+ */
108
+ public?: boolean;
100
109
  /** Tag as the OAuth login action */
101
110
  isLoginAction?: boolean;
102
111
  /** Tag as the OAuth signup action */
@@ -19,4 +19,14 @@ export const configRateLimit = {
19
19
  "RATE_LIMIT_OAUTH_REGISTER_WINDOW_MS",
20
20
  3_600_000,
21
21
  ),
22
+ /** Stricter limit on new anonymous MCP sessions (`initialize` without a token), per IP per window. */
23
+ mcpAnonymousInitLimit: await loadFromEnvIfSet(
24
+ "RATE_LIMIT_MCP_ANON_INIT_LIMIT",
25
+ 10,
26
+ ),
27
+ /** Window for the anonymous MCP session-creation rate limit (default: 1 minute). */
28
+ mcpAnonymousInitWindowMs: await loadFromEnvIfSet(
29
+ "RATE_LIMIT_MCP_ANON_INIT_WINDOW_MS",
30
+ 60_000,
31
+ ),
22
32
  };
@@ -4,6 +4,12 @@ import { loadFromEnvIfSet } from "../../util/config";
4
4
  export const configServerMcp = {
5
5
  enabled: await loadFromEnvIfSet("MCP_SERVER_ENABLED", false),
6
6
  route: await loadFromEnvIfSet("MCP_SERVER_ROUTE", "/mcp"),
7
+ // `"required"` (default): every MCP request must carry a valid OAuth bearer
8
+ // token. `"optional"`: requests without a token are served as anonymous
9
+ // sessions that may only use actions marked `mcp.public`; calling anything
10
+ // else returns a 401 challenge so the client can authenticate and upgrade
11
+ // the session. An invalid or expired token is always rejected with 401.
12
+ authMode: await loadFromEnvIfSet("MCP_AUTH_MODE", "required"),
7
13
  allowedOrigins: await loadFromEnvIfSet(
8
14
  "MCP_ALLOWED_ORIGINS",
9
15
  [
@@ -59,4 +65,11 @@ export const configServerMcp = {
59
65
  // registry is shared, any node in a cluster can serve any session until it
60
66
  // expires. Defaults to 24 hours.
61
67
  sessionTtl: await loadFromEnvIfSet("MCP_SESSION_TTL", 60 * 60 * 24),
68
+ // Idle TTL (seconds) for anonymous sessions (`authMode: "optional"`), kept
69
+ // shorter than `sessionTtl` so floods of throwaway sessions age out quickly.
70
+ // A session that upgrades to an authenticated one switches to `sessionTtl`.
71
+ anonymousSessionTtl: await loadFromEnvIfSet(
72
+ "MCP_ANONYMOUS_SESSION_TTL",
73
+ 60 * 60,
74
+ ),
62
75
  };
@@ -10,6 +10,10 @@ import { api, logger } from "../api";
10
10
  import { Initializer } from "../classes/Initializer";
11
11
  import { ErrorType, TypedError } from "../classes/TypedError";
12
12
  import { config } from "../config";
13
+ import {
14
+ checkRateLimit,
15
+ rateLimitExceededResponse,
16
+ } from "../middleware/rateLimit";
13
17
  import { ansi } from "../util/ansi";
14
18
  import {
15
19
  buildCorsHeaders,
@@ -20,10 +24,14 @@ import {
20
24
  import { resolveMcpAppUiResources } from "../util/mcpAppBundler";
21
25
  import {
22
26
  adoptMcpSession,
27
+ buildAnonymousMcpAuthInfo,
23
28
  createMcpServer,
29
+ findMcpTargetAction,
24
30
  forgetMcpSession,
25
31
  formatToolName,
26
32
  handleTransportRequest,
33
+ isAnonymousMcpAuth,
34
+ isMcpAccessAllowed,
27
35
  isMcpSessionAuthorizedForChannel,
28
36
  MCP_JSONRPC_ERROR,
29
37
  type McpAuthInfo,
@@ -35,6 +43,8 @@ import {
35
43
  refreshMcpSessionTtl,
36
44
  sanitizeSchemaForMcp,
37
45
  terminateMcpSession,
46
+ unlockMcpServer,
47
+ upgradeAnonymousMcpSession,
38
48
  validateJsonRpcPayload,
39
49
  writeMcpSessionRecord,
40
50
  } from "../util/mcpServer";
@@ -67,6 +77,83 @@ export type OnMcpDisconnectHook = (sessionId: string) => Promise<void> | void;
67
77
 
68
78
  const namespace = "mcp";
69
79
 
80
+ /** A live, node-local MCP session: its transport, owning client, and server. */
81
+ export type McpTransportEntry = {
82
+ transport: WebStandardStreamableHTTPServerTransport;
83
+ /** OAuth client id that owns the session (the anonymous sentinel if anonymous). */
84
+ clientId: string;
85
+ /** The `McpServer` connected to `transport`. */
86
+ mcpServer: McpServer;
87
+ /**
88
+ * `true` while the server still hides non-public entries from an anonymous
89
+ * session; cleared (via `unlockMcpServer`) once the session upgrades.
90
+ */
91
+ anonymous: boolean;
92
+ };
93
+
94
+ /** Whether a parsed POST body (single message or batch) contains an `initialize` request. */
95
+ function containsInitializeRequest(body: unknown): boolean {
96
+ return Array.isArray(body)
97
+ ? body.some(isInitializeRequest)
98
+ : isInitializeRequest(body);
99
+ }
100
+
101
+ /**
102
+ * Build the 401 response that sends an MCP client into the OAuth flow: a
103
+ * `WWW-Authenticate` challenge pointing at the protected resource metadata
104
+ * (RFC 9728). Returned when a token is missing (in `required` mode), invalid or
105
+ * expired (always), or when an anonymous request targets a protected action or
106
+ * an authenticated session (in `optional` mode).
107
+ */
108
+ function mcpAuthChallenge(
109
+ req: Request,
110
+ corsHeaders: Record<string, string>,
111
+ ): Response {
112
+ const origin = getExternalOrigin(req, new URL(req.url));
113
+ const resourceMetadataUrl = `${origin}/.well-known/oauth-protected-resource${config.server.mcp.route}`;
114
+ return mcpJsonResponse(
115
+ { error: "Authentication required" },
116
+ 401,
117
+ corsHeaders,
118
+ {
119
+ "WWW-Authenticate": `Bearer resource_metadata="${resourceMetadataUrl}", scope="mcp"`,
120
+ },
121
+ );
122
+ }
123
+
124
+ /**
125
+ * Rate-limit an anonymous MCP request by IP: every request counts against the
126
+ * unauthenticated limit, and a session-creating `initialize` also counts
127
+ * against the stricter anonymous-session limit.
128
+ *
129
+ * @returns A 429 response if a limit is exceeded, otherwise `undefined`.
130
+ */
131
+ async function checkAnonymousMcpRateLimit(
132
+ ip: string,
133
+ isInitialize: boolean,
134
+ corsHeaders: Record<string, string>,
135
+ ): Promise<Response | undefined> {
136
+ if (!config.rateLimit.enabled) return undefined;
137
+ const keyPrefix = config.rateLimit.keyPrefix;
138
+ const info = await checkRateLimit(`ip:${ip}`, false, {
139
+ keyPrefix: `${keyPrefix}:mcp-anon`,
140
+ });
141
+ if (info.retryAfter !== undefined) {
142
+ return rateLimitExceededResponse(info, corsHeaders);
143
+ }
144
+ if (isInitialize) {
145
+ const initInfo = await checkRateLimit(`ip:${ip}`, false, {
146
+ limit: config.rateLimit.mcpAnonymousInitLimit,
147
+ windowMs: config.rateLimit.mcpAnonymousInitWindowMs,
148
+ keyPrefix: `${keyPrefix}:mcp-anon-init`,
149
+ });
150
+ if (initInfo.retryAfter !== undefined) {
151
+ return rateLimitExceededResponse(initInfo, corsHeaders);
152
+ }
153
+ }
154
+ return undefined;
155
+ }
156
+
70
157
  /**
71
158
  * Resolve the protocol version an `initialize` request body (single message or
72
159
  * batch) actually negotiates, so it can be stored in the shared session registry
@@ -125,13 +212,7 @@ export class McpInitializer extends Initializer {
125
212
  // Per-session auth context, so a broadcast is delivered only to sessions
126
213
  // whose user is authorized for its channel (see sendNotification).
127
214
  const mcpServerAuth = new Map<McpServer, McpSessionAuth>();
128
- const transports = new Map<
129
- string,
130
- {
131
- transport: WebStandardStreamableHTTPServerTransport;
132
- clientId: string;
133
- }
134
- >();
215
+ const transports = new Map<string, McpTransportEntry>();
135
216
 
136
217
  // Deliver a PubSub broadcast to MCP sessions as a logging notification, but
137
218
  // ONLY to sessions whose user is authorized to subscribe to the broadcast's
@@ -264,35 +345,30 @@ export class McpInitializer extends Initializer {
264
345
  return new Response(null, { status: 405, headers: corsHeaders });
265
346
  }
266
347
 
267
- // Extract and verify Bearer token for auth
348
+ // Extract and verify the Bearer token. A token that is present but
349
+ // invalid or expired is always rejected with 401 (the spec requires it),
350
+ // never downgraded to anonymous access.
268
351
  let authInfo: McpAuthInfo | undefined;
269
352
  const authHeader = req.headers.get("authorization");
270
353
  if (authHeader?.startsWith("Bearer ")) {
271
354
  const token = authHeader.slice(7);
272
355
  const tokenData = await api.oauth.verifyAccessToken(token);
273
- if (tokenData) {
274
- authInfo = {
275
- token,
276
- clientId: tokenData.clientId,
277
- scopes: tokenData.scopes ?? [],
278
- extra: { userId: tokenData.userId, ip },
279
- };
280
- }
281
- }
282
-
283
- // Require authentication — return 401 so MCP clients initiate the OAuth flow
284
- if (!authInfo) {
285
- const origin = getExternalOrigin(req, new URL(req.url));
286
- const resourceMetadataUrl = `${origin}/.well-known/oauth-protected-resource${config.server.mcp.route}`;
287
- return mcpJsonResponse(
288
- { error: "Authentication required" },
289
- 401,
290
- corsHeaders,
291
- {
292
- "WWW-Authenticate": `Bearer resource_metadata="${resourceMetadataUrl}", scope="mcp"`,
293
- },
294
- );
356
+ if (!tokenData) return mcpAuthChallenge(req, corsHeaders);
357
+ authInfo = {
358
+ token,
359
+ clientId: tokenData.clientId,
360
+ scopes: tokenData.scopes ?? [],
361
+ extra: { userId: tokenData.userId, ip },
362
+ };
363
+ } else if (config.server.mcp.authMode === "optional") {
364
+ // No token, but anonymous access is enabled: serve the request as an
365
+ // anonymous session limited to `mcp.public` actions.
366
+ authInfo = buildAnonymousMcpAuthInfo(ip);
367
+ } else {
368
+ // Require authentication — return 401 so MCP clients initiate the OAuth flow
369
+ return mcpAuthChallenge(req, corsHeaders);
295
370
  }
371
+ const isAnonymous = isAnonymousMcpAuth(authInfo);
296
372
 
297
373
  const sessionId = req.headers.get("mcp-session-id");
298
374
 
@@ -326,15 +402,35 @@ export class McpInitializer extends Initializer {
326
402
  }
327
403
  }
328
404
 
405
+ if (isAnonymous) {
406
+ const limited = await checkAnonymousMcpRateLimit(
407
+ ip,
408
+ method === "POST" && !sessionId && containsInitializeRequest(body),
409
+ corsHeaders,
410
+ );
411
+ if (limited) return limited;
412
+
413
+ // Step-up: an anonymous call to a protected tool, prompt, or resource
414
+ // gets a 401 challenge before dispatch, so the client runs the OAuth
415
+ // flow and retries with a token (which upgrades the session below).
416
+ if (method === "POST") {
417
+ const messages = Array.isArray(body) ? body : [body];
418
+ const needsAuth = messages.some((message) => {
419
+ const action = findMcpTargetAction(message);
420
+ return (
421
+ action !== undefined && !isMcpAccessAllowed(action, authInfo)
422
+ );
423
+ });
424
+ if (needsAuth) return mcpAuthChallenge(req, corsHeaders);
425
+ }
426
+ }
427
+
329
428
  if (method === "POST" && !sessionId) {
330
429
  // Only an `initialize` request may create a new session. Any other
331
430
  // request without a session id is a protocol error → 400. We must gate
332
431
  // here rather than delegating, otherwise a non-initialize POST spins up
333
432
  // an McpServer that never initializes and leaks into `mcpServers`.
334
- const isInit = Array.isArray(body)
335
- ? body.some(isInitializeRequest)
336
- : isInitializeRequest(body);
337
- if (!isInit) {
433
+ if (!containsInitializeRequest(body)) {
338
434
  return mcpJsonResponse(
339
435
  { error: "Mcp-Session-Id header required" },
340
436
  400,
@@ -344,7 +440,7 @@ export class McpInitializer extends Initializer {
344
440
  const protocolVersion = negotiateInitProtocolVersion(body);
345
441
 
346
442
  // New session — create a new McpServer + transport
347
- const mcpServer = createMcpServer();
443
+ const mcpServer = createMcpServer({ anonymous: isAnonymous });
348
444
  mcpServers.push(mcpServer);
349
445
  // Capture the session's auth context so channel-broadcast delivery can
350
446
  // authorize this session (see sendNotification).
@@ -366,8 +462,14 @@ export class McpInitializer extends Initializer {
366
462
  clientId: sessionClientId,
367
463
  protocolVersion,
368
464
  createdAt: Date.now(),
465
+ ...(isAnonymous ? { anonymous: true } : {}),
466
+ });
467
+ transports.set(sid, {
468
+ transport,
469
+ clientId: sessionClientId,
470
+ mcpServer,
471
+ anonymous: isAnonymous,
369
472
  });
370
- transports.set(sid, { transport, clientId: sessionClientId });
371
473
  for (const hook of api.hooks.mcp.onConnectHooks) {
372
474
  await hook(sid);
373
475
  }
@@ -398,7 +500,7 @@ export class McpInitializer extends Initializer {
398
500
  // The shared Redis registry — not the node-local map — is the source of
399
501
  // truth for session existence and ownership, so a request that a load
400
502
  // balancer routes to any node resolves consistently.
401
- const record = await readMcpSessionRecord(sessionId);
503
+ let record = await readMcpSessionRecord(sessionId);
402
504
  if (!record) {
403
505
  // Unknown/expired session → 404 (the client's cue to re-`initialize`).
404
506
  // Evict any stale local transport so it can never bypass this gate.
@@ -414,7 +516,31 @@ export class McpInitializer extends Initializer {
414
516
  );
415
517
  }
416
518
 
417
- if (record.clientId !== authInfo.clientId) {
519
+ if (record.anonymous && !isAnonymous) {
520
+ // Upgrade: the first request on an anonymous session that carries a
521
+ // valid token rebinds the session to that token's client (with the
522
+ // authenticated TTL). The swap is atomic, so only one client can
523
+ // ever claim a given anonymous session.
524
+ const current = await upgradeAnonymousMcpSession(
525
+ sessionId,
526
+ record,
527
+ authInfo.clientId,
528
+ );
529
+ if (!current) {
530
+ return mcpJsonResponse(
531
+ { error: "Session not found" },
532
+ 404,
533
+ corsHeaders,
534
+ );
535
+ }
536
+ record = current;
537
+ }
538
+
539
+ if (isAnonymous && !record.anonymous) {
540
+ // Never downgrade an authenticated session to anonymous access.
541
+ return mcpAuthChallenge(req, corsHeaders);
542
+ }
543
+ if (!isAnonymous && record.clientId !== authInfo.clientId) {
418
544
  return mcpJsonResponse(
419
545
  { error: "Token does not match session" },
420
546
  403,
@@ -431,10 +557,26 @@ export class McpInitializer extends Initializer {
431
557
  record.clientId,
432
558
  record.protocolVersion,
433
559
  { userId: authInfo.extra?.userId, ip },
560
+ record.anonymous === true,
434
561
  );
435
562
  }
436
563
 
437
- await refreshMcpSessionTtl(sessionId);
564
+ // The session has been upgraded (here or on another node) but this
565
+ // node's server still hides protected entries: rebind its broadcast
566
+ // auth to the token's user and reveal everything.
567
+ const local = transports.get(sessionId);
568
+ if (local?.anonymous && !record.anonymous) {
569
+ local.anonymous = false;
570
+ local.clientId = record.clientId;
571
+ api.mcp.mcpServerAuth.set(local.mcpServer, {
572
+ clientId: record.clientId,
573
+ userId: authInfo.extra?.userId,
574
+ ip,
575
+ });
576
+ unlockMcpServer(local.mcpServer);
577
+ }
578
+
579
+ await refreshMcpSessionTtl(sessionId, record.anonymous);
438
580
 
439
581
  for (const hook of api.hooks.mcp.onMessageHooks) {
440
582
  await hook(sessionId);
@@ -1,7 +1,10 @@
1
1
  import { api } from "../api";
2
2
  import { Initializer } from "../classes/Initializer";
3
3
  import { config } from "../config";
4
- import { checkRateLimit } from "../middleware/rateLimit";
4
+ import {
5
+ checkRateLimit,
6
+ rateLimitExceededResponse,
7
+ } from "../middleware/rateLimit";
5
8
  import {
6
9
  appendHeaders,
7
10
  buildCorsHeaders,
@@ -121,22 +124,7 @@ export class OAuthInitializer extends Initializer {
121
124
  : undefined;
122
125
  const info = await checkRateLimit(`ip:${ip}`, false, overrides);
123
126
  if (info.retryAfter !== undefined) {
124
- return new Response(
125
- JSON.stringify({
126
- error: "rate_limit_exceeded",
127
- error_description: `Rate limit exceeded. Try again in ${info.retryAfter} seconds.`,
128
- }),
129
- {
130
- status: 429,
131
- headers: {
132
- "Content-Type": "application/json",
133
- "Retry-After": String(info.retryAfter),
134
- "X-RateLimit-Limit": String(info.limit),
135
- "X-RateLimit-Remaining": "0",
136
- "X-RateLimit-Reset": String(info.resetAt),
137
- },
138
- },
139
- );
127
+ return rateLimitExceededResponse(info);
140
128
  }
141
129
  }
142
130
 
@@ -82,6 +82,38 @@ export async function checkRateLimit(
82
82
  return { limit, remaining, resetAt };
83
83
  }
84
84
 
85
+ /**
86
+ * Build the HTTP 429 response for a request that exceeded a rate limit checked
87
+ * outside the action pipeline (OAuth endpoints, the MCP endpoint). The body is
88
+ * an OAuth-style `{ error, error_description }` object, and `Retry-After` plus
89
+ * the `X-RateLimit-*` headers tell the client when to try again.
90
+ *
91
+ * @param info - The result of {@link checkRateLimit}; must have `retryAfter` set.
92
+ * @param extraHeaders - Additional headers to include (e.g. CORS headers).
93
+ */
94
+ export function rateLimitExceededResponse(
95
+ info: RateLimitInfo,
96
+ extraHeaders: Record<string, string> = {},
97
+ ): Response {
98
+ return new Response(
99
+ JSON.stringify({
100
+ error: "rate_limit_exceeded",
101
+ error_description: `Rate limit exceeded. Try again in ${info.retryAfter} seconds.`,
102
+ }),
103
+ {
104
+ status: 429,
105
+ headers: {
106
+ "Content-Type": "application/json",
107
+ ...extraHeaders,
108
+ "Retry-After": String(info.retryAfter),
109
+ "X-RateLimit-Limit": String(info.limit),
110
+ "X-RateLimit-Remaining": "0",
111
+ "X-RateLimit-Reset": String(info.resetAt),
112
+ },
113
+ },
114
+ );
115
+ }
116
+
85
117
  /**
86
118
  * Action middleware that enforces per-connection rate limiting. Add to an action's
87
119
  * `middleware` array to apply. Throws `ErrorType.CONNECTION_RATE_LIMITED` when exceeded.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keryx",
3
- "version": "0.47.0",
3
+ "version": "0.48.1",
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/servers/web.ts CHANGED
@@ -131,6 +131,13 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
131
131
  url: string = "";
132
132
  /** Per-connection message rate tracking (keyed by connection id). */
133
133
  private wsRateMap = new Map<string, { count: number; windowStart: number }>();
134
+ /**
135
+ * Tail of each connection's queue of subscribe/unsubscribe frames (keyed by connection id).
136
+ * Bun doesn't wait for one `message` callback to finish before calling the next, so channel
137
+ * operations are chained here to apply in the order the client sent them. The stored
138
+ * promise never rejects.
139
+ */
140
+ private wsChannelOpQueue = new Map<string, Promise<void>>();
134
141
  /** Set to true when the server is shutting down; rejects new WS upgrades. */
135
142
  private shuttingDown = false;
136
143
 
@@ -419,6 +426,17 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
419
426
  /**
420
427
  * Called when a WebSocket message arrives. Parses JSON, enforces per-connection rate limiting,
421
428
  * and dispatches to action, subscribe, or unsubscribe handlers based on `messageType`.
429
+ *
430
+ * Bun invokes this for each frame without waiting for the previous call to settle, so frames
431
+ * are ordered per connection: subscribe and unsubscribe frames run one at a time, in the order
432
+ * they were sent. An action frame waits for the channel operations sent before it, but doesn't
433
+ * hold up later frames, so actions (including long-running streams) still run concurrently.
434
+ *
435
+ * @param ws - The Bun WebSocket the frame arrived on. Its `data` identifies the {@link Connection}.
436
+ * @param message - The raw frame. Expected to be a JSON object with a `messageType` of
437
+ * `"action"`, `"subscribe"`, or `"unsubscribe"`; anything else gets an error frame back.
438
+ * @throws {TypedError} When no connection is registered for the socket, or rethrown from an
439
+ * `onMessage` hook.
422
440
  */
423
441
  async handleWebSocketConnectionMessage(
424
442
  ws: ServerWebSocket,
@@ -464,13 +482,58 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
464
482
  }
465
483
  }
466
484
 
485
+ // Parse up front (synchronously, in arrival order) so we know whether this frame
486
+ // joins the connection's channel-op queue. Parse errors are reported after the hooks run.
487
+ let parsedMessage: any;
488
+ let parseError: unknown;
489
+ try {
490
+ parsedMessage = JSON.parse(message.toString());
491
+ } catch (e) {
492
+ parseError = e;
493
+ }
494
+ const messageType = parsedMessage?.["messageType"];
495
+ const isChannelOp =
496
+ messageType === "subscribe" || messageType === "unsubscribe";
497
+
498
+ const previous = this.wsChannelOpQueue.get(connection.id);
499
+ const handled = this.processWebSocketMessage(
500
+ connection,
501
+ ws,
502
+ message,
503
+ parsedMessage,
504
+ parseError,
505
+ previous,
506
+ );
507
+ if (isChannelOp) {
508
+ this.wsChannelOpQueue.set(
509
+ connection.id,
510
+ handled.catch(() => {}),
511
+ );
512
+ }
513
+ await handled;
514
+ }
515
+
516
+ /**
517
+ * Runs one inbound WebSocket frame after the connection's earlier channel operations settle:
518
+ * the `onMessage` hooks, then the action / subscribe / unsubscribe handler.
519
+ */
520
+ private async processWebSocketMessage(
521
+ connection: Connection,
522
+ ws: ServerWebSocket,
523
+ message: string | Buffer,
524
+ parsedMessage: any,
525
+ parseError: unknown,
526
+ previous: Promise<void> | undefined,
527
+ ) {
528
+ if (previous) await previous;
529
+
467
530
  for (const hook of api.hooks.ws.onMessageHooks) {
468
531
  await hook(connection, message);
469
532
  }
470
533
 
471
534
  let messageId: unknown;
472
535
  try {
473
- const parsedMessage = JSON.parse(message.toString());
536
+ if (parseError) throw parseError;
474
537
  messageId = parsedMessage["messageId"];
475
538
  if (parsedMessage["messageType"] === "action") {
476
539
  await handleWebsocketAction(connection, ws, parsedMessage);
@@ -510,6 +573,11 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
510
573
  );
511
574
  if (!connection) return;
512
575
 
576
+ // Let in-flight subscribe/unsubscribe frames finish so presence cleanup sees the final set
577
+ const pendingChannelOps = this.wsChannelOpQueue.get(connection.id);
578
+ if (pendingChannelOps) await pendingChannelOps;
579
+ this.wsChannelOpQueue.delete(connection.id);
580
+
513
581
  for (const hook of api.hooks.ws.onDisconnectHooks) {
514
582
  await hook(connection);
515
583
  }
package/util/mcpServer.ts CHANGED
@@ -4,9 +4,11 @@ import {
4
4
  } from "@modelcontextprotocol/sdk/server/mcp.js";
5
5
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
6
6
  import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
7
+ import { UriTemplate } from "@modelcontextprotocol/sdk/shared/uriTemplate.js";
7
8
  import {
8
9
  DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
9
10
  JSONRPCMessageSchema,
11
+ ListResourceTemplatesRequestSchema,
10
12
  type ServerNotification,
11
13
  type ServerRequest,
12
14
  SUPPORTED_PROTOCOL_VERSIONS,
@@ -56,6 +58,132 @@ export type McpAuthInfo = {
56
58
  extra?: Record<string, unknown>;
57
59
  };
58
60
 
61
+ /**
62
+ * Sentinel OAuth client id recorded for anonymous MCP sessions (served when
63
+ * `config.server.mcp.authMode` is `"optional"` and the request has no bearer
64
+ * token). It can never collide with a real client id: registered clients get a
65
+ * UUID and CIMD clients an `https://` URL.
66
+ */
67
+ export const ANONYMOUS_MCP_CLIENT_ID = "keryx:anonymous";
68
+
69
+ /**
70
+ * Build the auth context for an anonymous MCP request. It is passed to the
71
+ * transport like a verified token's, so the client IP still reaches
72
+ * `Connection.identifier` (and IP-keyed rate limiting inside actions), but it
73
+ * carries no token and is flagged `extra.anonymous` so access checks can deny
74
+ * non-public actions.
75
+ *
76
+ * @param ip - The remote IP of the request.
77
+ */
78
+ export function buildAnonymousMcpAuthInfo(ip: string): McpAuthInfo {
79
+ return {
80
+ token: "",
81
+ clientId: ANONYMOUS_MCP_CLIENT_ID,
82
+ scopes: [],
83
+ extra: { ip, anonymous: true },
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Whether an MCP request's auth context is anonymous. A missing auth context
89
+ * counts as anonymous, so every access check fails closed.
90
+ */
91
+ export function isAnonymousMcpAuth(authInfo: McpAuthInfo | undefined): boolean {
92
+ return !authInfo || authInfo.extra?.anonymous === true;
93
+ }
94
+
95
+ /** Whether an action opted in to anonymous MCP access via `mcp.public`. */
96
+ export function isActionPublicForMcp(action: Action): boolean {
97
+ return action.mcp?.public === true;
98
+ }
99
+
100
+ /**
101
+ * Whether an action is registered as an MCP tool. Tools are opt-in: an action
102
+ * must set `mcp.tool = true`, or declare an MCP App (`mcp.ui`) without opting
103
+ * out.
104
+ */
105
+ export function isMcpTool(action: Action): boolean {
106
+ return (
107
+ action.mcp?.tool === true ||
108
+ (action.mcp?.ui != null && action.mcp?.tool !== false)
109
+ );
110
+ }
111
+
112
+ /**
113
+ * Find the action an MCP resource URI is served by: a static `mcp.resource.uri`,
114
+ * a match against an `mcp.resource.uriTemplate`, or an MCP App's `ui://` URI.
115
+ *
116
+ * @param uri - The URI from a `resources/read` request.
117
+ * @returns The matching action, or `undefined` if no action serves the URI.
118
+ */
119
+ export function findActionForResourceUri(uri: string): Action | undefined {
120
+ for (const action of api.actions.actions) {
121
+ const resource = action.mcp?.resource;
122
+ if (resource?.uri && resource.uri === uri) return action;
123
+ if (resource?.uriTemplate && !resource.uri) {
124
+ try {
125
+ if (new UriTemplate(resource.uriTemplate).match(uri)) return action;
126
+ } catch {
127
+ // malformed template or URI — not a match
128
+ }
129
+ }
130
+ if (action.mcp?.ui && uiResourceUri(action) === uri) return action;
131
+ }
132
+ return undefined;
133
+ }
134
+
135
+ /**
136
+ * Find the action a single JSON-RPC message would invoke: `tools/call` and
137
+ * `prompts/get` by name, `resources/read` by URI. Used to challenge anonymous
138
+ * requests for protected actions with a 401 before they are dispatched.
139
+ *
140
+ * @param message - One JSON-RPC message from a POST body.
141
+ * @returns The targeted action, or `undefined` for any other message or an
142
+ * unknown target (the SDK then answers with its own not-found error).
143
+ */
144
+ export function findMcpTargetAction(message: unknown): Action | undefined {
145
+ if (!message || typeof message !== "object") return undefined;
146
+ const { method, params } = message as {
147
+ method?: unknown;
148
+ params?: { name?: unknown; uri?: unknown };
149
+ };
150
+ if (method === "tools/call" && typeof params?.name === "string") {
151
+ return api.actions.actions.find(
152
+ (a: Action) => isMcpTool(a) && formatToolName(a.name) === params.name,
153
+ );
154
+ }
155
+ if (method === "prompts/get" && typeof params?.name === "string") {
156
+ return api.actions.actions.find(
157
+ (a: Action) =>
158
+ a.mcp?.prompt != null && formatToolName(a.name) === params.name,
159
+ );
160
+ }
161
+ if (method === "resources/read" && typeof params?.uri === "string") {
162
+ return findActionForResourceUri(params.uri);
163
+ }
164
+ return undefined;
165
+ }
166
+
167
+ /**
168
+ * Whether an MCP request may run an action: authenticated requests always may
169
+ * (the action's own middleware still applies), anonymous requests only when the
170
+ * action is marked `mcp.public`.
171
+ */
172
+ export function isMcpAccessAllowed(
173
+ action: Action,
174
+ authInfo: McpAuthInfo | undefined,
175
+ ): boolean {
176
+ return !isAnonymousMcpAuth(authInfo) || isActionPublicForMcp(action);
177
+ }
178
+
179
+ /** The error raised when an anonymous MCP request targets a non-public action. */
180
+ function mcpAuthenticationRequiredError(action: Action): TypedError {
181
+ return new TypedError({
182
+ message: `Authentication required: '${formatToolName(action.name)}' is not available to anonymous MCP clients. Reconnect with an OAuth access token.`,
183
+ type: ErrorType.CONNECTION_SESSION_NOT_FOUND,
184
+ });
185
+ }
186
+
59
187
  /**
60
188
  * Create an authenticated MCP Connection from the auth info attached to an MCP request.
61
189
  * Shared by tool, resource, and prompt handlers to avoid duplicating connection setup.
@@ -75,7 +203,9 @@ export async function createMcpConnection(
75
203
  clientIp,
76
204
  randomUUID(),
77
205
  undefined,
78
- authInfo?.token,
206
+ // Anonymous requests carry an empty token; leave the session id unset so
207
+ // the connection gets its own throwaway session rather than a shared "".
208
+ isAnonymousMcpAuth(authInfo) ? undefined : authInfo?.token,
79
209
  );
80
210
 
81
211
  if (authInfo?.extra?.userId) {
@@ -298,6 +428,20 @@ export interface McpSessionRecord {
298
428
  protocolVersion?: string;
299
429
  /** Creation timestamp (ms since epoch). */
300
430
  createdAt: number;
431
+ /**
432
+ * `true` for an anonymous session (opened without a token in `optional` auth
433
+ * mode). Such a session expires after `anonymousSessionTtl`, and may be
434
+ * upgraded once — by the first request carrying a valid token — to a session
435
+ * owned by that token's client.
436
+ */
437
+ anonymous?: boolean;
438
+ }
439
+
440
+ /** The idle TTL (seconds) for a session registry record. */
441
+ function mcpSessionTtl(anonymous: boolean | undefined): number {
442
+ return anonymous
443
+ ? config.server.mcp.anonymousSessionTtl
444
+ : config.server.mcp.sessionTtl;
301
445
  }
302
446
 
303
447
  /** Redis key for a session registry record. */
@@ -320,7 +464,7 @@ export async function writeMcpSessionRecord(
320
464
  mcpSessionKey(sessionId),
321
465
  JSON.stringify(record),
322
466
  "EX",
323
- config.server.mcp.sessionTtl,
467
+ mcpSessionTtl(record.anonymous),
324
468
  );
325
469
  }
326
470
 
@@ -342,14 +486,54 @@ export async function readMcpSessionRecord(
342
486
  * TTL behaves as an idle timeout across the cluster.
343
487
  *
344
488
  * @param sessionId - The transport session id (`Mcp-Session-Id`).
489
+ * @param anonymous - Whether the session is anonymous (see
490
+ * {@link McpSessionRecord.anonymous}), which selects the shorter TTL.
345
491
  */
346
- export async function refreshMcpSessionTtl(sessionId: string): Promise<void> {
492
+ export async function refreshMcpSessionTtl(
493
+ sessionId: string,
494
+ anonymous?: boolean,
495
+ ): Promise<void> {
347
496
  await api.redis.redis.expire(
348
497
  mcpSessionKey(sessionId),
349
- config.server.mcp.sessionTtl,
498
+ mcpSessionTtl(anonymous),
350
499
  );
351
500
  }
352
501
 
502
+ /**
503
+ * Atomically upgrade an anonymous session to one owned by an authenticated
504
+ * OAuth client. A compare-and-set on the stored record (Lua, so it is atomic
505
+ * across the cluster) guarantees only one upgrade can win: if two clients race
506
+ * to claim the same anonymous session, the loser sees the winner's record and
507
+ * gets the normal ownership check (403).
508
+ *
509
+ * @param sessionId - The transport session id (`Mcp-Session-Id`).
510
+ * @param anonymousRecord - The anonymous record as just read from Redis.
511
+ * @param clientId - The OAuth client id of the token presented on this request.
512
+ * @returns The upgraded record, or the record as it now stands if another
513
+ * request changed it first (`null` if it was deleted meanwhile).
514
+ */
515
+ export async function upgradeAnonymousMcpSession(
516
+ sessionId: string,
517
+ anonymousRecord: McpSessionRecord,
518
+ clientId: string,
519
+ ): Promise<McpSessionRecord | null> {
520
+ const { anonymous: _anonymous, ...rest } = anonymousRecord;
521
+ const upgraded: McpSessionRecord = { ...rest, clientId };
522
+ const swapped = await api.redis.redis.eval(
523
+ `if redis.call("GET", KEYS[1]) == ARGV[1] then
524
+ redis.call("SET", KEYS[1], ARGV[2], "EX", ARGV[3])
525
+ return 1
526
+ end
527
+ return 0`,
528
+ 1,
529
+ mcpSessionKey(sessionId),
530
+ JSON.stringify(anonymousRecord),
531
+ JSON.stringify(upgraded),
532
+ mcpSessionTtl(false),
533
+ );
534
+ return swapped === 1 ? upgraded : readMcpSessionRecord(sessionId);
535
+ }
536
+
353
537
  /**
354
538
  * Delete a session registry record.
355
539
  *
@@ -473,6 +657,8 @@ const adoptionsInFlight = new Map<
473
657
  * @param protocolVersion - The negotiated protocol version from the registry record, if any.
474
658
  * @param auth - The adopting request's user id / ip, captured so channel-broadcast
475
659
  * authorization ({@link isMcpSessionAuthorizedForChannel}) works for this session too.
660
+ * @param anonymous - Whether the session is anonymous (see
661
+ * {@link McpSessionRecord.anonymous}); if so, non-public entries are hidden.
476
662
  * @returns The connected, initialized transport (also registered in `api.mcp.transports`).
477
663
  */
478
664
  export async function adoptMcpSession(
@@ -480,12 +666,13 @@ export async function adoptMcpSession(
480
666
  clientId: string,
481
667
  protocolVersion: string | undefined,
482
668
  auth?: Pick<McpSessionAuth, "userId" | "ip">,
669
+ anonymous = false,
483
670
  ): Promise<WebStandardStreamableHTTPServerTransport> {
484
671
  const inFlight = adoptionsInFlight.get(sessionId);
485
672
  if (inFlight) return inFlight;
486
673
 
487
674
  const promise = (async () => {
488
- const mcpServer = createMcpServer();
675
+ const mcpServer = createMcpServer({ anonymous });
489
676
  api.mcp.mcpServers.push(mcpServer);
490
677
  api.mcp.mcpServerAuth.set(mcpServer, {
491
678
  clientId,
@@ -498,7 +685,12 @@ export async function adoptMcpSession(
498
685
  enableJsonResponse: true,
499
686
  // Local registration only — no hooks, no registry write (see doc above).
500
687
  onsessioninitialized: (sid) => {
501
- api.mcp.transports.set(sid, { transport, clientId });
688
+ api.mcp.transports.set(sid, {
689
+ transport,
690
+ clientId,
691
+ mcpServer,
692
+ anonymous,
693
+ });
502
694
  },
503
695
  onsessionclosed: (sid) => terminateMcpSession(sid, mcpServer),
504
696
  });
@@ -525,12 +717,62 @@ export async function adoptMcpSession(
525
717
  }
526
718
  }
527
719
 
720
+ /**
721
+ * Tools, resources, and prompts registered on an anonymous session's
722
+ * `McpServer` but disabled (hidden from list results) because their action is
723
+ * not `mcp.public`. {@link unlockMcpServer} enables them on session upgrade.
724
+ */
725
+ const gatedMcpItems = new WeakMap<McpServer, Array<{ enable(): void }>>();
726
+
727
+ /**
728
+ * Hide a just-registered tool/resource/prompt from an anonymous session when its
729
+ * action is not `mcp.public`. The item stays registered (the SDK cannot add
730
+ * capabilities after `connect()`), so the session can be unlocked later.
731
+ */
732
+ function gateForAnonymous(
733
+ mcpServer: McpServer,
734
+ action: Action,
735
+ item: { enable(): void; disable(): void },
736
+ anonymous: boolean,
737
+ ): void {
738
+ if (!anonymous || isActionPublicForMcp(action)) return;
739
+ item.disable();
740
+ const gated = gatedMcpItems.get(mcpServer) ?? [];
741
+ gated.push(item);
742
+ gatedMcpItems.set(mcpServer, gated);
743
+ }
744
+
745
+ /**
746
+ * Reveal every tool, resource, and prompt hidden from an anonymous session,
747
+ * after the session upgrades to an authenticated one. The SDK sends the
748
+ * client `notifications/tools/list_changed` (and the resource and prompt
749
+ * equivalents) as each item is enabled. A no-op for servers created for authenticated sessions or already
750
+ * unlocked.
751
+ *
752
+ * @param mcpServer - The session's `McpServer`, created via
753
+ * `createMcpServer({ anonymous: true })`.
754
+ */
755
+ export function unlockMcpServer(mcpServer: McpServer): void {
756
+ const gated = gatedMcpItems.get(mcpServer);
757
+ if (!gated) return;
758
+ gatedMcpItems.delete(mcpServer);
759
+ for (const item of gated) item.enable();
760
+ }
761
+
528
762
  /**
529
763
  * Create a new McpServer instance with all actions registered as tools, resources, and prompts.
530
764
  * Each MCP session gets its own McpServer (the SDK requires 1:1 mapping).
531
765
  * Actions with `mcp.tool === false` are excluded from tool registration.
766
+ *
767
+ * @param options.anonymous - Build the server for an anonymous session
768
+ * (`MCP_AUTH_MODE=optional`, no token): everything whose action is not
769
+ * `mcp.public` is registered but disabled, so list results show only public
770
+ * entries until {@link unlockMcpServer} is called on upgrade.
532
771
  */
533
- export function createMcpServer(): McpServer {
772
+ export function createMcpServer(
773
+ options: { anonymous?: boolean } = {},
774
+ ): McpServer {
775
+ const anonymous = options.anonymous === true;
534
776
  // Advertise the MCP Apps UI extension so hosts negotiate UI support during
535
777
  // `initialize` (spec 2026-01-26, SEP-1724). Only declared when at least one
536
778
  // action ships a UI, keeping the capability surface minimal.
@@ -551,10 +793,10 @@ export function createMcpServer(): McpServer {
551
793
  },
552
794
  );
553
795
 
554
- registerTools(mcpServer);
555
- registerResources(mcpServer);
556
- registerUiResources(mcpServer);
557
- registerPrompts(mcpServer);
796
+ registerTools(mcpServer, anonymous);
797
+ registerResources(mcpServer, anonymous);
798
+ registerUiResources(mcpServer, anonymous);
799
+ registerPrompts(mcpServer, anonymous);
558
800
 
559
801
  return mcpServer;
560
802
  }
@@ -588,16 +830,13 @@ function buildUiMeta(ui: McpUiConfig): Record<string, unknown> {
588
830
  return meta;
589
831
  }
590
832
 
591
- function registerTools(mcpServer: McpServer) {
833
+ function registerTools(mcpServer: McpServer, anonymous: boolean) {
592
834
  const registered = new Set<string>();
593
835
  for (const action of api.actions.actions) {
594
836
  // Tools are opt-in: register only actions that explicitly set `mcp.tool =
595
837
  // true`, or that declare an MCP App (`mcp.ui`) without opting out. Every
596
838
  // other action — including those with no `mcp` config — is never exposed.
597
- const isTool =
598
- action.mcp?.tool === true ||
599
- (action.mcp?.ui != null && action.mcp?.tool !== false);
600
- if (!isTool) continue;
839
+ if (!isMcpTool(action)) continue;
601
840
 
602
841
  const toolName = formatToolName(action.name);
603
842
  if (registered.has(toolName)) continue;
@@ -622,13 +861,31 @@ function registerTools(mcpServer: McpServer) {
622
861
  toolConfig._meta = { ui: { resourceUri: uiResourceUri(action) } };
623
862
  }
624
863
 
625
- mcpServer.registerTool(
864
+ const tool = mcpServer.registerTool(
626
865
  toolName,
627
866
  toolConfig,
628
867
  async (
629
868
  args: Record<string, unknown>,
630
869
  extra: RequestHandlerExtra<ServerRequest, ServerNotification>,
631
870
  ) => {
871
+ // Anonymous sessions may only call public tools. The HTTP layer already
872
+ // answers such a call with a 401 challenge; this is the backstop.
873
+ if (!isMcpAccessAllowed(action, extra.authInfo)) {
874
+ const denied = mcpAuthenticationRequiredError(action);
875
+ return {
876
+ content: [
877
+ {
878
+ type: "text" as const,
879
+ text: JSON.stringify({
880
+ error: denied.message,
881
+ type: denied.type,
882
+ }),
883
+ },
884
+ ],
885
+ isError: true,
886
+ };
887
+ }
888
+
632
889
  const mcpSessionId = extra.sessionId || "";
633
890
  const connection = await createMcpConnection(extra, mcpServer);
634
891
 
@@ -733,10 +990,12 @@ function registerTools(mcpServer: McpServer) {
733
990
  }
734
991
  },
735
992
  );
993
+ gateForAnonymous(mcpServer, action, tool, anonymous);
736
994
  }
737
995
  }
738
996
 
739
- function registerResources(mcpServer: McpServer) {
997
+ function registerResources(mcpServer: McpServer, anonymous: boolean) {
998
+ let registeredTemplate = false;
740
999
  for (const action of api.actions.actions) {
741
1000
  if (!action.mcp?.resource) continue;
742
1001
  const { uri, uriTemplate, mimeType } = action.mcp.resource;
@@ -746,6 +1005,9 @@ function registerResources(mcpServer: McpServer) {
746
1005
  variables: Record<string, string | string[]>,
747
1006
  extra: any,
748
1007
  ) => {
1008
+ if (!isMcpAccessAllowed(action, extra.authInfo)) {
1009
+ throw mcpAuthenticationRequiredError(action);
1010
+ }
749
1011
  const mcpSessionId = extra.sessionId || "";
750
1012
  const connection = await createMcpConnection(extra, mcpServer);
751
1013
 
@@ -795,21 +1057,59 @@ function registerResources(mcpServer: McpServer) {
795
1057
  };
796
1058
 
797
1059
  if (uriTemplate) {
798
- mcpServer.registerResource(
1060
+ const resource = mcpServer.registerResource(
799
1061
  formatToolName(action.name),
800
1062
  new ResourceTemplate(uriTemplate, { list: undefined }),
801
1063
  { description: action.description, mimeType },
802
1064
  readCb,
803
1065
  );
1066
+ gateForAnonymous(mcpServer, action, resource, anonymous);
1067
+ registeredTemplate = true;
804
1068
  } else if (uri) {
805
- mcpServer.registerResource(
1069
+ const resource = mcpServer.registerResource(
806
1070
  formatToolName(action.name),
807
1071
  uri,
808
1072
  { description: action.description, mimeType },
809
1073
  (mcpUri: URL, extra: any) => readCb(mcpUri, {}, extra),
810
1074
  );
1075
+ gateForAnonymous(mcpServer, action, resource, anonymous);
811
1076
  }
812
1077
  }
1078
+
1079
+ if (registeredTemplate) listOnlyEnabledResourceTemplates(mcpServer);
1080
+ }
1081
+
1082
+ /**
1083
+ * Replace the SDK's `resources/templates/list` handler with one that skips
1084
+ * disabled templates. The SDK filters disabled entries out of `tools/list`,
1085
+ * `prompts/list`, and `resources/list`, but not out of the template list, so
1086
+ * without this an anonymous session would still see protected templates.
1087
+ */
1088
+ function listOnlyEnabledResourceTemplates(mcpServer: McpServer): void {
1089
+ mcpServer.server.setRequestHandler(
1090
+ ListResourceTemplatesRequestSchema,
1091
+ async () => {
1092
+ const templates: Record<
1093
+ string,
1094
+ {
1095
+ enabled: boolean;
1096
+ resourceTemplate: ResourceTemplate;
1097
+ metadata?: Record<string, unknown>;
1098
+ }
1099
+ > =
1100
+ // @ts-expect-error -- the SDK keeps registered templates in a private field and exposes no public accessor
1101
+ mcpServer._registeredResourceTemplates;
1102
+ return {
1103
+ resourceTemplates: Object.entries(templates)
1104
+ .filter(([, template]) => template.enabled)
1105
+ .map(([name, template]) => ({
1106
+ name,
1107
+ uriTemplate: template.resourceTemplate.uriTemplate.toString(),
1108
+ ...template.metadata,
1109
+ })),
1110
+ };
1111
+ },
1112
+ );
813
1113
  }
814
1114
 
815
1115
  /**
@@ -818,7 +1118,7 @@ function registerResources(mcpServer: McpServer) {
818
1118
  * and any `_meta.ui` (CSP, permissions, etc.). The matching tool is linked to it
819
1119
  * via `_meta.ui.resourceUri` in `registerTools()`.
820
1120
  */
821
- function registerUiResources(mcpServer: McpServer) {
1121
+ function registerUiResources(mcpServer: McpServer, anonymous: boolean) {
822
1122
  const registered = new Set<string>();
823
1123
  for (const action of api.actions.actions) {
824
1124
  const ui = action.mcp?.ui;
@@ -842,39 +1142,53 @@ function registerUiResources(mcpServer: McpServer) {
842
1142
  const metadata: Record<string, unknown> = { mimeType: MCP_APP_MIME_TYPE };
843
1143
  if (hasMeta) metadata._meta = { ui: uiMeta };
844
1144
 
845
- mcpServer.registerResource(
1145
+ const uiResource = mcpServer.registerResource(
846
1146
  `${formatToolName(action.name)}-ui`,
847
1147
  resourceUri,
848
1148
  metadata,
849
- (mcpUri: URL) => ({
850
- contents: [
851
- {
852
- uri: mcpUri.toString(),
853
- mimeType: MCP_APP_MIME_TYPE,
854
- text: html,
855
- ...(hasMeta ? { _meta: { ui: uiMeta } } : {}),
856
- },
857
- ],
858
- }),
1149
+ (mcpUri: URL, extra: { authInfo?: McpAuthInfo }) => {
1150
+ if (!isMcpAccessAllowed(action, extra.authInfo)) {
1151
+ throw mcpAuthenticationRequiredError(action);
1152
+ }
1153
+ return {
1154
+ contents: [
1155
+ {
1156
+ uri: mcpUri.toString(),
1157
+ mimeType: MCP_APP_MIME_TYPE,
1158
+ text: html,
1159
+ ...(hasMeta ? { _meta: { ui: uiMeta } } : {}),
1160
+ },
1161
+ ],
1162
+ };
1163
+ },
859
1164
  );
1165
+ gateForAnonymous(mcpServer, action, uiResource, anonymous);
860
1166
  }
861
1167
  }
862
1168
 
863
- function registerPrompts(mcpServer: McpServer) {
1169
+ function registerPrompts(mcpServer: McpServer, anonymous: boolean) {
864
1170
  for (const action of api.actions.actions) {
865
1171
  if (!action.mcp?.prompt) continue;
866
1172
  const { title } = action.mcp.prompt;
867
1173
 
868
- mcpServer.registerPrompt(
1174
+ const argsSchema = action.inputs
1175
+ ? sanitizeSchemaForMcp(action.inputs)?.shape
1176
+ : undefined;
1177
+
1178
+ const prompt = mcpServer.registerPrompt(
869
1179
  formatToolName(action.name),
870
1180
  {
871
1181
  title: title ?? action.name,
872
1182
  description: action.description,
873
- argsSchema: action.inputs
874
- ? sanitizeSchemaForMcp(action.inputs)?.shape
875
- : undefined,
1183
+ argsSchema,
876
1184
  },
877
- async (args: any, extra: any) => {
1185
+ async (...cbArgs: any[]) => {
1186
+ // The SDK calls `cb(args, extra)` when the prompt declares an
1187
+ // argsSchema, but `cb(extra)` when it doesn't.
1188
+ const [args, extra] = argsSchema ? cbArgs : [{}, cbArgs[0]];
1189
+ if (!isMcpAccessAllowed(action, extra.authInfo)) {
1190
+ throw mcpAuthenticationRequiredError(action);
1191
+ }
878
1192
  const mcpSessionId = extra.sessionId || "";
879
1193
  const connection = await createMcpConnection(extra, mcpServer);
880
1194
 
@@ -904,6 +1218,7 @@ function registerPrompts(mcpServer: McpServer) {
904
1218
  }
905
1219
  },
906
1220
  );
1221
+ gateForAnonymous(mcpServer, action, prompt, anonymous);
907
1222
  }
908
1223
  }
909
1224