keryx 0.31.1 → 0.34.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/README.md CHANGED
@@ -10,11 +10,11 @@
10
10
 
11
11
  ## What is this Project?
12
12
 
13
- This is a ground-up rewrite of [ActionHero](https://www.actionherojs.com), built on [Bun](https://bun.sh). I still believe in the core ideas behind ActionHero — it was an attempt to take the best ideas from Rails and Node.js and shove them together — but the original framework needed a fresh start with Bun, Zod, Drizzle, and first-class MCP support.
13
+ The big idea behind Keryx: **write your controller once, and it works everywhere.** A single action class handles HTTP requests, WebSocket messages, CLI commands, background tasks, and MCP tool calls — same inputs, same Zod validation, same middleware, same response. You write the logic once; the only thing that changes is how the request arrived and how the response gets delivered.
14
14
 
15
- The big idea: **write your controller once, and it works everywhere**. A single action class handles HTTP requests, WebSocket messages, CLI commands, background tasks, and MCP tool calls — same inputs, same validation, same middleware, same response. No duplication.
15
+ That last transport — MCP — is the reason I built this now. Every action is automatically an MCP tool, so AI agents authenticate with built-in OAuth 2.1, get typed errors, and call the exact same validated endpoints your HTTP clients do. There's no second MCP server to maintain and no schemas to keep in sync… you expose your app to agents by writing the app.
16
16
 
17
- That includes AI agents. Every action is automatically an MCP tool — agents authenticate via built-in OAuth 2.1, get typed errors, and call the same validated endpoints your HTTP clients use. No separate MCP server, no duplicated schemas.
17
+ And it's a real backend, not a toy. You get Drizzle ORM with auto-migrations, background tasks with fan-out on Resque, streaming responses (SSE, chunked binary, and the same stream over WebSocket and MCP), OpenAPI generation, pagination and caching helpers, database transactions, and a companion Vite + React frontend that reads your actions with end-to-end type safety — no code generation. It's all on [Bun](https://bun.sh), so TypeScript runs natively and startup is fast.
18
18
 
19
19
  ### One Action, Every Transport
20
20
 
@@ -242,11 +242,11 @@ async run(params: { prompt: string }) {
242
242
 
243
243
  Over HTTP this is native SSE; over WebSocket each chunk becomes an incremental message; over MCP chunks are forwarded as logging messages. See the [Streaming guide](https://keryxjs.com/guide/streaming) for full details.
244
244
 
245
- ## Coming from ActionHero?
245
+ ## A Note on ActionHero
246
246
 
247
- Keryx keeps the core ideas but rewrites everything on Bun with first-class MCP support. The biggest changes: unified controllers (actions = tasks = CLI commands = MCP tools), separate frontend/backend applications, Drizzle ORM, and MCP as a first-class transport.
247
+ If you've used [ActionHero](https://www.actionherojs.com), Keryx will feel familiar — it's the spiritual successor. I built ActionHero years ago to take the best ideas from Rails and Node.js and shove them together, and I still believe in those ideas… but the framework needed a fresh start on Bun, Zod, and Drizzle, with first-class MCP support instead of something bolted on later. Keryx is that restart.
248
248
 
249
- See the full [migration guide](https://keryxjs.com/guide/from-actionhero) for details.
249
+ If you're coming from ActionHero, the biggest changes are: unified controllers (actions = tasks = CLI commands = MCP tools), separate frontend and backend applications, Drizzle ORM in place of Sequelize, and MCP as a first-class transport. See the full [migration guide](https://keryxjs.com/guide/from-actionhero) for details.
250
250
 
251
251
  ## Production Deployment
252
252
 
package/classes/API.ts CHANGED
@@ -26,7 +26,7 @@ export enum RUN_MODE {
26
26
  export class API {
27
27
  /** The root directory of the user's application. Set this before calling `initialize()`. */
28
28
  rootDir: string;
29
- /** The root directory of the keryx package itself (auto-resolved from `import.meta.filename`). */
29
+ /** The root directory of the keryx package itself (auto-resolved from `import.meta.path`). */
30
30
  packageDir: string;
31
31
  /** Whether `initialize()` has completed successfully. */
32
32
  initialized: boolean;
@@ -50,7 +50,7 @@ export class API {
50
50
 
51
51
  constructor() {
52
52
  this.bootTime = new Date().getTime();
53
- this.packageDir = path.join(import.meta.filename, "..", "..");
53
+ this.packageDir = path.join(import.meta.path, "..", "..");
54
54
  this.rootDir = this.packageDir;
55
55
  this.logger = new Logger(config.logger);
56
56
 
package/classes/Action.ts CHANGED
@@ -7,6 +7,56 @@ export enum MCP_RESPONSE_FORMAT {
7
7
  MARKDOWN = "markdown",
8
8
  }
9
9
 
10
+ /**
11
+ * MIME type for MCP App UI resources, per the MCP Apps extension.
12
+ * A `ui://` resource declared via an action's `mcp.ui` config is served with this type.
13
+ * @see {@link https://modelcontextprotocol.io/extensions/apps/overview}
14
+ */
15
+ export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
16
+
17
+ /**
18
+ * Configures an action as an **MCP App** — a tool whose result renders an interactive
19
+ * HTML UI in the host (Claude, Claude Desktop, VS Code Copilot, …) inside a sandboxed iframe.
20
+ *
21
+ * When set, Keryx registers a `ui://` resource that serves `html`, links the action's tool
22
+ * to it via the tool's `_meta.ui.resourceUri`, and — when `run()` returns a `UIResponse` —
23
+ * delivers `structuredContent` to the app for rendering.
24
+ *
25
+ * @see {@link https://modelcontextprotocol.io/extensions/apps/overview}
26
+ */
27
+ export type McpUiConfig = {
28
+ /**
29
+ * Self-contained HTML for the app UI. Keep external assets minimal (or inline them) so the
30
+ * default deny-by-default CSP applies. To serve HTML from a file, read it yourself
31
+ * (e.g. `await Bun.file(path).text()`) and pass the string here.
32
+ */
33
+ html: string;
34
+ /** The `ui://` resource URI. Defaults to `ui://<tool-name>`. */
35
+ resourceUri?: string;
36
+ /** Content-Security-Policy allowances for external origins the app may reach. */
37
+ csp?: {
38
+ /** Origins the app may `connect` to (fetch/XHR/WebSocket). */
39
+ connectDomains?: string[];
40
+ /** Origins the app may load sub-resources (scripts, styles, images, fonts) from. */
41
+ resourceDomains?: string[];
42
+ /** Origins the app may embed in nested frames. */
43
+ frameDomains?: string[];
44
+ /** Origins allowed in the app's `<base href>`. */
45
+ baseUriDomains?: string[];
46
+ };
47
+ /** Additional iframe capabilities the app requests (subject to host/user consent). */
48
+ permissions?: {
49
+ camera?: Record<string, never>;
50
+ microphone?: Record<string, never>;
51
+ geolocation?: Record<string, never>;
52
+ clipboardWrite?: Record<string, never>;
53
+ };
54
+ /** Hint that the host should render a border/frame around the app. */
55
+ prefersBorder?: boolean;
56
+ /** Logical domain grouping for the app (host-specific display/isolation hint). */
57
+ domain?: string;
58
+ };
59
+
10
60
  export enum HTTP_METHOD {
11
61
  GET = "GET",
12
62
  POST = "POST",
@@ -51,6 +101,13 @@ export type McpActionConfig = {
51
101
  /** Human-readable display title for the prompt */
52
102
  title?: string;
53
103
  };
104
+ /**
105
+ * Register this action as an **MCP App** (a dynamic UI). The tool is linked to an
106
+ * auto-registered `ui://` HTML resource, and the action's `run()` should return a
107
+ * {@link UIResponse} to deliver structured data to the app.
108
+ * @see {@link https://modelcontextprotocol.io/extensions/apps/overview}
109
+ */
110
+ ui?: McpUiConfig;
54
111
  /**
55
112
  * Response format for MCP tool calls.
56
113
  * `MCP_RESPONSE_FORMAT.JSON` (default) returns `JSON.stringify(response)`.
@@ -10,6 +10,7 @@ import type { Action, ActionParams } from "./Action";
10
10
  import { LogFormat } from "./Logger";
11
11
  import { StreamingResponse } from "./StreamingResponse";
12
12
  import { ErrorType, TypedError } from "./TypedError";
13
+ import { UIResponse } from "./UIResponse";
13
14
 
14
15
  /**
15
16
  * Per-invocation context passed to {@link BeforeActHook} and {@link AfterActHook}.
@@ -425,6 +426,10 @@ export class Connection<
425
426
  logger.warn(
426
427
  `Middleware cannot replace a StreamingResponse for action '${action.name}'`,
427
428
  );
429
+ } else if (updatedResponse instanceof UIResponse) {
430
+ logger.warn(
431
+ `Middleware cannot replace a UIResponse for action '${action.name}'`,
432
+ );
428
433
  } else {
429
434
  updatedResponse = middlewareResponse.updatedResponse;
430
435
  }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Response type for actions that back an **MCP App** (a dynamic UI).
3
+ * Actions return a `UIResponse` from `run()` to hand the host two payloads at once:
4
+ * a `structuredContent` object rendered by the app's HTML UI, and a `text`
5
+ * representation added to the model's context.
6
+ *
7
+ * See {@link https://modelcontextprotocol.io/extensions/apps/overview | MCP Apps}.
8
+ */
9
+
10
+ /**
11
+ * A response that pairs app-facing structured data with model-facing text.
12
+ *
13
+ * Returned from an action whose `mcp.ui` config declares an HTML UI. The MCP
14
+ * server delivers `structuredContent` to the app (via `ui/notifications/tool-result`,
15
+ * where it is used for rendering and is *not* added to model context) and the
16
+ * `text` as a normal text content block (which *is* added to model context).
17
+ *
18
+ * Over non-MCP transports (HTTP, WebSocket, CLI) a `UIResponse` serializes to
19
+ * its `structuredContent` via {@link UIResponse.toJSON}, so the same action still
20
+ * returns useful JSON everywhere.
21
+ *
22
+ * Use the static factory {@link UIResponse.from} or the constructor directly.
23
+ */
24
+ export class UIResponse {
25
+ /** Structured data delivered to the app UI for rendering (not added to model context). */
26
+ readonly structuredContent: Record<string, unknown>;
27
+ /**
28
+ * Text representation added to the model's context. Defaults to
29
+ * `JSON.stringify(structuredContent)` when not provided.
30
+ */
31
+ readonly text: string;
32
+
33
+ /**
34
+ * @param structuredContent - The structured data the app UI will render. Must be a
35
+ * JSON-serializable object; it is delivered to the app verbatim and is not added to
36
+ * the model's context.
37
+ * @param options - Optional model-facing text.
38
+ * @param options.text - Text representation added to the model's context. When omitted,
39
+ * defaults to `JSON.stringify(structuredContent)`.
40
+ */
41
+ constructor(
42
+ structuredContent: Record<string, unknown>,
43
+ options?: { text?: string },
44
+ ) {
45
+ this.structuredContent = structuredContent;
46
+ this.text = options?.text ?? JSON.stringify(structuredContent);
47
+ }
48
+
49
+ /**
50
+ * Convenience factory mirroring `StreamingResponse.sse()` / `.stream()`.
51
+ *
52
+ * @param structuredContent - The structured data the app UI will render.
53
+ * @param options - Optional model-facing text (see the constructor).
54
+ * @returns A new `UIResponse`.
55
+ */
56
+ static from(
57
+ structuredContent: Record<string, unknown>,
58
+ options?: { text?: string },
59
+ ): UIResponse {
60
+ return new UIResponse(structuredContent, options);
61
+ }
62
+
63
+ /**
64
+ * Serialize to the structured payload so non-MCP transports (HTTP, WebSocket, CLI)
65
+ * return the data rather than the wrapper object.
66
+ *
67
+ * @returns The `structuredContent` object.
68
+ */
69
+ toJSON(): Record<string, unknown> {
70
+ return this.structuredContent;
71
+ }
72
+ }
package/index.ts CHANGED
@@ -19,8 +19,12 @@ import "./initializers/signals";
19
19
  import "./initializers/swagger";
20
20
 
21
21
  export * from "./api";
22
- export type { ActionMiddleware } from "./classes/Action";
23
- export { HTTP_METHOD, MCP_RESPONSE_FORMAT } from "./classes/Action";
22
+ export type { ActionMiddleware, McpUiConfig } from "./classes/Action";
23
+ export {
24
+ HTTP_METHOD,
25
+ MCP_APP_MIME_TYPE,
26
+ MCP_RESPONSE_FORMAT,
27
+ } from "./classes/Action";
24
28
  export type { ChannelMiddleware } from "./classes/Channel";
25
29
  export { CHANNEL_NAME_PATTERN } from "./classes/Channel";
26
30
  export type {
@@ -34,6 +38,7 @@ export { LogLevel } from "./classes/Logger";
34
38
  export type { KeryxPlugin, PluginGenerator } from "./classes/Plugin";
35
39
  export { SSEResponse, StreamingResponse } from "./classes/StreamingResponse";
36
40
  export { ErrorStatusCodes, ErrorType, TypedError } from "./classes/TypedError";
41
+ export { UIResponse } from "./classes/UIResponse";
37
42
  export type { KeryxConfig } from "./config";
38
43
  export type { OnEnqueueHook } from "./initializers/actionts";
39
44
  export type {
@@ -10,7 +10,7 @@ import { globLoader } from "../util/glob";
10
10
 
11
11
  const namespace = "channels";
12
12
  const PRESENCE_KEY_PREFIX = "presence:";
13
- const LUA_DIR = join(import.meta.dirname, "..", "lua");
13
+ const LUA_DIR = join(import.meta.dir, "..", "lua");
14
14
 
15
15
  const ADD_PRESENCE_LUA = await Bun.file(
16
16
  join(LUA_DIR, "add-presence.lua"),
@@ -135,7 +135,7 @@ export class OAuthInitializer extends Initializer {
135
135
  return handleAuthorizeGet(url, templates);
136
136
  }
137
137
  if (path === OAUTH_PATHS.authorize && method === "POST") {
138
- return handleAuthorizePost(req, templates);
138
+ return handleAuthorizePost(req, templates, origin);
139
139
  }
140
140
  if (path === OAUTH_PATHS.token && method === "POST") {
141
141
  return appendHeaders(await handleToken(req), corsHeaders);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keryx",
3
- "version": "0.31.1",
3
+ "version": "0.34.1",
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -77,7 +77,7 @@
77
77
  "start": "bun keryx.ts start",
78
78
  "dev": "bun --watch keryx.ts start",
79
79
  "migrations": "bun run migrations.ts",
80
- "test": "tsc && bunx --bun vitest run",
80
+ "test": "tsc && bun test",
81
81
  "compile": "bun build keryx.ts --compile --outfile keryx",
82
82
  "lint": "tsc && biome check .",
83
83
  "format": "tsc && biome check --write .",
@@ -100,18 +100,11 @@
100
100
  "peerDependencies": {
101
101
  "drizzle-orm": "^0.45.2",
102
102
  "drizzle-zod": "^0.8.3",
103
- "vitest": "^4.1.9",
104
103
  "zod": "^4.3.6"
105
104
  },
106
- "peerDependenciesMeta": {
107
- "vitest": {
108
- "optional": true
109
- }
110
- },
111
105
  "devDependencies": {
112
106
  "@types/bun": "^1.3.12",
113
107
  "drizzle-kit": "^0.31.10",
114
- "drizzle-zod": "^0.8.3",
115
- "vitest": "^4.1.9"
108
+ "drizzle-zod": "^0.8.3"
116
109
  }
117
110
  }
@@ -1,4 +1,4 @@
1
- import { afterAll, beforeAll, describe, expect, test } from "vitest";
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
2
  import { api } from "keryx";
3
3
 
4
4
  beforeAll(async () => {
@@ -4,7 +4,7 @@ import { api } from "keryx";
4
4
  // actions, initializers, channels, etc. from this directory.
5
5
  // Every entry point (keryx.ts, migrations.ts, test setup) should
6
6
  // `import "./index"` to ensure rootDir is set before anything runs.
7
- api.rootDir = import.meta.dirname;
7
+ api.rootDir = import.meta.dir;
8
8
 
9
9
  // Re-export everything from keryx for convenience
10
10
  export * from "keryx";
package/testing/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { afterAll, beforeAll } from "vitest";
1
+ import { afterAll, beforeAll } from "bun:test";
2
2
  import { api } from "../api";
3
3
  import type { WebServer } from "../servers/web";
4
4
 
@@ -1,4 +1,4 @@
1
- import { expect } from "vitest";
1
+ import { expect } from "bun:test";
2
2
  import { api } from "../api";
3
3
  import type { WebServer } from "../servers/web";
4
4
 
@@ -24,13 +24,13 @@ export interface ComponentDef {
24
24
  }
25
25
 
26
26
  const generateTemplatesDir = path.join(
27
- import.meta.dirname,
27
+ import.meta.dir,
28
28
  "..",
29
29
  "templates",
30
30
  "generate",
31
31
  );
32
32
  const scaffoldTemplatesDir = path.join(
33
- import.meta.dirname,
33
+ import.meta.dir,
34
34
  "..",
35
35
  "templates",
36
36
  "scaffold",
package/util/mcpServer.ts CHANGED
@@ -11,11 +11,12 @@ import type {
11
11
  import { randomUUID } from "crypto";
12
12
  import * as z4mini from "zod/v4-mini";
13
13
  import { api, logger } from "../api";
14
- import type { Action } from "../classes/Action";
15
- import { MCP_RESPONSE_FORMAT } from "../classes/Action";
14
+ import type { Action, McpUiConfig } from "../classes/Action";
15
+ import { MCP_APP_MIME_TYPE, MCP_RESPONSE_FORMAT } from "../classes/Action";
16
16
  import { CONNECTION_TYPE, Connection } from "../classes/Connection";
17
17
  import { StreamingResponse } from "../classes/StreamingResponse";
18
18
  import { ErrorType, TypedError } from "../classes/TypedError";
19
+ import { UIResponse } from "../classes/UIResponse";
19
20
  import { config } from "../config";
20
21
  import pkg from "../package.json";
21
22
  import { appendHeaders } from "../util/http";
@@ -135,11 +136,35 @@ export function createMcpServer(): McpServer {
135
136
 
136
137
  registerTools(mcpServer);
137
138
  registerResources(mcpServer);
139
+ registerUiResources(mcpServer);
138
140
  registerPrompts(mcpServer);
139
141
 
140
142
  return mcpServer;
141
143
  }
142
144
 
145
+ /**
146
+ * Compute the `ui://` resource URI for an action's MCP App.
147
+ * Defaults to `ui://<tool-name>` when `mcp.ui.resourceUri` is not set.
148
+ */
149
+ function uiResourceUri(action: Action): string {
150
+ return action.mcp?.ui?.resourceUri ?? `ui://${formatToolName(action.name)}`;
151
+ }
152
+
153
+ /**
154
+ * Build the MCP Apps `_meta.ui` object from an action's `mcp.ui` config,
155
+ * omitting empty sub-objects so the resource metadata stays minimal.
156
+ */
157
+ function buildUiMeta(ui: McpUiConfig): Record<string, unknown> {
158
+ const meta: Record<string, unknown> = {};
159
+ if (ui.csp && Object.keys(ui.csp).length > 0) meta.csp = ui.csp;
160
+ if (ui.permissions && Object.keys(ui.permissions).length > 0) {
161
+ meta.permissions = ui.permissions;
162
+ }
163
+ if (ui.prefersBorder !== undefined) meta.prefersBorder = ui.prefersBorder;
164
+ if (ui.domain !== undefined) meta.domain = ui.domain;
165
+ return meta;
166
+ }
167
+
143
168
  function registerTools(mcpServer: McpServer) {
144
169
  const registered = new Set<string>();
145
170
  for (const action of api.actions.actions) {
@@ -151,6 +176,7 @@ function registerTools(mcpServer: McpServer) {
151
176
  const toolConfig: {
152
177
  description?: string;
153
178
  inputSchema?: any;
179
+ _meta?: Record<string, unknown>;
154
180
  } = {};
155
181
 
156
182
  if (action.description) {
@@ -161,6 +187,12 @@ function registerTools(mcpServer: McpServer) {
161
187
  ? sanitizeSchemaForMcp(action.inputs)
162
188
  : z4mini.strictObject({});
163
189
 
190
+ // Link MCP App tools to their `ui://` resource so the host can preload and
191
+ // render the UI. See https://modelcontextprotocol.io/extensions/apps/overview
192
+ if (action.mcp?.ui) {
193
+ toolConfig._meta = { ui: { resourceUri: uiResourceUri(action) } };
194
+ }
195
+
164
196
  mcpServer.registerTool(
165
197
  toolName,
166
198
  toolConfig,
@@ -228,6 +260,15 @@ function registerTools(mcpServer: McpServer) {
228
260
  };
229
261
  }
230
262
 
263
+ // MCP App responses carry both a text block (added to model context)
264
+ // and structuredContent (delivered to the app UI for rendering).
265
+ if (response instanceof UIResponse) {
266
+ return {
267
+ content: [{ type: "text" as const, text: response.text }],
268
+ structuredContent: response.structuredContent,
269
+ };
270
+ }
271
+
231
272
  const format = action.mcp?.responseFormat ?? MCP_RESPONSE_FORMAT.JSON;
232
273
  const text =
233
274
  format === MCP_RESPONSE_FORMAT.MARKDOWN
@@ -323,6 +364,50 @@ function registerResources(mcpServer: McpServer) {
323
364
  }
324
365
  }
325
366
 
367
+ /**
368
+ * Register a `ui://` HTML resource for every action that declares `mcp.ui`.
369
+ * The resource serves the app's self-contained HTML with the MCP Apps MIME type
370
+ * and any `_meta.ui` (CSP, permissions, etc.). The matching tool is linked to it
371
+ * via `_meta.ui.resourceUri` in `registerTools()`.
372
+ */
373
+ function registerUiResources(mcpServer: McpServer) {
374
+ const registered = new Set<string>();
375
+ for (const action of api.actions.actions) {
376
+ const ui = action.mcp?.ui;
377
+ if (!ui) continue;
378
+
379
+ const resourceUri = uiResourceUri(action);
380
+ if (registered.has(resourceUri)) {
381
+ logger.warn(
382
+ `Skipping duplicate MCP App UI resource '${resourceUri}' (action '${action.name}')`,
383
+ );
384
+ continue;
385
+ }
386
+ registered.add(resourceUri);
387
+
388
+ const uiMeta = buildUiMeta(ui);
389
+ const hasMeta = Object.keys(uiMeta).length > 0;
390
+ const metadata: Record<string, unknown> = { mimeType: MCP_APP_MIME_TYPE };
391
+ if (hasMeta) metadata._meta = { ui: uiMeta };
392
+
393
+ mcpServer.registerResource(
394
+ `${formatToolName(action.name)}-ui`,
395
+ resourceUri,
396
+ metadata,
397
+ (mcpUri: URL) => ({
398
+ contents: [
399
+ {
400
+ uri: mcpUri.toString(),
401
+ mimeType: MCP_APP_MIME_TYPE,
402
+ text: ui.html,
403
+ ...(hasMeta ? { _meta: { ui: uiMeta } } : {}),
404
+ },
405
+ ],
406
+ }),
407
+ );
408
+ }
409
+ }
410
+
326
411
  function registerPrompts(mcpServer: McpServer) {
327
412
  for (const action of api.actions.actions) {
328
413
  if (!action.mcp?.prompt) continue;
@@ -90,10 +90,19 @@ async function runAuthAction(
90
90
  }
91
91
  }
92
92
 
93
- /** Handle the OAuth authorize form POST (signin/signup). */
93
+ /**
94
+ * Handle the OAuth authorize form POST (signin/signup).
95
+ *
96
+ * @param req - The incoming form POST request.
97
+ * @param templates - Loaded OAuth HTML templates for rendering the auth/success pages.
98
+ * @param origin - The externally-visible origin of this authorization server. Used
99
+ * as the `iss` (issuer) value on the authorization-code redirect per RFC 9207
100
+ * (MCP 2026-07-28 / SEP-2468); matches the `issuer` advertised in AS metadata.
101
+ */
94
102
  export async function handleAuthorizePost(
95
103
  req: Request,
96
104
  templates: OAuthTemplates,
105
+ origin: string,
97
106
  ): Promise<Response> {
98
107
  let fields: Record<string, string>;
99
108
  try {
@@ -163,6 +172,8 @@ export async function handleAuthorizePost(
163
172
 
164
173
  const redirectUrl = new URL(oauthParams.redirectUri);
165
174
  redirectUrl.searchParams.set("code", code);
175
+ // RFC 9207 — advertise the issuer so the client can detect mix-up attacks.
176
+ redirectUrl.searchParams.set("iss", origin);
166
177
  if (oauthParams.state)
167
178
  redirectUrl.searchParams.set("state", oauthParams.state);
168
179
 
@@ -30,6 +30,9 @@ export function handleMetadata(origin: string): Response {
30
30
  response_types_supported: ["code"],
31
31
  grant_types_supported: ["authorization_code", "refresh_token"],
32
32
  code_challenge_methods_supported: ["S256"],
33
+ // RFC 9207 — return the `iss` parameter on authorization responses so
34
+ // clients can guard against mix-up attacks (MCP 2026-07-28 / SEP-2468).
35
+ authorization_response_iss_parameter_supported: true,
33
36
  token_endpoint_auth_methods_supported: ["none"],
34
37
  introspection_endpoint_auth_methods_supported: ["none"],
35
38
  revocation_endpoint_auth_methods_supported: ["none"],
@@ -37,6 +37,17 @@ export async function handleRegister(req: Request): Promise<Response> {
37
37
  }
38
38
  }
39
39
 
40
+ // `application_type` is required of clients per MCP 2026-07-28 / SEP-837, but
41
+ // remains optional here for backwards compatibility; default to the OIDC
42
+ // default of "web" when omitted (RFC 7591).
43
+ const applicationType = body.application_type ?? "web";
44
+ if (applicationType !== "web" && applicationType !== "native") {
45
+ return oauthError(
46
+ "invalid_client_metadata",
47
+ 'application_type must be "web" or "native"',
48
+ );
49
+ }
50
+
40
51
  const clientId = randomUUID();
41
52
  const client: OAuthClient = {
42
53
  client_id: clientId,
@@ -45,6 +56,7 @@ export async function handleRegister(req: Request): Promise<Response> {
45
56
  grant_types: body.grant_types ?? ["authorization_code"],
46
57
  response_types: body.response_types ?? ["code"],
47
58
  token_endpoint_auth_method: body.token_endpoint_auth_method ?? "none",
59
+ application_type: applicationType,
48
60
  };
49
61
 
50
62
  await api.redis.redis.set(
@@ -5,6 +5,12 @@ export type OAuthClient = {
5
5
  grant_types?: string[];
6
6
  response_types?: string[];
7
7
  token_endpoint_auth_method?: string;
8
+ /**
9
+ * OpenID Connect `application_type` (`"web"` | `"native"`), declared at
10
+ * registration per MCP 2026-07-28 / SEP-837 so the authorization server does
11
+ * not misclassify native/CLI clients as web clients. Defaults to `"web"`.
12
+ */
13
+ application_type?: "web" | "native";
8
14
  };
9
15
 
10
16
  export type AuthCode = {
@@ -20,7 +20,7 @@ export type OAuthTemplates = {
20
20
  lionSvg: string;
21
21
  };
22
22
 
23
- const frameworkTemplatesDir = import.meta.dirname + "/../templates";
23
+ const frameworkTemplatesDir = import.meta.dir + "/../templates";
24
24
 
25
25
  /**
26
26
  * Resolve a template file, checking the user's rootDir first, then falling back
package/util/scaffold.ts CHANGED
@@ -66,7 +66,7 @@ export async function generateOAuthTemplateContents(): Promise<
66
66
  "oauth-common.css",
67
67
  "lion.svg",
68
68
  ];
69
- const sourceDir = path.join(import.meta.dirname, "..", "templates");
69
+ const sourceDir = path.join(import.meta.dir, "..", "templates");
70
70
 
71
71
  for (const file of oauthTemplates) {
72
72
  const content = await Bun.file(path.join(sourceDir, file)).text();
@@ -85,7 +85,7 @@ export async function generateConfigFileContents(): Promise<
85
85
  Map<string, string>
86
86
  > {
87
87
  const result = new Map<string, string>();
88
- const configDir = path.join(import.meta.dirname, "..", "config");
88
+ const configDir = path.join(import.meta.dir, "..", "config");
89
89
  const glob = new Glob("**/*.ts");
90
90
 
91
91
  for await (const file of glob.scan(configDir)) {
@@ -140,7 +140,7 @@ export async function generateBuiltinActionContents(): Promise<
140
140
  > {
141
141
  const result = new Map<string, string>();
142
142
  const builtinActions = ["status.ts", "swagger.ts"];
143
- const actionsDir = path.join(import.meta.dirname, "..", "actions");
143
+ const actionsDir = path.join(import.meta.dir, "..", "actions");
144
144
 
145
145
  for (const file of builtinActions) {
146
146
  let content = await Bun.file(path.join(actionsDir, file)).text();
@@ -318,7 +318,6 @@ export async function scaffoldProject(
318
318
  start: "bun keryx.ts start",
319
319
  dev: "bun --watch keryx.ts start",
320
320
  ...(options.includeDb ? { migrations: "bun run migrations.ts" } : {}),
321
- test: "tsc && bunx --bun vitest run",
322
321
  lint: "tsc && biome check .",
323
322
  format: "tsc && biome check --write .",
324
323
  },
@@ -335,7 +334,6 @@ export async function scaffoldProject(
335
334
  devDependencies: {
336
335
  "@biomejs/biome": "^2.4.8",
337
336
  "@types/bun": "latest",
338
- vitest: "^4.1.9",
339
337
  ...(options.includeDb ? { "drizzle-kit": "^0.20.18" } : {}),
340
338
  },
341
339
  },
@@ -345,7 +343,6 @@ export async function scaffoldProject(
345
343
  );
346
344
 
347
345
  await write("tsconfig.json", generateTsconfigContents());
348
- await writeTemplate("vitest.config.ts", "vitest.config.ts.mustache");
349
346
  await write(
350
347
  "biome.json",
351
348
  JSON.stringify(
@@ -1,18 +0,0 @@
1
- import { defineConfig } from "vitest/config";
2
-
3
- export default defineConfig({
4
- test: {
5
- include: ["__tests__/**/*.test.ts"],
6
- globals: false,
7
- // Run on the Bun runtime via `bunx --bun vitest`. The forks pool keeps
8
- // Node/Bun process APIs available; file parallelism is disabled so test
9
- // files that boot the server don't race on the shared database/Redis.
10
- pool: "forks",
11
- fileParallelism: false,
12
- testTimeout: 15_000,
13
- hookTimeout: 60_000,
14
- // zod (and other CJS deps consumed via named imports) must be transformed
15
- // by Vite so the named-export interop works under the Bun runtime.
16
- server: { deps: { inline: ["zod"] } },
17
- },
18
- });