keryx 0.32.0 → 0.35.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 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/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
+ }
@@ -4,6 +4,16 @@ import { loadFromEnvIfSet } from "../../util/config";
4
4
  export const configServerMcp = {
5
5
  enabled: await loadFromEnvIfSet("MCP_SERVER_ENABLED", false),
6
6
  route: await loadFromEnvIfSet("MCP_SERVER_ROUTE", "/mcp"),
7
+ allowedOrigins: await loadFromEnvIfSet(
8
+ "MCP_ALLOWED_ORIGINS",
9
+ [
10
+ "https://claude.ai", // Anthropic Claude web connector
11
+ "https://claude.com", // Anthropic Claude web connector
12
+ "https://chatgpt.com", // OpenAI ChatGPT connectors
13
+ "https://vscode.dev", // VS Code for the Web
14
+ "https://github.dev", // github.dev web editor
15
+ ].join(","),
16
+ ),
7
17
  instructions: await loadFromEnvIfSet(
8
18
  "MCP_SERVER_INSTRUCTIONS",
9
19
  pkg.description as string,
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 {
@@ -6,7 +6,12 @@ import { Initializer } from "../classes/Initializer";
6
6
  import { ErrorType, TypedError } from "../classes/TypedError";
7
7
  import { config } from "../config";
8
8
  import { ansi } from "../util/ansi";
9
- import { buildCorsHeaders, getExternalOrigin } from "../util/http";
9
+ import {
10
+ buildCorsHeaders,
11
+ getExternalOrigin,
12
+ getMcpAllowedOrigins,
13
+ isOriginAllowed,
14
+ } from "../util/http";
10
15
  import {
11
16
  createMcpServer,
12
17
  formatToolName,
@@ -142,26 +147,29 @@ export class McpInitializer extends Initializer {
142
147
  ): Promise<Response> => {
143
148
  const method = req.method.toUpperCase();
144
149
  const requestOrigin = req.headers.get("origin") ?? undefined;
145
- const corsHeaders = buildCorsHeaders(requestOrigin, {
146
- "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
147
- "Access-Control-Allow-Headers":
148
- "Content-Type, mcp-session-id, Authorization",
149
- "Access-Control-Expose-Headers": "mcp-session-id",
150
- });
150
+ const mcpAllowedOrigins = getMcpAllowedOrigins();
151
+ const corsHeaders = buildCorsHeaders(
152
+ requestOrigin,
153
+ {
154
+ "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
155
+ "Access-Control-Allow-Headers":
156
+ "Content-Type, mcp-session-id, Authorization",
157
+ "Access-Control-Expose-Headers": "mcp-session-id",
158
+ },
159
+ mcpAllowedOrigins,
160
+ );
151
161
 
152
- // Reject requests from unrecognized origins when APPLICATION_URL is set
153
- if (requestOrigin) {
154
- const appUrl = config.server.web.applicationUrl;
155
- if (appUrl && !appUrl.startsWith("http://localhost")) {
156
- const allowedOrigin = new URL(appUrl).origin;
157
- if (requestOrigin !== allowedOrigin) {
158
- return mcpJsonResponse(
159
- { error: "Origin not allowed" },
160
- 403,
161
- corsHeaders,
162
- );
163
- }
164
- }
162
+ // Reject browser requests from unrecognized origins. Requests with no
163
+ // Origin (non-browser clients like the Claude Code CLI) always pass; the
164
+ // bearer token is the real security boundary for this public endpoint.
165
+ // Uses the same allowlist as buildCorsHeaders above so the 403 gate and
166
+ // the Access-Control-Allow-Origin reflection can never disagree.
167
+ if (requestOrigin && !isOriginAllowed(requestOrigin, mcpAllowedOrigins)) {
168
+ return mcpJsonResponse(
169
+ { error: "Origin not allowed" },
170
+ 403,
171
+ corsHeaders,
172
+ );
165
173
  }
166
174
 
167
175
  // Handle OPTIONS for CORS preflight
@@ -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.32.0",
3
+ "version": "0.35.0",
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/util/http.ts CHANGED
@@ -2,12 +2,49 @@ import { config } from "../config";
2
2
 
3
3
  /**
4
4
  * Check whether a request origin is permitted by the configured allowed-origins list.
5
+ *
6
+ * @param origin - The request `Origin` to check.
7
+ * @param extraAllowedOrigins - Additional origins to permit beyond
8
+ * `WEB_SERVER_ALLOWED_ORIGINS`. Used by the MCP endpoint to admit
9
+ * browser connector origins (see {@link getMcpAllowedOrigins}) so
10
+ * the origin gate and CORS reflection share one allowlist. When
11
+ * `WEB_SERVER_ALLOWED_ORIGINS` is `"*"`, all origins are allowed and
12
+ * this list is not consulted.
5
13
  */
6
- export function isOriginAllowed(origin: string): boolean {
14
+ export function isOriginAllowed(
15
+ origin: string,
16
+ extraAllowedOrigins: string[] = [],
17
+ ): boolean {
7
18
  const allowedOrigins = config.server.web.allowedOrigins;
8
19
  if (allowedOrigins === "*") return true;
9
20
  const allowed = allowedOrigins.split(",").map((o) => o.trim());
10
- return allowed.includes(origin);
21
+ return allowed.includes(origin) || extraAllowedOrigins.includes(origin);
22
+ }
23
+
24
+ /**
25
+ * Compute the extra origins permitted to reach the MCP endpoint from a browser,
26
+ * on top of `WEB_SERVER_ALLOWED_ORIGINS`. Always includes the `applicationUrl`
27
+ * origin (the server's own domain) plus the configurable `MCP_ALLOWED_ORIGINS`
28
+ * list (defaults to the popular browser-based agent connector origins).
29
+ *
30
+ * Passed to both {@link buildCorsHeaders} and {@link isOriginAllowed} in the MCP
31
+ * request handler so the 403 origin gate and the CORS `Access-Control-Allow-Origin`
32
+ * reflection can never disagree.
33
+ */
34
+ export function getMcpAllowedOrigins(): string[] {
35
+ const origins: string[] = [];
36
+ const appUrl = config.server.web.applicationUrl;
37
+ if (appUrl) origins.push(new URL(appUrl).origin);
38
+ const configured = config.server.mcp.allowedOrigins;
39
+ if (configured) {
40
+ origins.push(
41
+ ...configured
42
+ .split(",")
43
+ .map((o) => o.trim())
44
+ .filter(Boolean),
45
+ );
46
+ }
47
+ return origins;
11
48
  }
12
49
 
13
50
  /**
@@ -16,17 +53,24 @@ export function isOriginAllowed(origin: string): boolean {
16
53
  * @param requestOrigin - The `Origin` header from the incoming request (if any).
17
54
  * @param extra - Additional CORS headers to merge (e.g. `Access-Control-Allow-Methods`).
18
55
  * Any key not already set will be added.
56
+ * @param extraAllowedOrigins - Additional origins to permit beyond
57
+ * `WEB_SERVER_ALLOWED_ORIGINS` when deciding whether to reflect
58
+ * `Access-Control-Allow-Origin` (see {@link isOriginAllowed}).
19
59
  */
20
60
  export function buildCorsHeaders(
21
61
  requestOrigin: string | undefined,
22
62
  extra?: Record<string, string>,
63
+ extraAllowedOrigins: string[] = [],
23
64
  ): Record<string, string> {
24
65
  const headers: Record<string, string> = { ...extra };
25
66
  const allowedOrigins = config.server.web.allowedOrigins;
26
67
 
27
68
  if (allowedOrigins === "*" && !requestOrigin) {
28
69
  headers["Access-Control-Allow-Origin"] = "*";
29
- } else if (requestOrigin && isOriginAllowed(requestOrigin)) {
70
+ } else if (
71
+ requestOrigin &&
72
+ isOriginAllowed(requestOrigin, extraAllowedOrigins)
73
+ ) {
30
74
  headers["Access-Control-Allow-Origin"] = requestOrigin;
31
75
  headers["Vary"] = "Origin";
32
76
  }
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 = {