keryx 0.46.0 → 0.48.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/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
 
package/util/scaffold.ts CHANGED
@@ -7,8 +7,17 @@ import pkg from "../package.json";
7
7
  import { loadScaffoldTemplate as loadTemplate } from "./componentRegistry";
8
8
 
9
9
  export interface ScaffoldOptions {
10
+ /**
11
+ * Generate Postgres/Drizzle files and point `DATABASE_URL` at a local database. When
12
+ * false, `DATABASE_URL` is left empty so the app runs without a database.
13
+ */
10
14
  includeDb: boolean;
11
15
  includeExample: boolean;
16
+ /**
17
+ * Point `REDIS_URL` at a local Redis server. When false, `REDIS_URL` is `memory://`,
18
+ * which runs an in-process Redis (single process, not persisted). Defaults to `true`.
19
+ */
20
+ includeRedis?: boolean;
12
21
  /**
13
22
  * When true, scaffold into an existing directory instead of refusing.
14
23
  * Files that already exist on disk are left untouched (merge-skip); only
@@ -46,10 +55,17 @@ export async function interactiveScaffold(
46
55
  projectName = await prompt("Project name:", "my-keryx-app");
47
56
  }
48
57
 
49
- const includeDb = await promptYesNo("Include database setup?", true);
58
+ const includeDb = await promptYesNo(
59
+ "Include database setup? (PostgreSQL — if no, the app runs without a database)",
60
+ true,
61
+ );
62
+ const includeRedis = await promptYesNo(
63
+ "Use a Redis server? (if no, an in-memory Redis is used: single process, not persisted)",
64
+ true,
65
+ );
50
66
  const includeExample = await promptYesNo("Include example action?", true);
51
67
 
52
- return { projectName, options: { includeDb, includeExample } };
68
+ return { projectName, options: { includeDb, includeRedis, includeExample } };
53
69
  }
54
70
 
55
71
  /**
@@ -280,7 +296,12 @@ export async function scaffoldProject(
280
296
 
281
297
  fs.mkdirSync(targetDir, { recursive: true });
282
298
 
283
- const view = { projectName, keryxVersion };
299
+ const view = {
300
+ projectName,
301
+ keryxVersion,
302
+ includeDb: options.includeDb,
303
+ includeRedis: options.includeRedis !== false,
304
+ };
284
305
 
285
306
  const write = async (filePath: string, content: string) => {
286
307
  const fullPath = path.join(targetDir, filePath);
@@ -28,6 +28,22 @@ export type Transaction = NodePgDatabase<Record<string, never>>;
28
28
  */
29
29
  export type DbOrTransaction = NodePgDatabase<Record<string, never>>;
30
30
 
31
+ /**
32
+ * Throw a clear error when code that needs Postgres runs while the database is
33
+ * disabled (`DATABASE_URL` empty or `"none"`). Without this, callers would fail with
34
+ * an opaque `cannot read properties of undefined` on `api.db.pool` / `api.db.db`.
35
+ *
36
+ * @param feature - What needed the database, included in the error message.
37
+ * @throws {TypedError} With `ErrorType.SERVER_INITIALIZATION` when `api.db.enabled` is `false`.
38
+ */
39
+ export function assertDatabaseEnabled(feature: string) {
40
+ if (api.db?.enabled) return;
41
+ throw new TypedError({
42
+ message: `${feature} requires a database, but the database is disabled (DATABASE_URL is empty or "none")`,
43
+ type: ErrorType.SERVER_INITIALIZATION,
44
+ });
45
+ }
46
+
31
47
  /**
32
48
  * Run a callback inside a database transaction with automatic commit/rollback.
33
49
  *
@@ -44,7 +60,8 @@ export type DbOrTransaction = NodePgDatabase<Record<string, never>>;
44
60
  * All queries executed through `tx` participate in the same transaction.
45
61
  * @returns The value returned by `fn`.
46
62
  * @throws {TypedError} Re-throws `TypedError` directly. Wraps other errors in
47
- * a `TypedError` with `ErrorType.CONNECTION_ACTION_RUN`.
63
+ * a `TypedError` with `ErrorType.CONNECTION_ACTION_RUN`. Throws
64
+ * `ErrorType.SERVER_INITIALIZATION` when the database is disabled.
48
65
  *
49
66
  * @example
50
67
  * ```ts
@@ -58,6 +75,7 @@ export type DbOrTransaction = NodePgDatabase<Record<string, never>>;
58
75
  export async function withTransaction<T>(
59
76
  fn: (tx: Transaction) => Promise<T>,
60
77
  ): Promise<T> {
78
+ assertDatabaseEnabled("withTransaction");
61
79
  const client = await api.db.pool.connect();
62
80
  try {
63
81
  await client.query("BEGIN");
package/util/zodMixins.ts CHANGED
@@ -2,6 +2,7 @@ import { type AnyColumn, eq, type Table } from "drizzle-orm";
2
2
  import { z } from "zod/v4";
3
3
  import { api } from "../api";
4
4
  import { ErrorType, TypedError } from "../classes/TypedError";
5
+ import { assertDatabaseEnabled } from "./transaction";
5
6
 
6
7
  // Zod v4: Extend GlobalMeta to support custom 'isSecret' metadata
7
8
  // This allows using .meta({ isSecret: true }) on any zod schema
@@ -100,6 +101,7 @@ export function zIdOrModel<TModel>(
100
101
  if (isModel(val)) {
101
102
  return val;
102
103
  }
104
+ assertDatabaseEnabled(`Loading ${entityName} by id`);
103
105
  const [record] = await api.db.db
104
106
  .select()
105
107
  .from(table)