keryx 0.37.1 → 0.38.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/classes/Action.ts CHANGED
@@ -25,12 +25,30 @@ export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
25
25
  * @see {@link https://modelcontextprotocol.io/extensions/apps/overview}
26
26
  */
27
27
  export type McpUiConfig = {
28
+ /**
29
+ * Browser entrypoint for the app UI. Keryx bundles it at boot (with Bun's browser
30
+ * bundler) and inlines the result into {@link McpUiConfig.html} — or a default
31
+ * self-contained shell — to produce the served HTML. Point it at a `.ts`/`.tsx`
32
+ * file, e.g. `new URL("./app/status.ts", import.meta.url)`.
33
+ *
34
+ * Provide `client`, `html`, or both. With only `client`, Keryx wraps the bundle in a
35
+ * default shell (a document containing a `<div id="root">`). With both, `html` is the
36
+ * shell the bundle is inlined into. See {@link McpUiConfig.html}.
37
+ */
38
+ client?: string | URL;
28
39
  /**
29
40
  * 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.
41
+ * default deny-by-default CSP applies.
42
+ *
43
+ * - **Without `client`:** served verbatim — you inline your own scripts/styles. To serve
44
+ * HTML from a file, read it yourself (e.g. `await Bun.file(path).text()`) and pass the string.
45
+ * - **With `client`:** treated as the shell the bundled client is inlined into — at an empty
46
+ * `<script type="module"></script>`, else a placeholder comment (`MCP_APP_CLIENT`), else
47
+ * appended before `</body>`.
48
+ *
49
+ * At least one of `client` or `html` must be set.
32
50
  */
33
- html: string;
51
+ html?: string;
34
52
  /** The `ui://` resource URI. Defaults to `ui://<tool-name>`. */
35
53
  resourceUri?: string;
36
54
  /** Content-Security-Policy allowances for external origins the app may reach. */
@@ -13,6 +13,7 @@ import {
13
13
  getMcpAllowedOrigins,
14
14
  isOriginAllowed,
15
15
  } from "../util/http";
16
+ import { resolveMcpAppUiResources } from "../util/mcpAppBundler";
16
17
  import {
17
18
  adoptMcpSession,
18
19
  createMcpServer,
@@ -162,6 +163,11 @@ export class McpInitializer extends Initializer {
162
163
  }
163
164
  }
164
165
 
166
+ // Bundle every MCP App UI (mcp.ui.client) once, before any session can be
167
+ // created, so per-session resource registration serves pre-built HTML and a
168
+ // bundle error fails startup fast.
169
+ await resolveMcpAppUiResources();
170
+
165
171
  // Build handleRequest — each new session creates a fresh McpServer
166
172
  const transports = api.mcp.transports;
167
173
  const mcpServers = api.mcp.mcpServers;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keryx",
3
- "version": "0.37.1",
3
+ "version": "0.38.0",
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,156 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { api, logger } from "../api";
3
+ import type { Action, McpUiConfig } from "../classes/Action";
4
+ import { ErrorType, TypedError } from "../classes/TypedError";
5
+
6
+ /**
7
+ * Default self-contained HTML shell for an MCP App declared with only `mcp.ui.client`.
8
+ * Provides a `<div id="root">` (the element {@link "@keryxjs/mcp-app"!mountMcpApp} targets
9
+ * by default) and an empty module script the bundled client is inlined into.
10
+ */
11
+ export const DEFAULT_MCP_APP_SHELL = `<!doctype html>
12
+ <html lang="en">
13
+ <head>
14
+ <meta charset="utf-8" />
15
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
16
+ <style>
17
+ :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, sans-serif; }
18
+ body { margin: 0; padding: 16px; }
19
+ </style>
20
+ </head>
21
+ <body>
22
+ <div id="root"></div>
23
+ <script type="module"></script>
24
+ </body>
25
+ </html>
26
+ `;
27
+
28
+ /** Placeholder comment a shell may use to mark where the bundled client is inlined. */
29
+ const COMMENT_PLACEHOLDER = "/* MCP_APP_CLIENT */";
30
+ /** Matches an empty `<script type="module">` tag (the preferred, declarative injection point). */
31
+ const EMPTY_MODULE_SCRIPT = /<script\s+type=["']module["']>\s*<\/script>/;
32
+
33
+ /** Resolved HTML per UI action, computed once at boot by {@link resolveMcpAppUiResources}. */
34
+ const resolvedUiHtml = new Map<Action, string>();
35
+
36
+ /**
37
+ * Bundle a browser entrypoint into a single minified ESM string.
38
+ *
39
+ * Runs `bun build` in a **child process** rather than the in-process `Bun.build` API:
40
+ * once the server has started, Bun has memory-mapped its loaded modules (e.g. zod), and
41
+ * the in-process bundler fails to re-read them ("Unseekable reading file"). A fresh
42
+ * process sidesteps that and is only paid once, at boot.
43
+ *
44
+ * @param client - Path or `file:` URL to the browser entrypoint (`.ts`/`.tsx`/`.js`).
45
+ * @returns The minified, bundled client script.
46
+ * @throws {TypedError} When the bundle fails (message includes the bundler's stderr).
47
+ */
48
+ export async function bundleMcpAppClient(
49
+ client: string | URL,
50
+ ): Promise<string> {
51
+ const entrypoint =
52
+ client instanceof URL
53
+ ? fileURLToPath(client)
54
+ : client.startsWith("file:")
55
+ ? fileURLToPath(new URL(client))
56
+ : client;
57
+
58
+ const proc = Bun.spawn(
59
+ [
60
+ process.execPath,
61
+ "build",
62
+ entrypoint,
63
+ "--target=browser",
64
+ "--format=esm",
65
+ "--minify",
66
+ ],
67
+ { stdout: "pipe", stderr: "pipe" },
68
+ );
69
+ const [script, stderr, exitCode] = await Promise.all([
70
+ new Response(proc.stdout).text(),
71
+ new Response(proc.stderr).text(),
72
+ proc.exited,
73
+ ]);
74
+
75
+ if (exitCode !== 0 || script.trim().length === 0) {
76
+ throw new TypedError({
77
+ message: `Failed to bundle MCP App client "${entrypoint}":\n${stderr || "no output"}`,
78
+ type: ErrorType.SERVER_INITIALIZATION,
79
+ });
80
+ }
81
+
82
+ return script;
83
+ }
84
+
85
+ /**
86
+ * Inline a bundled client script into an HTML shell. Prefers an empty
87
+ * `<script type="module"></script>`, then a `MCP_APP_CLIENT` placeholder comment,
88
+ * then just before `</body>`, and finally appends as a last resort.
89
+ *
90
+ * Uses replacer functions so `$`-sequences in the bundled JS are inserted literally.
91
+ */
92
+ function injectClientScript(shell: string, script: string): string {
93
+ if (EMPTY_MODULE_SCRIPT.test(shell)) {
94
+ return shell.replace(
95
+ EMPTY_MODULE_SCRIPT,
96
+ () => `<script type="module">${script}</script>`,
97
+ );
98
+ }
99
+ if (shell.includes(COMMENT_PLACEHOLDER)) {
100
+ return shell.replace(COMMENT_PLACEHOLDER, () => script);
101
+ }
102
+ const scriptTag = `<script type="module">${script}</script>`;
103
+ if (shell.includes("</body>")) {
104
+ return shell.replace("</body>", () => `${scriptTag}</body>`);
105
+ }
106
+ return `${shell}${scriptTag}`;
107
+ }
108
+
109
+ /**
110
+ * Compute the served HTML for an MCP App's `mcp.ui` config.
111
+ *
112
+ * - With `client`: bundles it and inlines the result into `html` (or {@link DEFAULT_MCP_APP_SHELL}).
113
+ * - With only `html`: returns it verbatim.
114
+ *
115
+ * @param ui - The action's `mcp.ui` config.
116
+ * @returns The self-contained HTML to serve as the `ui://` resource.
117
+ * @throws {TypedError} When neither `client` nor `html` is set, or bundling fails.
118
+ */
119
+ export async function resolveMcpAppHtml(ui: McpUiConfig): Promise<string> {
120
+ if (ui.client) {
121
+ const script = await bundleMcpAppClient(ui.client);
122
+ return injectClientScript(ui.html ?? DEFAULT_MCP_APP_SHELL, script);
123
+ }
124
+ if (ui.html !== undefined) return ui.html;
125
+ throw new TypedError({
126
+ message: "mcp.ui requires either `client` or `html` to be set",
127
+ type: ErrorType.ACTION_VALIDATION,
128
+ });
129
+ }
130
+
131
+ /**
132
+ * Resolve and cache the HTML for every action declaring `mcp.ui`. Called once at MCP
133
+ * server boot so per-session resource registration reads pre-built HTML (and so a bundle
134
+ * error fails startup fast rather than the first tool call).
135
+ *
136
+ * @throws {TypedError} When any UI action's HTML cannot be resolved (e.g. a bundle error).
137
+ */
138
+ export async function resolveMcpAppUiResources(): Promise<void> {
139
+ resolvedUiHtml.clear();
140
+ let count = 0;
141
+ for (const action of api.actions.actions) {
142
+ const ui = action.mcp?.ui;
143
+ if (!ui) continue;
144
+ resolvedUiHtml.set(action, await resolveMcpAppHtml(ui));
145
+ count++;
146
+ }
147
+ if (count > 0) logger.debug(`Bundled ${count} MCP App UI resource(s)`);
148
+ }
149
+
150
+ /**
151
+ * The pre-resolved HTML for an action's MCP App, or `undefined` if it was not resolved
152
+ * at boot (callers fall back to `action.mcp.ui.html`).
153
+ */
154
+ export function getResolvedMcpAppHtml(action: Action): string | undefined {
155
+ return resolvedUiHtml.get(action);
156
+ }
package/util/mcpServer.ts CHANGED
@@ -22,6 +22,7 @@ import { UIResponse } from "../classes/UIResponse";
22
22
  import { config } from "../config";
23
23
  import pkg from "../package.json";
24
24
  import { appendHeaders } from "../util/http";
25
+ import { getResolvedMcpAppHtml } from "../util/mcpAppBundler";
25
26
  import { toMarkdown } from "../util/toMarkdown";
26
27
 
27
28
  /**
@@ -653,6 +654,10 @@ function registerUiResources(mcpServer: McpServer) {
653
654
  }
654
655
  registered.add(resourceUri);
655
656
 
657
+ // HTML is resolved (client bundled + inlined) once at boot; fall back to a
658
+ // verbatim `html` string for actions registered outside the boot pass.
659
+ const html = getResolvedMcpAppHtml(action) ?? ui.html ?? "";
660
+
656
661
  const uiMeta = buildUiMeta(ui);
657
662
  const hasMeta = Object.keys(uiMeta).length > 0;
658
663
  const metadata: Record<string, unknown> = { mimeType: MCP_APP_MIME_TYPE };
@@ -667,7 +672,7 @@ function registerUiResources(mcpServer: McpServer) {
667
672
  {
668
673
  uri: mcpUri.toString(),
669
674
  mimeType: MCP_APP_MIME_TYPE,
670
- text: ui.html,
675
+ text: html,
671
676
  ...(hasMeta ? { _meta: { ui: uiMeta } } : {}),
672
677
  },
673
678
  ],