keryx 0.45.0 → 0.47.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/README.md +1 -1
- package/actions/status.ts +9 -7
- package/classes/Connection.ts +107 -4
- package/classes/McpUrlElicitationRequiredError.ts +32 -0
- package/classes/TypedError.ts +2 -0
- package/config/database.ts +2 -1
- package/index.ts +7 -1
- package/initializers/db.ts +28 -0
- package/initializers/redis.ts +23 -1
- package/initializers/resque.ts +14 -3
- package/middleware/transaction.ts +3 -1
- package/package.json +7 -5
- package/templates/scaffold/env.example.mustache +16 -1
- package/testing/index.ts +2 -2
- package/util/cli.ts +9 -1
- package/util/connectionString.ts +26 -1
- package/util/mcpElicitation.ts +191 -0
- package/util/mcpServer.ts +30 -7
- package/util/scaffold.ts +24 -3
- package/util/transaction.ts +19 -1
- package/util/zodMixins.ts +2 -0
package/README.md
CHANGED
|
@@ -123,7 +123,7 @@ bun install
|
|
|
123
123
|
bun dev
|
|
124
124
|
```
|
|
125
125
|
|
|
126
|
-
Requires Bun, PostgreSQL, and Redis. See the [Getting Started guide](https://keryxjs.com/guide/) for full setup instructions.
|
|
126
|
+
Requires Bun, PostgreSQL, and Redis. See the [Getting Started guide](https://keryxjs.com/guide/) for full setup instructions (including running without Postgres or Redis for quick prototypes).
|
|
127
127
|
|
|
128
128
|
### Developing the framework itself
|
|
129
129
|
|
package/actions/status.ts
CHANGED
|
@@ -7,7 +7,7 @@ import packageJSON from "../package.json";
|
|
|
7
7
|
export class Status implements Action {
|
|
8
8
|
name = "status";
|
|
9
9
|
description =
|
|
10
|
-
"Returns server health and runtime information including the server name, process ID, package version, uptime in milliseconds, memory consumption in MB, and dependency health checks for the database and Redis. Does not require authentication.";
|
|
10
|
+
"Returns server health and runtime information including the server name, process ID, package version, uptime in milliseconds, memory consumption in MB, and dependency health checks for the database and Redis. A check is `null` when that dependency is disabled (e.g. no `DATABASE_URL`), and disabled checks do not affect `healthy`. Does not require authentication.";
|
|
11
11
|
inputs = z.object({});
|
|
12
12
|
web = { route: "/status", method: HTTP_METHOD.GET };
|
|
13
13
|
tracing = false;
|
|
@@ -16,13 +16,15 @@ export class Status implements Action {
|
|
|
16
16
|
const consumedMemoryMB =
|
|
17
17
|
Math.round((process.memoryUsage().heapUsed / 1024 / 1024) * 100) / 100;
|
|
18
18
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
// `null` = the database is disabled, so it is not part of the health verdict.
|
|
20
|
+
let databaseHealthy: boolean | null = null;
|
|
21
|
+
if (api.db?.enabled) {
|
|
22
|
+
databaseHealthy = false;
|
|
23
|
+
try {
|
|
22
24
|
await api.db.db.execute(sql`SELECT NOW()`);
|
|
23
25
|
databaseHealthy = true;
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
+
} catch {}
|
|
27
|
+
}
|
|
26
28
|
|
|
27
29
|
let redisHealthy = false;
|
|
28
30
|
try {
|
|
@@ -32,7 +34,7 @@ export class Status implements Action {
|
|
|
32
34
|
}
|
|
33
35
|
} catch {}
|
|
34
36
|
|
|
35
|
-
const healthy = databaseHealthy && redisHealthy;
|
|
37
|
+
const healthy = databaseHealthy !== false && redisHealthy;
|
|
36
38
|
|
|
37
39
|
return {
|
|
38
40
|
name: api.process.name,
|
package/classes/Connection.ts
CHANGED
|
@@ -1,10 +1,19 @@
|
|
|
1
1
|
import { randomUUID } from "crypto";
|
|
2
|
+
import type { z } from "zod";
|
|
2
3
|
import { api, logger } from "../api";
|
|
3
4
|
import { config } from "../config";
|
|
4
5
|
import type { PubSubMessage } from "../initializers/pubsub";
|
|
5
6
|
import type { SessionData } from "../initializers/session";
|
|
6
7
|
import type { RateLimitInfo } from "../middleware/rateLimit";
|
|
7
8
|
import { ansi } from "../util/ansi";
|
|
9
|
+
import {
|
|
10
|
+
completeMcpElicitation,
|
|
11
|
+
elicitMcpForm,
|
|
12
|
+
elicitMcpUrl,
|
|
13
|
+
type McpElicitationContext,
|
|
14
|
+
type McpFormElicitationResult,
|
|
15
|
+
type McpUrlElicitationResult,
|
|
16
|
+
} from "../util/mcpElicitation";
|
|
8
17
|
import { isSecret } from "../util/zodMixins";
|
|
9
18
|
import type { Action, ActionParams } from "./Action";
|
|
10
19
|
import { LogFormat } from "./Logger";
|
|
@@ -130,6 +139,10 @@ export class Connection<
|
|
|
130
139
|
metadata: Partial<TMeta>;
|
|
131
140
|
/** @internal Tracks nested `act()` depth so metadata is only reset on the outermost call. */
|
|
132
141
|
private _actDepth = 0;
|
|
142
|
+
/** @internal MCP request functions for this transient connection. */
|
|
143
|
+
private mcpElicitationContext?: McpElicitationContext;
|
|
144
|
+
/** Abort signal for the action currently executing on this connection. */
|
|
145
|
+
private actionAbortSignal?: AbortSignal;
|
|
133
146
|
|
|
134
147
|
/**
|
|
135
148
|
* Create a new connection and register it in `api.connections`.
|
|
@@ -295,6 +308,89 @@ export class Connection<
|
|
|
295
308
|
return api.session.regenerate(this);
|
|
296
309
|
}
|
|
297
310
|
|
|
311
|
+
/**
|
|
312
|
+
* Attach the current MCP request context. Framework transport code calls this before
|
|
313
|
+
* invoking an action; application code should use {@link elicitForm} and
|
|
314
|
+
* {@link elicitUrl} instead.
|
|
315
|
+
*
|
|
316
|
+
* @param context - Request-scoped MCP client capabilities and send functions.
|
|
317
|
+
* @internal
|
|
318
|
+
*/
|
|
319
|
+
setMcpElicitationContext(context: McpElicitationContext): void {
|
|
320
|
+
this.mcpElicitationContext = context;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Ask an MCP client to collect non-sensitive structured input from the user.
|
|
325
|
+
* Accepted content is validated against `schema` before it is returned.
|
|
326
|
+
*
|
|
327
|
+
* Form elicitation must never request passwords, API keys, access tokens, payment
|
|
328
|
+
* credentials, or other secrets. Use {@link elicitUrl} for sensitive input.
|
|
329
|
+
*
|
|
330
|
+
* @param options - Human-readable prompt and a flat Zod object schema containing
|
|
331
|
+
* primitive fields supported by MCP.
|
|
332
|
+
* @returns The client's accept, decline, or cancel decision.
|
|
333
|
+
* @throws {TypedError} When called outside MCP, when the client lacks form
|
|
334
|
+
* elicitation support, when the schema is incompatible, or when accepted content
|
|
335
|
+
* fails validation.
|
|
336
|
+
*/
|
|
337
|
+
async elicitForm<TSchema extends z.ZodType>(options: {
|
|
338
|
+
message: string;
|
|
339
|
+
schema: TSchema;
|
|
340
|
+
}): Promise<McpFormElicitationResult<TSchema>> {
|
|
341
|
+
return elicitMcpForm(
|
|
342
|
+
{
|
|
343
|
+
connectionType: this.type,
|
|
344
|
+
context: this.mcpElicitationContext,
|
|
345
|
+
actionAbortSignal: this.actionAbortSignal,
|
|
346
|
+
},
|
|
347
|
+
options,
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Ask an MCP client to obtain consent to open an out-of-band URL.
|
|
353
|
+
*
|
|
354
|
+
* An `accept` result only means that the user consented to navigate. The application
|
|
355
|
+
* must detect completion through its own callback, webhook, database, or Redis state,
|
|
356
|
+
* then call {@link completeElicitation}.
|
|
357
|
+
*
|
|
358
|
+
* @param options - Message, absolute URL, and optional stable elicitation id.
|
|
359
|
+
* @returns The client's decision and the elicitation id used for later completion.
|
|
360
|
+
* @throws {TypedError} When called outside MCP, when the client lacks URL
|
|
361
|
+
* elicitation support, or when `url` is invalid.
|
|
362
|
+
*/
|
|
363
|
+
async elicitUrl(options: {
|
|
364
|
+
message: string;
|
|
365
|
+
url: string | URL;
|
|
366
|
+
elicitationId?: string;
|
|
367
|
+
}): Promise<McpUrlElicitationResult> {
|
|
368
|
+
return elicitMcpUrl(
|
|
369
|
+
{
|
|
370
|
+
connectionType: this.type,
|
|
371
|
+
context: this.mcpElicitationContext,
|
|
372
|
+
actionAbortSignal: this.actionAbortSignal,
|
|
373
|
+
},
|
|
374
|
+
options,
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Notify the initiating MCP client that an accepted URL elicitation completed.
|
|
380
|
+
*
|
|
381
|
+
* @param elicitationId - The id supplied to or returned by {@link elicitUrl}.
|
|
382
|
+
* @throws {TypedError} When called outside an active MCP request.
|
|
383
|
+
*/
|
|
384
|
+
async completeElicitation(elicitationId: string): Promise<void> {
|
|
385
|
+
await completeMcpElicitation(
|
|
386
|
+
{
|
|
387
|
+
connectionType: this.type,
|
|
388
|
+
context: this.mcpElicitationContext,
|
|
389
|
+
},
|
|
390
|
+
elicitationId,
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
|
|
298
394
|
/** Add a channel to this connection's subscription set. */
|
|
299
395
|
subscribe(channel: string) {
|
|
300
396
|
this.subscriptions.add(channel);
|
|
@@ -469,11 +565,18 @@ export class Connection<
|
|
|
469
565
|
}, timeoutMs);
|
|
470
566
|
});
|
|
471
567
|
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
568
|
+
const previousSignal = this.actionAbortSignal;
|
|
569
|
+
this.actionAbortSignal = controller.signal;
|
|
570
|
+
try {
|
|
571
|
+
return await Promise.race([
|
|
572
|
+
action.run(params, this, controller.signal),
|
|
573
|
+
timeoutPromise,
|
|
574
|
+
]);
|
|
575
|
+
} finally {
|
|
576
|
+
this.actionAbortSignal = previousSignal;
|
|
577
|
+
}
|
|
476
578
|
}
|
|
579
|
+
|
|
477
580
|
private async formatParams(params: Record<string, unknown>, action: Action) {
|
|
478
581
|
if (!action.inputs) return {} as ActionParams<Action>;
|
|
479
582
|
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ElicitRequestURLParams } from "@modelcontextprotocol/sdk/types.js";
|
|
2
|
+
import { ErrorType, TypedError } from "./TypedError";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Signals that an MCP request cannot continue until the client completes one or
|
|
6
|
+
* more URL elicitations and retries the original request.
|
|
7
|
+
*
|
|
8
|
+
* Throw this from an MCP action when work cannot remain pending inside the current
|
|
9
|
+
* tool call. Keryx maps it to the MCP `-32042` URL elicitation required error.
|
|
10
|
+
*/
|
|
11
|
+
export class McpUrlElicitationRequiredError extends TypedError {
|
|
12
|
+
/** URL elicitations the client must complete before retrying. */
|
|
13
|
+
readonly elicitations: ElicitRequestURLParams[];
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Create a URL elicitation required error.
|
|
17
|
+
*
|
|
18
|
+
* @param elicitations - One or more URL-mode elicitation descriptions. Each must
|
|
19
|
+
* include a stable `elicitationId`, absolute `url`, and user-facing `message`.
|
|
20
|
+
* @param message - Error message shown to the MCP client.
|
|
21
|
+
*/
|
|
22
|
+
constructor(
|
|
23
|
+
elicitations: ElicitRequestURLParams[],
|
|
24
|
+
message = "This request requires additional information.",
|
|
25
|
+
) {
|
|
26
|
+
super({
|
|
27
|
+
message,
|
|
28
|
+
type: ErrorType.CONNECTION_MCP_ELICITATION,
|
|
29
|
+
});
|
|
30
|
+
this.elicitations = elicitations;
|
|
31
|
+
}
|
|
32
|
+
}
|
package/classes/TypedError.ts
CHANGED
|
@@ -33,6 +33,7 @@ export enum ErrorType {
|
|
|
33
33
|
|
|
34
34
|
CONNECTION_ACTION_TIMEOUT = "CONNECTION_ACTION_TIMEOUT",
|
|
35
35
|
CONNECTION_RATE_LIMITED = "CONNECTION_RATE_LIMITED",
|
|
36
|
+
CONNECTION_MCP_ELICITATION = "CONNECTION_MCP_ELICITATION",
|
|
36
37
|
|
|
37
38
|
CONNECTION_TASK_DEFINITION = "CONNECTION_TASK_DEFINITION",
|
|
38
39
|
}
|
|
@@ -64,6 +65,7 @@ export const ErrorStatusCodes: Record<ErrorType, number> = {
|
|
|
64
65
|
[ErrorType.CONNECTION_CHANNEL_VALIDATION]: 400,
|
|
65
66
|
[ErrorType.CONNECTION_ACTION_TIMEOUT]: 408,
|
|
66
67
|
[ErrorType.CONNECTION_RATE_LIMITED]: 429,
|
|
68
|
+
[ErrorType.CONNECTION_MCP_ELICITATION]: 406,
|
|
67
69
|
|
|
68
70
|
[ErrorType.CONNECTION_TASK_DEFINITION]: 500,
|
|
69
71
|
};
|
package/config/database.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { loadFromEnvIfSet } from "../util/config";
|
|
2
2
|
|
|
3
3
|
export const configDatabase = {
|
|
4
|
-
|
|
4
|
+
/** Postgres connection URL. Empty (the default) or `"none"` runs without a database. */
|
|
5
|
+
connectionString: await loadFromEnvIfSet("DATABASE_URL", ""),
|
|
5
6
|
autoMigrate: await loadFromEnvIfSet("DATABASE_AUTO_MIGRATE", true),
|
|
6
7
|
pool: {
|
|
7
8
|
max: await loadFromEnvIfSet("DATABASE_POOL_MAX", 10),
|
package/index.ts
CHANGED
|
@@ -35,6 +35,7 @@ export type {
|
|
|
35
35
|
} from "./classes/Connection";
|
|
36
36
|
export { CONNECTION_TYPE, Connection } from "./classes/Connection";
|
|
37
37
|
export { LogLevel } from "./classes/Logger";
|
|
38
|
+
export { McpUrlElicitationRequiredError } from "./classes/McpUrlElicitationRequiredError";
|
|
38
39
|
export type { KeryxPlugin, PluginGenerator } from "./classes/Plugin";
|
|
39
40
|
export { SSEResponse, StreamingResponse } from "./classes/StreamingResponse";
|
|
40
41
|
export { ErrorStatusCodes, ErrorType, TypedError } from "./classes/TypedError";
|
|
@@ -69,6 +70,11 @@ export { buildProgram } from "./util/cli";
|
|
|
69
70
|
export { deepMerge, deepMergeDefaults, loadFromEnvIfSet } from "./util/config";
|
|
70
71
|
export { getValidTypes } from "./util/generate";
|
|
71
72
|
export { globLoader, globModuleExports } from "./util/glob";
|
|
73
|
+
export type {
|
|
74
|
+
McpElicitationAction,
|
|
75
|
+
McpFormElicitationResult,
|
|
76
|
+
McpUrlElicitationResult,
|
|
77
|
+
} from "./util/mcpElicitation";
|
|
72
78
|
export { type PaginatedResult, paginate } from "./util/pagination";
|
|
73
79
|
export { safeCompare } from "./util/safeCompare";
|
|
74
80
|
export type { JSONSchema } from "./util/swaggerSchemaGenerator";
|
|
@@ -80,7 +86,7 @@ export {
|
|
|
80
86
|
} from "./util/swaggerSchemaGenerator";
|
|
81
87
|
export { toMarkdown } from "./util/toMarkdown";
|
|
82
88
|
export type { DbOrTransaction, Transaction } from "./util/transaction";
|
|
83
|
-
export { withTransaction } from "./util/transaction";
|
|
89
|
+
export { assertDatabaseEnabled, withTransaction } from "./util/transaction";
|
|
84
90
|
export {
|
|
85
91
|
isSecret,
|
|
86
92
|
paginationInputs,
|
package/initializers/db.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { ErrorType, TypedError } from "../classes/TypedError";
|
|
|
14
14
|
import { config } from "../config";
|
|
15
15
|
import {
|
|
16
16
|
formatConnectionStringForLogging,
|
|
17
|
+
isDatabaseDisabled,
|
|
17
18
|
throwConnectionError,
|
|
18
19
|
} from "../util/connectionString";
|
|
19
20
|
import { globModuleExports } from "../util/glob";
|
|
@@ -72,6 +73,15 @@ declare module "keryx" {
|
|
|
72
73
|
}
|
|
73
74
|
}
|
|
74
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Initializer that connects Drizzle ORM to Postgres, runs migrations, and exposes
|
|
78
|
+
* `api.db.db` (the Drizzle instance), `api.db.pool` and `api.db.schema`.
|
|
79
|
+
*
|
|
80
|
+
* An empty `DATABASE_URL` (or `"none"`) disables the database: nothing connects, no
|
|
81
|
+
* migrations run, `api.db.enabled` is `false`, and `api.db.db` / `api.db.pool` stay
|
|
82
|
+
* unset. Helpers that need a database (`withTransaction`, `TransactionMiddleware`,
|
|
83
|
+
* `zIdOrModel`) then throw a clear `TypedError` instead.
|
|
84
|
+
*/
|
|
75
85
|
export class DB extends Initializer {
|
|
76
86
|
constructor() {
|
|
77
87
|
super(namespace);
|
|
@@ -91,12 +101,27 @@ export class DB extends Initializer {
|
|
|
91
101
|
generateMigrations: this.generateMigrations,
|
|
92
102
|
clearDatabase: this.clearDatabase,
|
|
93
103
|
schema,
|
|
104
|
+
/** `false` when `DATABASE_URL` is empty or `"none"` and no database is connected. */
|
|
105
|
+
enabled: false,
|
|
94
106
|
},
|
|
95
107
|
dbContainer,
|
|
96
108
|
);
|
|
97
109
|
}
|
|
98
110
|
|
|
99
111
|
async start() {
|
|
112
|
+
if (isDatabaseDisabled(config.database.connectionString)) {
|
|
113
|
+
api.db.enabled = false;
|
|
114
|
+
logger.warn('database disabled (DATABASE_URL is empty or "none")');
|
|
115
|
+
const tableCount = Object.keys(api.db.schema).length;
|
|
116
|
+
if (tableCount > 0) {
|
|
117
|
+
logger.warn(
|
|
118
|
+
`${tableCount} table(s) found in ${SCHEMA_DIR}/ will not be available without a database`,
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
api.db.enabled = true;
|
|
100
125
|
api.db.pool = new Pool({
|
|
101
126
|
connectionString: config.database.connectionString,
|
|
102
127
|
...config.database.pool,
|
|
@@ -216,6 +241,7 @@ export class DB extends Initializer {
|
|
|
216
241
|
|
|
217
242
|
/**
|
|
218
243
|
* Erase all the tables in the active database. Will fail on production environments.
|
|
244
|
+
* A no-op when the database is disabled.
|
|
219
245
|
*/
|
|
220
246
|
async clearDatabase(restartIdentity = true, cascade = true) {
|
|
221
247
|
if (Bun.env.NODE_ENV === "production") {
|
|
@@ -225,6 +251,8 @@ export class DB extends Initializer {
|
|
|
225
251
|
});
|
|
226
252
|
}
|
|
227
253
|
|
|
254
|
+
if (!api.db.enabled) return;
|
|
255
|
+
|
|
228
256
|
const { rows } = await api.db.db.execute(
|
|
229
257
|
sql`SELECT tablename FROM pg_tables WHERE schemaname = CURRENT_SCHEMA`,
|
|
230
258
|
);
|
package/initializers/redis.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { config } from "../config";
|
|
|
5
5
|
|
|
6
6
|
import {
|
|
7
7
|
formatConnectionStringForLogging,
|
|
8
|
+
isMemoryRedis,
|
|
8
9
|
throwConnectionError,
|
|
9
10
|
} from "../util/connectionString";
|
|
10
11
|
|
|
@@ -21,6 +22,12 @@ declare module "keryx" {
|
|
|
21
22
|
* Initializer that manages two Redis connections: `redis` for general commands and
|
|
22
23
|
* `subscription` for PubSub. Both are created during `start()` and closed during `stop()`.
|
|
23
24
|
* Exposes `api.redis.redis` and `api.redis.subscription` as ioredis `RedisClient` instances.
|
|
25
|
+
*
|
|
26
|
+
* When `REDIS_URL` uses the `memory:` scheme (e.g. `memory://`), both clients are
|
|
27
|
+
* in-process `ioredis-mock` instances that share one dataset instead of connections to
|
|
28
|
+
* a Redis server. Tasks, PubSub, presence, sessions and rate limiting all keep working,
|
|
29
|
+
* but state lives only in this process: it is not shared with other processes and is
|
|
30
|
+
* lost when the process exits. `api.redis.inMemory` reports which mode is active.
|
|
24
31
|
*/
|
|
25
32
|
export class Redis extends Initializer {
|
|
26
33
|
constructor() {
|
|
@@ -28,14 +35,29 @@ export class Redis extends Initializer {
|
|
|
28
35
|
}
|
|
29
36
|
|
|
30
37
|
async initialize() {
|
|
31
|
-
const redisContainer = {} as {
|
|
38
|
+
const redisContainer = { inMemory: false } as {
|
|
32
39
|
redis: RedisClient;
|
|
33
40
|
subscription: RedisClient;
|
|
41
|
+
/** `true` when `REDIS_URL` selected the in-process `memory://` Redis. */
|
|
42
|
+
inMemory: boolean;
|
|
34
43
|
};
|
|
35
44
|
return redisContainer;
|
|
36
45
|
}
|
|
37
46
|
|
|
38
47
|
async start() {
|
|
48
|
+
api.redis.inMemory = isMemoryRedis(config.redis.connectionString);
|
|
49
|
+
|
|
50
|
+
if (api.redis.inMemory) {
|
|
51
|
+
// Loaded on demand so apps using a real Redis never pay for ioredis-mock's Lua VM.
|
|
52
|
+
const { default: RedisMock } = await import("ioredis-mock");
|
|
53
|
+
api.redis.redis = new RedisMock();
|
|
54
|
+
api.redis.subscription = new RedisMock();
|
|
55
|
+
logger.warn(
|
|
56
|
+
"using in-memory redis (REDIS_URL=memory://): state is kept in this process only, is not shared with other processes, and is lost on restart",
|
|
57
|
+
);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
39
61
|
api.redis.redis = new RedisClient(config.redis.connectionString);
|
|
40
62
|
api.redis.subscription = new RedisClient(config.redis.connectionString);
|
|
41
63
|
|
package/initializers/resque.ts
CHANGED
|
@@ -100,10 +100,21 @@ export class Resque extends Initializer {
|
|
|
100
100
|
this.dependsOn = ["redis", "db", "actions", "process", "hooks"];
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
+
/**
|
|
104
|
+
* Connection options shared by the resque Queue, Scheduler and Workers. They all reuse
|
|
105
|
+
* `api.redis.redis`. With the in-memory Redis, `pkg: "ioredis-mock"` tells node-resque
|
|
106
|
+
* to skip its `cjson`-based Lua script (unsupported by ioredis-mock) and fall back to
|
|
107
|
+
* plain commands when workers pop jobs.
|
|
108
|
+
*/
|
|
109
|
+
connectionOptions = () => ({
|
|
110
|
+
redis: api.redis.redis,
|
|
111
|
+
...(api.redis.inMemory ? { pkg: "ioredis-mock" } : {}),
|
|
112
|
+
});
|
|
113
|
+
|
|
103
114
|
/** Create and connect the resque `Queue` instance (used for enqueuing jobs). */
|
|
104
115
|
startQueue = async () => {
|
|
105
116
|
api.resque.queue = new Queue(
|
|
106
|
-
{ connection:
|
|
117
|
+
{ connection: this.connectionOptions() },
|
|
107
118
|
api.resque.jobs,
|
|
108
119
|
);
|
|
109
120
|
|
|
@@ -125,7 +136,7 @@ export class Resque extends Initializer {
|
|
|
125
136
|
startScheduler = async () => {
|
|
126
137
|
if (config.tasks.enabled === true) {
|
|
127
138
|
api.resque.scheduler = new Scheduler({
|
|
128
|
-
connection:
|
|
139
|
+
connection: this.connectionOptions(),
|
|
129
140
|
timeout: config.tasks.timeout,
|
|
130
141
|
stuckWorkerTimeout: config.tasks.stuckWorkerTimeout,
|
|
131
142
|
retryStuckJobs: config.tasks.retryStuckJobs,
|
|
@@ -177,7 +188,7 @@ export class Resque extends Initializer {
|
|
|
177
188
|
while (id < config.tasks.taskProcessors) {
|
|
178
189
|
const worker = new Worker(
|
|
179
190
|
{
|
|
180
|
-
connection:
|
|
191
|
+
connection: this.connectionOptions(),
|
|
181
192
|
queues: Array.isArray(config.tasks.queues)
|
|
182
193
|
? config.tasks.queues
|
|
183
194
|
: await config.tasks.queues(),
|
|
@@ -4,7 +4,7 @@ import { api, logger } from "../api";
|
|
|
4
4
|
import type { ActionMiddleware } from "../classes/Action";
|
|
5
5
|
import type { Connection } from "../classes/Connection";
|
|
6
6
|
import type { TypedError } from "../classes/TypedError";
|
|
7
|
-
import type
|
|
7
|
+
import { assertDatabaseEnabled, type Transaction } from "../util/transaction";
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Action middleware that wraps the entire action execution in a database transaction.
|
|
@@ -50,6 +50,8 @@ export const TransactionMiddleware: ActionMiddleware = {
|
|
|
50
50
|
_params: Record<string, unknown>,
|
|
51
51
|
connection: Connection,
|
|
52
52
|
) => {
|
|
53
|
+
assertDatabaseEnabled("TransactionMiddleware");
|
|
54
|
+
|
|
53
55
|
// If a parent action already opened a transaction, reuse it.
|
|
54
56
|
// Track depth so only the outermost middleware commits/rolls back.
|
|
55
57
|
const depth = (connection.metadata._txDepth as number | undefined) ?? 0;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keryx",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.47.0",
|
|
4
4
|
"module": "index.ts",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -87,15 +87,17 @@
|
|
|
87
87
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
88
88
|
"@opentelemetry/api": "^1.9.1",
|
|
89
89
|
"@opentelemetry/sdk-metrics": "^2.7.0",
|
|
90
|
+
"@types/ioredis-mock": "^8.2.8",
|
|
91
|
+
"@types/mustache": "^4.2.6",
|
|
92
|
+
"@types/pg": "^8.20.0",
|
|
93
|
+
"commander": "^14.0.3",
|
|
90
94
|
"ioredis": "^5.10.1",
|
|
95
|
+
"ioredis-mock": "^8.13.1",
|
|
91
96
|
"mustache": "^4.2.0",
|
|
92
97
|
"node-resque": "^9.5.2",
|
|
93
98
|
"pg": "^8.20.0",
|
|
94
99
|
"ts-morph": "^28.0.0",
|
|
95
|
-
"typescript": "^7.0.2"
|
|
96
|
-
"commander": "^14.0.3",
|
|
97
|
-
"@types/mustache": "^4.2.6",
|
|
98
|
-
"@types/pg": "^8.20.0"
|
|
100
|
+
"typescript": "^7.0.2"
|
|
99
101
|
},
|
|
100
102
|
"peerDependencies": {
|
|
101
103
|
"drizzle-orm": "^0.45.2",
|
|
@@ -20,12 +20,27 @@ MCP_SERVER_ENABLED=true
|
|
|
20
20
|
SESSION_TTL=86400
|
|
21
21
|
SESSION_COOKIE_NAME="__session"
|
|
22
22
|
|
|
23
|
+
{{#includeDb}}
|
|
23
24
|
DATABASE_URL="postgres://$USER@localhost:5432/{{projectName}}"
|
|
24
25
|
DATABASE_URL_TEST="postgres://$USER@localhost:5432/{{projectName}}-test"
|
|
25
26
|
DATABASE_AUTO_MIGRATE=true
|
|
26
|
-
|
|
27
|
+
{{/includeDb}}
|
|
28
|
+
{{^includeDb}}
|
|
29
|
+
# No database: an empty DATABASE_URL (or "none") runs without PostgreSQL.
|
|
30
|
+
# Set a postgres:// URL here to add one later.
|
|
31
|
+
DATABASE_URL=""
|
|
32
|
+
{{/includeDb}}
|
|
33
|
+
|
|
34
|
+
{{#includeRedis}}
|
|
27
35
|
REDIS_URL="redis://localhost:6379/0"
|
|
28
36
|
REDIS_URL_TEST="redis://localhost:6379/1"
|
|
37
|
+
{{/includeRedis}}
|
|
38
|
+
{{^includeRedis}}
|
|
39
|
+
# In-memory Redis: tasks, PubSub, sessions and caching work without a Redis server,
|
|
40
|
+
# but state lives in this process only and is lost on restart.
|
|
41
|
+
# Use a redis:// URL to run more than one process or keep state across restarts.
|
|
42
|
+
REDIS_URL="memory://"
|
|
43
|
+
{{/includeRedis}}
|
|
29
44
|
|
|
30
45
|
RATE_LIMIT_ENABLED=true
|
|
31
46
|
RATE_LIMIT_WINDOW_MS=60000
|
package/testing/index.ts
CHANGED
|
@@ -65,8 +65,8 @@ export function serverUrl(): string {
|
|
|
65
65
|
* start/stop pair rather than splitting it, or handle cleanup in `afterEach`.
|
|
66
66
|
*
|
|
67
67
|
* @param opts.clearDatabase - Truncate all tables in `beforeAll`. Default `false`.
|
|
68
|
-
* Requires the `db` initializer to be active
|
|
69
|
-
* persistent state.
|
|
68
|
+
* Requires the `db` initializer to be active; a no-op when the database is
|
|
69
|
+
* disabled (empty `DATABASE_URL`). Opt in for tests that mutate persistent state.
|
|
70
70
|
* @param opts.clearRedis - Flush the current Redis DB in `beforeAll`. Default
|
|
71
71
|
* `false`. Requires the `redis` initializer to be active. Opt in for tests
|
|
72
72
|
* that exercise pub/sub so messages from prior tests don't leak in.
|
package/util/cli.ts
CHANGED
|
@@ -39,7 +39,14 @@ export async function buildProgram(opts: {
|
|
|
39
39
|
.description("Scaffold a new Keryx application with project boilerplate")
|
|
40
40
|
.option("-y, --yes", "Skip prompts and use defaults")
|
|
41
41
|
.option("--no-interactive", "Skip prompts and use defaults")
|
|
42
|
-
.option(
|
|
42
|
+
.option(
|
|
43
|
+
"--no-db",
|
|
44
|
+
"Run without PostgreSQL (no database files, empty DATABASE_URL)",
|
|
45
|
+
)
|
|
46
|
+
.option(
|
|
47
|
+
"--no-redis",
|
|
48
|
+
"Run without a Redis server (in-memory Redis, REDIS_URL=memory://)",
|
|
49
|
+
)
|
|
43
50
|
.option("--no-example", "Skip example action")
|
|
44
51
|
.option(
|
|
45
52
|
"--force",
|
|
@@ -52,6 +59,7 @@ export async function buildProgram(opts: {
|
|
|
52
59
|
projectName = projectName || "my-keryx-app";
|
|
53
60
|
options = {
|
|
54
61
|
includeDb: cmdOpts.db !== false,
|
|
62
|
+
includeRedis: cmdOpts.redis !== false,
|
|
55
63
|
includeExample: cmdOpts.example !== false,
|
|
56
64
|
force: cmdOpts.force === true,
|
|
57
65
|
};
|
package/util/connectionString.ts
CHANGED
|
@@ -1,7 +1,32 @@
|
|
|
1
1
|
import { ErrorType, TypedError } from "../classes/TypedError";
|
|
2
2
|
|
|
3
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* Whether a Redis connection string selects the in-process, in-memory Redis
|
|
5
|
+
* (`ioredis-mock`) instead of a real server. Any URL with the `memory:` scheme
|
|
6
|
+
* qualifies, e.g. `memory://`.
|
|
7
|
+
*
|
|
8
|
+
* @param connectionString - The configured `REDIS_URL`.
|
|
9
|
+
* @returns `true` for `memory:` URLs.
|
|
10
|
+
*/
|
|
11
|
+
export function isMemoryRedis(connectionString: string) {
|
|
12
|
+
return connectionString.trim().toLowerCase().startsWith("memory:");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Whether a database connection string turns the database off. An empty string
|
|
17
|
+
* or the literal `"none"` (case-insensitive) means "run without Postgres".
|
|
18
|
+
*
|
|
19
|
+
* @param connectionString - The configured `DATABASE_URL`.
|
|
20
|
+
* @returns `true` when no database should be connected.
|
|
21
|
+
*/
|
|
22
|
+
export function isDatabaseDisabled(connectionString: string) {
|
|
23
|
+
const value = connectionString.trim().toLowerCase();
|
|
24
|
+
return value === "" || value === "none";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Strip the password from a connection string for safe logging. Preserves protocol, user, host, port, and path. Unparseable strings are returned as `"(invalid connection string)"`. */
|
|
4
28
|
export function formatConnectionStringForLogging(connectionString: string) {
|
|
29
|
+
if (!URL.canParse(connectionString)) return "(invalid connection string)";
|
|
5
30
|
const connectionStringParsed = new URL(connectionString);
|
|
6
31
|
const connectionStringInfo = `${connectionStringParsed.protocol ? `${connectionStringParsed.protocol}//` : ""}${connectionStringParsed.username ? `${connectionStringParsed.username}@` : ""}${connectionStringParsed.hostname}:${connectionStringParsed.port}${connectionStringParsed.pathname}`;
|
|
7
32
|
return connectionStringInfo;
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ClientCapabilities,
|
|
3
|
+
ElicitRequestFormParams,
|
|
4
|
+
ElicitRequestURLParams,
|
|
5
|
+
ElicitResult,
|
|
6
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
7
|
+
import { ElicitRequestFormParamsSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
8
|
+
import { randomUUID } from "crypto";
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
import { ErrorType, TypedError } from "../classes/TypedError";
|
|
11
|
+
|
|
12
|
+
/** Result action returned by an MCP client for an elicitation request. */
|
|
13
|
+
export type McpElicitationAction = ElicitResult["action"];
|
|
14
|
+
|
|
15
|
+
/** Result of an MCP form elicitation, with accepted content inferred from its Zod schema. */
|
|
16
|
+
export type McpFormElicitationResult<TSchema extends z.ZodType> =
|
|
17
|
+
| { action: "accept"; content: z.infer<TSchema> }
|
|
18
|
+
| { action: "decline" | "cancel"; content?: undefined };
|
|
19
|
+
|
|
20
|
+
/** Result of an MCP URL elicitation. Acceptance means consent, not completion. */
|
|
21
|
+
export type McpUrlElicitationResult = {
|
|
22
|
+
action: McpElicitationAction;
|
|
23
|
+
elicitationId: string;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** @internal Request-scoped MCP functions attached by the MCP transport. */
|
|
27
|
+
export type McpElicitationContext = {
|
|
28
|
+
clientCapabilities?: ClientCapabilities;
|
|
29
|
+
requestSignal: AbortSignal;
|
|
30
|
+
elicitInput: (
|
|
31
|
+
params: ElicitRequestFormParams | ElicitRequestURLParams,
|
|
32
|
+
signal: AbortSignal,
|
|
33
|
+
) => Promise<ElicitResult>;
|
|
34
|
+
completeElicitation: (elicitationId: string) => Promise<void>;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
type McpElicitationState = {
|
|
38
|
+
connectionType: string;
|
|
39
|
+
context?: McpElicitationContext;
|
|
40
|
+
actionAbortSignal?: AbortSignal;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Ask an MCP client to collect and validate structured input.
|
|
45
|
+
*
|
|
46
|
+
* @param state - Current connection type, request context, and action abort signal.
|
|
47
|
+
* @param options - Human-readable prompt and flat Zod schema supported by MCP.
|
|
48
|
+
* @returns The client's decision and validated content when accepted.
|
|
49
|
+
* @throws {TypedError} When MCP is unavailable, the schema is incompatible, or
|
|
50
|
+
* accepted content fails validation.
|
|
51
|
+
* @internal
|
|
52
|
+
*/
|
|
53
|
+
export async function elicitMcpForm<TSchema extends z.ZodType>(
|
|
54
|
+
state: McpElicitationState,
|
|
55
|
+
options: {
|
|
56
|
+
message: string;
|
|
57
|
+
schema: TSchema;
|
|
58
|
+
},
|
|
59
|
+
): Promise<McpFormElicitationResult<TSchema>> {
|
|
60
|
+
const context = requireMcpElicitation(state, "form");
|
|
61
|
+
let requestedSchema: ElicitRequestFormParams["requestedSchema"];
|
|
62
|
+
try {
|
|
63
|
+
requestedSchema = ElicitRequestFormParamsSchema.shape.requestedSchema.parse(
|
|
64
|
+
z.toJSONSchema(options.schema, { target: "draft-7", io: "input" }),
|
|
65
|
+
);
|
|
66
|
+
} catch (cause) {
|
|
67
|
+
throw new TypedError({
|
|
68
|
+
message: `Invalid MCP form elicitation schema: ${cause}`,
|
|
69
|
+
type: ErrorType.CONNECTION_MCP_ELICITATION,
|
|
70
|
+
cause,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const result = await context.elicitInput(
|
|
75
|
+
{ mode: "form", message: options.message, requestedSchema },
|
|
76
|
+
mcpElicitationSignal(context, state.actionAbortSignal),
|
|
77
|
+
);
|
|
78
|
+
if (result.action !== "accept") return { action: result.action };
|
|
79
|
+
|
|
80
|
+
const parsed = await options.schema.safeParseAsync(result.content);
|
|
81
|
+
if (!parsed.success) {
|
|
82
|
+
throw new TypedError({
|
|
83
|
+
message: `MCP client returned invalid elicitation content: ${parsed.error.message}`,
|
|
84
|
+
type: ErrorType.CONNECTION_MCP_ELICITATION,
|
|
85
|
+
cause: parsed.error,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
return { action: "accept", content: parsed.data };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Ask an MCP client for consent to open an out-of-band URL.
|
|
93
|
+
*
|
|
94
|
+
* @param state - Current connection type, request context, and action abort signal.
|
|
95
|
+
* @param options - Message, absolute URL, and optional stable elicitation id.
|
|
96
|
+
* @returns The client's decision and the elicitation id used for completion.
|
|
97
|
+
* @throws {TypedError} When MCP or URL elicitation is unavailable, or `url` is invalid.
|
|
98
|
+
* @internal
|
|
99
|
+
*/
|
|
100
|
+
export async function elicitMcpUrl(
|
|
101
|
+
state: McpElicitationState,
|
|
102
|
+
options: {
|
|
103
|
+
message: string;
|
|
104
|
+
url: string | URL;
|
|
105
|
+
elicitationId?: string;
|
|
106
|
+
},
|
|
107
|
+
): Promise<McpUrlElicitationResult> {
|
|
108
|
+
const context = requireMcpElicitation(state, "url");
|
|
109
|
+
let url: string;
|
|
110
|
+
try {
|
|
111
|
+
url = new URL(options.url).toString();
|
|
112
|
+
} catch (cause) {
|
|
113
|
+
throw new TypedError({
|
|
114
|
+
message: `Invalid MCP elicitation URL: ${options.url}`,
|
|
115
|
+
type: ErrorType.CONNECTION_MCP_ELICITATION,
|
|
116
|
+
cause,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const elicitationId = options.elicitationId ?? randomUUID();
|
|
121
|
+
const result = await context.elicitInput(
|
|
122
|
+
{
|
|
123
|
+
mode: "url",
|
|
124
|
+
message: options.message,
|
|
125
|
+
url,
|
|
126
|
+
elicitationId,
|
|
127
|
+
},
|
|
128
|
+
mcpElicitationSignal(context, state.actionAbortSignal),
|
|
129
|
+
);
|
|
130
|
+
return { action: result.action, elicitationId };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Notify the initiating MCP client that URL elicitation completed.
|
|
135
|
+
*
|
|
136
|
+
* @param state - Current connection type and request context.
|
|
137
|
+
* @param elicitationId - Stable id supplied to URL elicitation.
|
|
138
|
+
* @returns A promise that resolves after the notification is sent.
|
|
139
|
+
* @throws {TypedError} When called outside an active URL-capable MCP request.
|
|
140
|
+
* @internal
|
|
141
|
+
*/
|
|
142
|
+
export async function completeMcpElicitation(
|
|
143
|
+
state: McpElicitationState,
|
|
144
|
+
elicitationId: string,
|
|
145
|
+
): Promise<void> {
|
|
146
|
+
const context = requireMcpElicitation(state, "url");
|
|
147
|
+
await context.completeElicitation(elicitationId);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function requireMcpElicitation(
|
|
151
|
+
state: McpElicitationState,
|
|
152
|
+
mode: "form" | "url",
|
|
153
|
+
): McpElicitationContext {
|
|
154
|
+
if (state.connectionType !== "mcp") {
|
|
155
|
+
throw new TypedError({
|
|
156
|
+
message: `MCP elicitation is only available on MCP connections (got ${state.connectionType})`,
|
|
157
|
+
type: ErrorType.CONNECTION_MCP_ELICITATION,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const context = state.context;
|
|
162
|
+
if (!context) {
|
|
163
|
+
throw new TypedError({
|
|
164
|
+
message: "MCP elicitation is only available during an MCP request",
|
|
165
|
+
type: ErrorType.CONNECTION_MCP_ELICITATION,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const elicitation = context.clientCapabilities?.elicitation;
|
|
170
|
+
const supportsForm =
|
|
171
|
+
elicitation !== undefined &&
|
|
172
|
+
(elicitation.form !== undefined || Object.keys(elicitation).length === 0);
|
|
173
|
+
const supported =
|
|
174
|
+
mode === "form" ? supportsForm : elicitation?.url !== undefined;
|
|
175
|
+
if (!supported) {
|
|
176
|
+
throw new TypedError({
|
|
177
|
+
message: `MCP client does not support ${mode} elicitation`,
|
|
178
|
+
type: ErrorType.CONNECTION_MCP_ELICITATION,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
return context;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function mcpElicitationSignal(
|
|
185
|
+
context: McpElicitationContext,
|
|
186
|
+
actionAbortSignal?: AbortSignal,
|
|
187
|
+
): AbortSignal {
|
|
188
|
+
return actionAbortSignal
|
|
189
|
+
? AbortSignal.any([context.requestSignal, actionAbortSignal])
|
|
190
|
+
: context.requestSignal;
|
|
191
|
+
}
|
package/util/mcpServer.ts
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
type ServerNotification,
|
|
11
11
|
type ServerRequest,
|
|
12
12
|
SUPPORTED_PROTOCOL_VERSIONS,
|
|
13
|
+
UrlElicitationRequiredError,
|
|
13
14
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
14
15
|
import { randomUUID } from "crypto";
|
|
15
16
|
import * as z4mini from "zod/v4-mini";
|
|
@@ -17,6 +18,7 @@ import { api, logger } from "../api";
|
|
|
17
18
|
import type { Action, McpUiConfig } from "../classes/Action";
|
|
18
19
|
import { MCP_APP_MIME_TYPE, MCP_RESPONSE_FORMAT } from "../classes/Action";
|
|
19
20
|
import { CONNECTION_TYPE, Connection } from "../classes/Connection";
|
|
21
|
+
import { McpUrlElicitationRequiredError } from "../classes/McpUrlElicitationRequiredError";
|
|
20
22
|
import { StreamingResponse } from "../classes/StreamingResponse";
|
|
21
23
|
import { ErrorType, TypedError } from "../classes/TypedError";
|
|
22
24
|
import { UIResponse } from "../classes/UIResponse";
|
|
@@ -58,10 +60,14 @@ export type McpAuthInfo = {
|
|
|
58
60
|
* Create an authenticated MCP Connection from the auth info attached to an MCP request.
|
|
59
61
|
* Shared by tool, resource, and prompt handlers to avoid duplicating connection setup.
|
|
60
62
|
*/
|
|
61
|
-
export async function createMcpConnection(
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
63
|
+
export async function createMcpConnection(
|
|
64
|
+
extra: {
|
|
65
|
+
authInfo?: McpAuthInfo;
|
|
66
|
+
sessionId?: string;
|
|
67
|
+
signal?: AbortSignal;
|
|
68
|
+
},
|
|
69
|
+
mcpServer?: McpServer,
|
|
70
|
+
): Promise<Connection> {
|
|
65
71
|
const authInfo = extra.authInfo;
|
|
66
72
|
const clientIp = (authInfo?.extra?.ip as string) || "unknown";
|
|
67
73
|
const connection = new Connection(
|
|
@@ -77,6 +83,17 @@ export async function createMcpConnection(extra: {
|
|
|
77
83
|
await connection.updateSession({ userId: authInfo.extra.userId });
|
|
78
84
|
}
|
|
79
85
|
|
|
86
|
+
if (mcpServer && extra.signal) {
|
|
87
|
+
connection.setMcpElicitationContext({
|
|
88
|
+
clientCapabilities: mcpServer.server.getClientCapabilities(),
|
|
89
|
+
requestSignal: extra.signal,
|
|
90
|
+
elicitInput: (params, signal) =>
|
|
91
|
+
mcpServer.server.elicitInput(params, { signal }),
|
|
92
|
+
completeElicitation: (elicitationId) =>
|
|
93
|
+
mcpServer.server.createElicitationCompletionNotifier(elicitationId)(),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
80
97
|
return connection;
|
|
81
98
|
}
|
|
82
99
|
|
|
@@ -613,7 +630,7 @@ function registerTools(mcpServer: McpServer) {
|
|
|
613
630
|
extra: RequestHandlerExtra<ServerRequest, ServerNotification>,
|
|
614
631
|
) => {
|
|
615
632
|
const mcpSessionId = extra.sessionId || "";
|
|
616
|
-
const connection = await createMcpConnection(extra);
|
|
633
|
+
const connection = await createMcpConnection(extra, mcpServer);
|
|
617
634
|
|
|
618
635
|
try {
|
|
619
636
|
const params =
|
|
@@ -629,6 +646,12 @@ function registerTools(mcpServer: McpServer) {
|
|
|
629
646
|
);
|
|
630
647
|
|
|
631
648
|
if (error) {
|
|
649
|
+
if (error instanceof McpUrlElicitationRequiredError) {
|
|
650
|
+
throw new UrlElicitationRequiredError(
|
|
651
|
+
error.elicitations,
|
|
652
|
+
error.message,
|
|
653
|
+
);
|
|
654
|
+
}
|
|
632
655
|
return {
|
|
633
656
|
content: [
|
|
634
657
|
{
|
|
@@ -724,7 +747,7 @@ function registerResources(mcpServer: McpServer) {
|
|
|
724
747
|
extra: any,
|
|
725
748
|
) => {
|
|
726
749
|
const mcpSessionId = extra.sessionId || "";
|
|
727
|
-
const connection = await createMcpConnection(extra);
|
|
750
|
+
const connection = await createMcpConnection(extra, mcpServer);
|
|
728
751
|
|
|
729
752
|
try {
|
|
730
753
|
const params: Record<string, unknown> = { ...variables };
|
|
@@ -853,7 +876,7 @@ function registerPrompts(mcpServer: McpServer) {
|
|
|
853
876
|
},
|
|
854
877
|
async (args: any, extra: any) => {
|
|
855
878
|
const mcpSessionId = extra.sessionId || "";
|
|
856
|
-
const connection = await createMcpConnection(extra);
|
|
879
|
+
const connection = await createMcpConnection(extra, mcpServer);
|
|
857
880
|
|
|
858
881
|
try {
|
|
859
882
|
const params =
|
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(
|
|
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 = {
|
|
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);
|
package/util/transaction.ts
CHANGED
|
@@ -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)
|