@enhance-eng/enhance 0.1.22 → 0.1.33

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.
@@ -1,16 +1,585 @@
1
1
  #!/usr/bin/env node
2
- import { X as MCP_AUTH_SCOPE, Y as getMeOutputSchema, d as createCapabilityCatalogAdapter } from "./cli-output-identity.lib-a1wTreJ6.mjs";
3
- import { i as readRemoteMcpEnvironment, n as createHttpRemoteAdapter, t as createMutationKeyAdapter } from "./mutation-key.adapter-B3ugNA3r.mjs";
4
- import { t as createMcpInvocationAdapter } from "./mcp-invocation.adapter-vsj77GBt.mjs";
5
- import { t as createMcpServerAdapter } from "./mcp-server.adapter-Cgp05gfi.mjs";
6
- import os from "node:os";
2
+ import { M as canvasAssetImportInputSchema, N as canvasAssetImportOutputSchema, Ut as foldPrototypeArtifactPath, Xt as MCP_AUTH_SCOPE, Yt as getMeOutputSchema, b as canvasPrototypeIntentSchema, f as createCapabilityCatalogAdapter, jt as CliError, qt as prototypeArtifactPathSchema, x as canvasPrototypeOutputSchema } from "./cli-output-identity.lib-CWNAXho4.mjs";
3
+ import { a as readRemoteMcpEnvironment, c as createPrototypeArtifactAdapter, l as createPublishCanvasPrototypeComposite, n as createHttpRemoteAdapter, t as createMutationKeyAdapter, u as createImportCanvasAssetComposite } from "./mutation-key.adapter-A1d27TVY.mjs";
4
+ import { n as createMcpCanvasProfileAdapter, t as createMcpInvocationAdapter } from "./mcp-invocation.adapter-DHdF8-MP.mjs";
5
+ import { a as createMcpResultAdapter, o as createMcpClientContextAdapter, t as createMcpServerAdapter } from "./mcp-server.adapter-B0Kn0e7m.mjs";
7
6
  import process from "node:process";
7
+ import { z } from "zod";
8
+ import os, { tmpdir } from "node:os";
9
+ import { createWriteStream } from "node:fs";
8
10
  import path from "node:path";
9
- import { createServer } from "node:http";
11
+ import { createHash } from "node:crypto";
12
+ import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
13
+ import { Transform, Writable } from "node:stream";
14
+ import { pipeline } from "node:stream/promises";
15
+ import { createServer, request } from "node:http";
10
16
  import { OAuthError, OAuthErrorCode, createMcpHandler, getOAuthProtectedResourceMetadataUrl, hostHeaderValidationResponse, oauthMetadataResponse, originValidationResponse, requireBearerAuth } from "@modelcontextprotocol/server";
11
17
  import { OAuthMetadataSchema } from "@modelcontextprotocol/core";
12
18
  import { toNodeHandler } from "@modelcontextprotocol/node";
19
+ import { request as request$1 } from "node:https";
20
+ import { lookup } from "node:dns/promises";
21
+ import { BlockList, isIP } from "node:net";
22
+ import { crc32 } from "node:zlib";
23
+ import { open as open$1 } from "yauzl";
13
24
 
25
+ //#region src/infrastructure/mcp-canvas-ui.adapter.ts
26
+ const HTTP_OK$1 = 200;
27
+ const UI_TIMEOUT_MS = 15e3;
28
+ const MIME_TYPE = "text/html;profile=mcp-app";
29
+ const readHtml = async (url) => {
30
+ const signal = AbortSignal.timeout(UI_TIMEOUT_MS);
31
+ const response = await new Promise((resolve, reject) => {
32
+ const request$2 = (url.protocol === "https:" ? request$1 : request)(url, {
33
+ method: "GET",
34
+ agent: false,
35
+ signal,
36
+ headers: {
37
+ accept: "text/html",
38
+ "accept-encoding": "identity"
39
+ }
40
+ }, resolve);
41
+ request$2.on("error", reject);
42
+ request$2.end();
43
+ });
44
+ if (response.statusCode !== HTTP_OK$1 || response.headers["content-type"]?.startsWith("text/html") !== true || response.headers["content-encoding"] !== void 0 && response.headers["content-encoding"] !== "identity") {
45
+ response.destroy();
46
+ throw new Error("The Enhance canvas panel is unavailable. Continue through the canvas tools.");
47
+ }
48
+ const chunks = [];
49
+ await pipeline(response, new Writable({ write: (chunk, _encoding, callback) => {
50
+ chunks.push(chunk);
51
+ callback();
52
+ } }), { signal });
53
+ const html = Buffer.concat(chunks).toString("utf8");
54
+ if (!html.includes("<head>")) throw new Error("The Enhance canvas panel is not valid HTML.");
55
+ return html.replace("<head>", () => `<head><base href="${url.origin}/">`);
56
+ };
57
+ const loadReleaseHtml = (url) => {
58
+ let pending = null;
59
+ return async () => {
60
+ try {
61
+ pending ??= readHtml(url);
62
+ return await pending;
63
+ } catch (error) {
64
+ pending = null;
65
+ throw error;
66
+ }
67
+ };
68
+ };
69
+ const registerLauncher = (server, origin, resourceUri, isReadOnly) => {
70
+ server.registerTool("canvas_open", {
71
+ title: "Open Enhance canvas",
72
+ description: "Open the canvas browser and select existing objects to add to chat. Does not edit a canvas or send a message.",
73
+ inputSchema: z.strictObject({}),
74
+ outputSchema: z.strictObject({
75
+ kind: z.literal("canvas-browser"),
76
+ readOnly: z.boolean()
77
+ }),
78
+ annotations: {
79
+ readOnlyHint: true,
80
+ destructiveHint: false,
81
+ idempotentHint: true,
82
+ openWorldHint: false
83
+ },
84
+ _meta: {
85
+ ui: {
86
+ resourceUri,
87
+ visibility: ["app"]
88
+ },
89
+ "openai/ui": { entrypoints: [{ type: "thread" }] }
90
+ }
91
+ }, () => ({
92
+ structuredContent: {
93
+ kind: "canvas-browser",
94
+ readOnly: isReadOnly
95
+ },
96
+ content: [{
97
+ type: "text",
98
+ text: "Select a canvas to inspect and add its objects to chat."
99
+ }],
100
+ _meta: { enhanceCanvas: { appOrigin: origin } }
101
+ }));
102
+ };
103
+ const createMcpCanvasUiAdapter = (resourceUrl) => {
104
+ const url = new URL(resourceUrl);
105
+ if (!["https:", "http:"].includes(url.protocol) || url.protocol === "http:" && ![
106
+ "localhost",
107
+ "127.0.0.1",
108
+ "[::1]"
109
+ ].includes(url.hostname) || url.username !== "" || url.password !== "" || url.hash !== "" || url.search !== "") throw new Error("The canvas panel must use a trusted HTTPS release URL.");
110
+ const load = loadReleaseHtml(url);
111
+ const resourceUri = `ui://enhance/canvas/${encodeURIComponent(url.href)}`;
112
+ return {
113
+ toolMeta: { ui: { resourceUri } },
114
+ resultMeta: { enhanceCanvas: { appOrigin: url.origin } },
115
+ register: (server, isReadOnly) => {
116
+ server.registerResource("canvas-panel", resourceUri, { mimeType: MIME_TYPE }, async () => ({ contents: [{
117
+ uri: resourceUri,
118
+ mimeType: MIME_TYPE,
119
+ text: await load(),
120
+ _meta: {
121
+ ui: {
122
+ csp: {
123
+ connectDomains: [],
124
+ resourceDomains: [url.origin]
125
+ },
126
+ prefersBorder: true
127
+ },
128
+ "openai/ui": {
129
+ preferredDisplayMode: "inline",
130
+ availableDisplayModes: ["inline", "fullscreen"]
131
+ }
132
+ }
133
+ }] }));
134
+ registerLauncher(server, url.origin, resourceUri, isReadOnly);
135
+ }
136
+ };
137
+ };
138
+
139
+ //#endregion
140
+ //#region src/infrastructure/mcp-file-download.adapter.ts
141
+ const TIMEOUT_MS = 3e4;
142
+ const IPV4 = 4;
143
+ const IPV6 = 6;
144
+ const HTTP_OK = 200;
145
+ const createAddressPolicy = () => {
146
+ const blocked = new BlockList();
147
+ const publicV6 = new BlockList();
148
+ const add = (list, kind, networks) => {
149
+ for (const network of networks) {
150
+ const [address, prefix] = network.split("/", 2);
151
+ if (address === void 0 || prefix === void 0) throw new Error("Invalid network policy");
152
+ list.addSubnet(address, Number(prefix), kind);
153
+ }
154
+ };
155
+ add(blocked, "ipv4", [
156
+ "0.0.0.0/8",
157
+ "10.0.0.0/8",
158
+ "100.64.0.0/10",
159
+ "127.0.0.0/8",
160
+ "169.254.0.0/16",
161
+ "172.16.0.0/12",
162
+ "192.0.0.0/24",
163
+ "192.0.2.0/24",
164
+ "192.88.99.0/24",
165
+ "192.168.0.0/16",
166
+ "198.18.0.0/15",
167
+ "198.51.100.0/24",
168
+ "203.0.113.0/24",
169
+ "224.0.0.0/4",
170
+ "240.0.0.0/4"
171
+ ]);
172
+ add(blocked, "ipv6", [
173
+ "2001::/23",
174
+ "2001:db8::/32",
175
+ "2002::/16"
176
+ ]);
177
+ add(publicV6, "ipv6", ["2000::/3"]);
178
+ return (address, family) => family === IPV4 ? !blocked.check(address, "ipv4") : family === IPV6 && publicV6.check(address, "ipv6") && !blocked.check(address, "ipv6");
179
+ };
180
+ const unavailable = () => new CliError("BAD_REQUEST", "The selected host file could not be acquired.", "Select or upload the file again to obtain a fresh authorized HTTPS download reference. The connection must allow its exact file origin. No canvas change was made.");
181
+ const lookupFor = (isPublicAddress) => (hostname, options, callback) => {
182
+ lookup(hostname, {
183
+ all: true,
184
+ verbatim: true
185
+ }).then((addresses) => {
186
+ const selected = addresses[0];
187
+ if (selected === void 0 || addresses.some((entry) => !isPublicAddress(entry.address, entry.family))) callback(unavailable(), "", IPV4);
188
+ else if (options.all === true) callback(null, [selected]);
189
+ else callback(null, selected.address, selected.family);
190
+ }).catch(() => {
191
+ callback(unavailable(), "", IPV4);
192
+ });
193
+ };
194
+ const receive = async (url, outputPath, maxBytes, isPublicAddress) => {
195
+ const signal = AbortSignal.timeout(TIMEOUT_MS);
196
+ const response = await new Promise((resolve, reject) => {
197
+ const download = request$1(url, {
198
+ method: "GET",
199
+ agent: false,
200
+ signal,
201
+ headers: {
202
+ accept: "application/octet-stream",
203
+ "accept-encoding": "identity"
204
+ },
205
+ lookup: lookupFor(isPublicAddress)
206
+ }, resolve);
207
+ download.on("error", reject);
208
+ download.end();
209
+ });
210
+ const contentLength = response.headers["content-length"];
211
+ const encoding = response.headers["content-encoding"];
212
+ if (response.statusCode !== HTTP_OK || encoding !== void 0 && encoding !== "identity" || contentLength !== void 0 && (!/^\d+$/u.test(contentLength) || Number(contentLength) > maxBytes)) {
213
+ response.destroy();
214
+ throw unavailable();
215
+ }
216
+ let bytes = 0;
217
+ await pipeline(response, new Transform({ transform: (chunk, _encoding, callback) => {
218
+ bytes += chunk.byteLength;
219
+ callback(bytes > maxBytes ? unavailable() : null, chunk);
220
+ } }), createWriteStream(outputPath, {
221
+ flags: "wx",
222
+ mode: 384
223
+ }), { signal });
224
+ if (bytes === 0 || contentLength !== void 0 && bytes !== Number(contentLength)) throw unavailable();
225
+ return bytes;
226
+ };
227
+ const createMcpFileDownloadAdapter = (allowedOrigins) => {
228
+ const isPublicAddress = createAddressPolicy();
229
+ const origins = new Set(allowedOrigins.map((origin) => {
230
+ const url = new URL(origin);
231
+ if (url.hostname.includes("*") || url.protocol !== "https:" || url.origin !== origin || url.username !== "" || url.password !== "") throw new Error("Hosted file origins must be exact HTTPS origins.");
232
+ return origin;
233
+ }));
234
+ return { download: async (file, maxBytes = Infinity) => {
235
+ const url = new URL(file.download_url);
236
+ if (isIP(url.hostname.replaceAll(/^\[|\]$/gu, "")) !== 0 || url.protocol !== "https:" || !origins.has(url.origin) || url.username !== "" || url.password !== "" || url.hash !== "") throw unavailable();
237
+ const directory = await mkdtemp(path.join(tmpdir(), "enhance-host-file-"));
238
+ try {
239
+ const outputPath = path.join(directory, "input");
240
+ return {
241
+ path: outputPath,
242
+ bytes: await receive(url, outputPath, maxBytes, isPublicAddress),
243
+ dispose: async () => rm(directory, {
244
+ recursive: true,
245
+ force: true
246
+ })
247
+ };
248
+ } catch {
249
+ await rm(directory, {
250
+ recursive: true,
251
+ force: true
252
+ });
253
+ throw unavailable();
254
+ }
255
+ } };
256
+ };
257
+
258
+ //#endregion
259
+ //#region src/infrastructure/mcp-hosted-capabilities.adapter.ts
260
+ const createMcpHostedCapabilitiesAdapter = (offered, invocation) => {
261
+ const catalog = offered.filter((capability) => capability.policy.requiresLocalFiles !== true);
262
+ return {
263
+ catalog,
264
+ invocation: { invoke: async (request) => {
265
+ const capability = catalog.find((candidate) => candidate.id === request.capability.id);
266
+ if (capability === void 0) throw new CliError("FORBIDDEN", "This capability is unavailable through hosted MCP.", "Use a listed tool. Local file imports require the local CLI or MCP connection.");
267
+ const input = capability.inputSchema.parse(request.arguments);
268
+ const outputFields = capability.policy.localOutputFields ?? [];
269
+ for (const field of outputFields) {
270
+ const value = typeof input === "object" && input !== null ? Reflect.get(input, field) : void 0;
271
+ if (value !== null && value !== void 0) throw new CliError("BAD_REQUEST", "Hosted MCP cannot write to a caller-selected server path.", `Set ${field} to null to receive the artifact through the host, or use the local CLI.`);
272
+ }
273
+ return invocation.invoke({
274
+ ...request,
275
+ capability,
276
+ arguments: input
277
+ });
278
+ } }
279
+ };
280
+ };
281
+
282
+ //#endregion
283
+ //#region src/infrastructure/mcp-asset-file.adapter.ts
284
+ const SIGNATURES = [
285
+ {
286
+ hex: "89504e470d0a1a0a",
287
+ contentType: "image/png"
288
+ },
289
+ {
290
+ hex: "ffd8ff",
291
+ contentType: "image/jpeg"
292
+ },
293
+ {
294
+ hex: "474946383761",
295
+ contentType: "image/gif"
296
+ },
297
+ {
298
+ hex: "474946383961",
299
+ contentType: "image/gif"
300
+ },
301
+ {
302
+ hex: "00010000",
303
+ contentType: "font/ttf"
304
+ },
305
+ {
306
+ hex: "4f54544f",
307
+ contentType: "font/otf"
308
+ },
309
+ {
310
+ hex: "774f4646",
311
+ contentType: "font/woff"
312
+ },
313
+ {
314
+ hex: "774f4632",
315
+ contentType: "font/woff2"
316
+ }
317
+ ].map((entry) => ({
318
+ ...entry,
319
+ bytes: Buffer.from(entry.hex, "hex")
320
+ }));
321
+ const FOURCC_BYTES = 4;
322
+ const BRAND_OFFSET = 8;
323
+ const SIGNATURE_BYTES = 12;
324
+ const contentTypeOf = (body) => {
325
+ const match = SIGNATURES.find((entry) => body.subarray(0, entry.bytes.length).equals(entry.bytes));
326
+ if (match !== void 0) return match.contentType;
327
+ const prefix = body.subarray(0, SIGNATURE_BYTES);
328
+ const brand = prefix.subarray(BRAND_OFFSET).toString("ascii");
329
+ if (brand === "WEBP" && prefix.subarray(0, FOURCC_BYTES).toString("ascii") === "RIFF") return "image/webp";
330
+ if (prefix.subarray(FOURCC_BYTES, BRAND_OFFSET).toString("ascii") === "ftyp" && ["avif", "avis"].includes(brand)) return "image/avif";
331
+ throw new CliError("BAD_REQUEST", "The selected host file is not a supported image or font.", "Select PNG, JPEG, GIF, WebP, AVIF, TTF, OTF, WOFF or WOFF2. No resource was reserved.");
332
+ };
333
+ const createMcpAssetFileAdapter = (files, file) => ({ read: async () => {
334
+ const acquired = await files.download(file);
335
+ try {
336
+ const body = await readFile(acquired.path);
337
+ const contentType = contentTypeOf(body);
338
+ return {
339
+ body,
340
+ contentType,
341
+ bytes: body.byteLength,
342
+ sha256: createHash("sha256").update(body).digest("hex"),
343
+ kind: contentType.startsWith("image/") ? "image" : "font"
344
+ };
345
+ } finally {
346
+ await acquired.dispose();
347
+ }
348
+ } });
349
+
350
+ //#endregion
351
+ //#region src/infrastructure/mcp-file.schema.ts
352
+ const URL_LIMIT = 16384;
353
+ const ID_LIMIT = 512;
354
+ const MIME_LIMIT = 255;
355
+ const NAME_LIMIT = 1024;
356
+ const mcpFileSchema = z.strictObject({
357
+ download_url: z.url().max(URL_LIMIT),
358
+ file_id: z.string().min(1).max(ID_LIMIT),
359
+ mime_type: z.string().min(1).max(MIME_LIMIT).optional(),
360
+ file_name: z.string().min(1).max(NAME_LIMIT).optional()
361
+ });
362
+
363
+ //#endregion
364
+ //#region src/infrastructure/hosted-prototype-zip.adapter.ts
365
+ const ATTRIBUTE_BITS = 16;
366
+ const TYPE_MASK = 61440;
367
+ const DIRECTORY_TYPE = 16384;
368
+ const FILE_TYPE = 32768;
369
+ const BYTE_BITS = 8;
370
+ const DEFLATE = 8;
371
+ const UNIX_HOST = 3;
372
+ const invalidArchive = () => new CliError("BAD_REQUEST", "The uploaded ZIP is not a supported static build.", "Upload a ZIP containing regular build files and the selected HTML entry. Remove links, encrypted entries, reserved paths, path collisions, and oversized files. No deployment was reserved.");
373
+ const openArchive = async (archivePath) => new Promise((resolve, reject) => {
374
+ open$1(archivePath, {
375
+ lazyEntries: true,
376
+ autoClose: false,
377
+ decodeStrings: true,
378
+ validateEntrySizes: true,
379
+ strictFileNames: true
380
+ }, (error, zip) => {
381
+ if (error === null) resolve(zip);
382
+ else reject(error);
383
+ });
384
+ });
385
+ const streamOf = async (zip, entry) => new Promise((resolve, reject) => {
386
+ zip.openReadStream(entry, (error, stream) => {
387
+ if (error === null) resolve(stream);
388
+ else reject(error);
389
+ });
390
+ });
391
+ const hasAmbiguousParentPath = (prefixes, name) => {
392
+ const parts = name.split("/");
393
+ for (let length = 1; length <= parts.length; length += 1) {
394
+ const prefix = parts.slice(0, length).join("/");
395
+ const folded = foldPrototypeArtifactPath(prefix);
396
+ const previous = prefixes.get(folded);
397
+ if (previous !== void 0 && previous !== prefix) return true;
398
+ prefixes.set(folded, prefix);
399
+ }
400
+ return false;
401
+ };
402
+ const filesOf = async (zip, limits) => new Promise((resolve, reject) => {
403
+ const entries = [];
404
+ const paths = /* @__PURE__ */ new Set();
405
+ const prefixes = /* @__PURE__ */ new Map();
406
+ let bytes = 0;
407
+ zip.on("error", reject);
408
+ zip.on("end", () => {
409
+ resolve(entries);
410
+ });
411
+ zip.on("entry", (entry) => {
412
+ const isDirectory = entry.fileName.endsWith("/");
413
+ const name = isDirectory ? entry.fileName.slice(0, -1) : entry.fileName;
414
+ const unixType = entry.externalFileAttributes >>> ATTRIBUTE_BITS & TYPE_MASK;
415
+ const expectedType = isDirectory ? DIRECTORY_TYPE : FILE_TYPE;
416
+ bytes += entry.uncompressedSize;
417
+ const folded = foldPrototypeArtifactPath(name);
418
+ if (!isDirectory && limits.fileCount !== void 0 && entries.length >= limits.fileCount || !prototypeArtifactPathSchema.safeParse(name).success || Buffer.byteLength(name) > limits.pathBytes || paths.has(folded) || hasAmbiguousParentPath(prefixes, name) || (entry.generalPurposeBitFlag & 1) !== 0 || ![0, DEFLATE].includes(entry.compressionMethod) || unixType !== 0 && unixType !== expectedType && entry.versionMadeBy >>> BYTE_BITS === UNIX_HOST || isDirectory && entry.uncompressedSize !== 0 || entry.uncompressedSize > limits.fileBytes || limits.expandedBytes !== void 0 && bytes > limits.expandedBytes) {
419
+ reject(invalidArchive());
420
+ return;
421
+ }
422
+ paths.add(folded);
423
+ if (!isDirectory) entries.push(entry);
424
+ zip.readEntry();
425
+ });
426
+ zip.readEntry();
427
+ });
428
+ const extract = async (input) => {
429
+ let zip = null;
430
+ try {
431
+ zip = await openArchive(input.archivePath);
432
+ const entries = await filesOf(zip, input.limits);
433
+ for (const entry of entries) {
434
+ const destination = path.join(input.directory, entry.fileName);
435
+ await mkdir(path.dirname(destination), { recursive: true });
436
+ let bytes = 0;
437
+ let checksum = 0;
438
+ const budget = new Transform({ transform: (chunk, _encoding, callback) => {
439
+ bytes += chunk.byteLength;
440
+ checksum = crc32(chunk, checksum);
441
+ callback(bytes > entry.uncompressedSize ? invalidArchive() : null, chunk);
442
+ } });
443
+ await pipeline(await streamOf(zip, entry), budget, createWriteStream(destination, {
444
+ flags: "wx",
445
+ mode: 384
446
+ }));
447
+ if (bytes !== entry.uncompressedSize || checksum !== entry.crc32) throw invalidArchive();
448
+ }
449
+ } catch {
450
+ throw invalidArchive();
451
+ } finally {
452
+ zip?.close();
453
+ }
454
+ };
455
+ const createHostedPrototypeZipAdapter = () => ({ extract });
456
+
457
+ //#endregion
458
+ //#region src/infrastructure/mcp-prototype-artifact.adapter.ts
459
+ const createMcpPrototypeArtifactAdapter = (files, file) => ({ package: async (input) => {
460
+ if (file === void 0) throw new CliError("BAD_REQUEST", "A build file is required.", "Select the ZIP to publish.");
461
+ const limits = input.limits;
462
+ const acquired = await files.download(file, limits.artifactBytes);
463
+ let directory = null;
464
+ try {
465
+ directory = await mkdtemp(path.join(tmpdir(), "enhance-host-build-"));
466
+ await createHostedPrototypeZipAdapter().extract({
467
+ archivePath: acquired.path,
468
+ directory,
469
+ limits
470
+ });
471
+ return await createPrototypeArtifactAdapter(directory).package({
472
+ ...input,
473
+ limits
474
+ });
475
+ } finally {
476
+ if (directory !== null) await rm(directory, {
477
+ recursive: true,
478
+ force: true
479
+ });
480
+ await acquired.dispose();
481
+ }
482
+ } });
483
+
484
+ //#endregion
485
+ //#region src/infrastructure/mcp-hosted-files.adapter.ts
486
+ const clientContext$1 = createMcpClientContextAdapter();
487
+ const assetInputSchema = canvasAssetImportInputSchema.omit({ source: true }).extend({ file: mcpFileSchema });
488
+ const prototypeInputSchema = canvasPrototypeIntentSchema.extend({ file: mcpFileSchema.optional() });
489
+ const transfer = async (action) => {
490
+ const result = createMcpResultAdapter("Select the same host file with a fresh download URL and reuse the original clientToken after uncertainty.");
491
+ try {
492
+ return await action();
493
+ } catch (error) {
494
+ return result.failure(error);
495
+ }
496
+ };
497
+ const registerAsset = (server, input) => {
498
+ server.registerTool("asset_import", {
499
+ title: "Import a canvas asset",
500
+ description: "Import one file explicitly uploaded or selected in this host. Supply its authorized file reference, never a local path or an arbitrary URL. Accepts PNG, JPEG, GIF, WebP, AVIF, TTF, OTF, WOFF or WOFF2; verifies actual bytes and native metadata. Returns a durable resource without placing it or changing the canvas version. Retry with the same bytes and clientToken; a refreshed download URL is allowed.",
501
+ inputSchema: assetInputSchema,
502
+ outputSchema: canvasAssetImportOutputSchema,
503
+ annotations: {
504
+ readOnlyHint: false,
505
+ destructiveHint: false,
506
+ idempotentHint: true,
507
+ openWorldHint: false
508
+ },
509
+ _meta: { "openai/fileParams": ["file"] }
510
+ }, async (args, context) => clientContext$1.run(context, async () => transfer(async () => {
511
+ const result = canvasAssetImportOutputSchema.parse(await createImportCanvasAssetComposite(input.remoteFor(args.clientToken), createMcpAssetFileAdapter(input.files, args.file)).execute(args));
512
+ return createMcpResultAdapter("Reconnect Enhance and retry the same intent.").structured(result);
513
+ })));
514
+ };
515
+ const registerPrototype = (server, input) => {
516
+ server.registerTool("prototype_publish", {
517
+ title: "Publish a prototype to the canvas",
518
+ description: "Publish an uploaded static build ZIP or resume an existing deployment. For source.kind=build supply file and build metadata; use a ZIP with the chosen HTML entry at its stated path. Runnable builds can execute scripts and contact external services when opened. Preserve the complete canvas reference and baseVersion. Reports ingestion separately from attachment. Retry identical build bytes and clientToken; a fresh download URL is allowed. After attachment conflict, reuse the ready deployment with a new token and deliberate revised baseVersion. Status reads never attach.",
519
+ inputSchema: prototypeInputSchema,
520
+ outputSchema: canvasPrototypeOutputSchema,
521
+ annotations: {
522
+ readOnlyHint: false,
523
+ destructiveHint: true,
524
+ idempotentHint: true,
525
+ openWorldHint: true
526
+ },
527
+ _meta: { "openai/fileParams": ["file"] }
528
+ }, async ({ file, ...args }, context) => clientContext$1.run(context, async () => transfer(async () => {
529
+ if (args.source.kind === "build" !== (file !== void 0)) throw new CliError("BAD_REQUEST", "Supply a file only when publishing a new build.", "For a new build select its ZIP. To resume an existing deployment, omit file.");
530
+ const result = canvasPrototypeOutputSchema.parse(await createPublishCanvasPrototypeComposite(input.remoteFor(args.clientToken), createMcpPrototypeArtifactAdapter(input.files, file)).execute(args));
531
+ return createMcpResultAdapter("Reconnect Enhance and retry the same intent.").structured(result);
532
+ })));
533
+ };
534
+ const createMcpHostedFilesAdapter = (input) => ({ register: (server) => {
535
+ registerAsset(server, input);
536
+ registerPrototype(server, input);
537
+ } });
538
+
539
+ //#endregion
540
+ //#region src/infrastructure/mcp-http-profile.adapter.ts
541
+ const clientContext = createMcpClientContextAdapter();
542
+ const createMcpHttpProfileAdapter = (config, catalog, credentialFor, profile) => {
543
+ const files = config.fileOrigins !== void 0 && config.fileOrigins.length > 0 ? createMcpFileDownloadAdapter(config.fileOrigins) : void 0;
544
+ const ui = config.uiUrl === void 0 ? void 0 : createMcpCanvasUiAdapter(config.uiUrl);
545
+ return createMcpHandler(({ authInfo }) => {
546
+ if (authInfo === void 0) throw new Error("authenticated MCP request held no identity");
547
+ const credentials = credentialFor(authInfo.token);
548
+ const hosted = createMcpHostedCapabilitiesAdapter(catalog, createMcpInvocationAdapter(config.apiUrl, credentials, config.configDirectory, {
549
+ version: config.version,
550
+ connectionPath: "hosted_mcp"
551
+ }));
552
+ return profile.kind === "canvas" ? createMcpCanvasProfileAdapter({
553
+ version: config.version,
554
+ ...hosted,
555
+ delivery: "embedded",
556
+ authentication: "oauth",
557
+ ...ui !== void 0 && { ui },
558
+ ...files !== void 0 && { hostedFiles: createMcpHostedFilesAdapter({
559
+ files,
560
+ remoteFor: (clientToken) => {
561
+ const mutationKey = createMutationKeyAdapter();
562
+ mutationKey.select(clientToken, true);
563
+ return createHttpRemoteAdapter(config.apiUrl, credentials, mutationKey, {
564
+ ...clientContext.current(),
565
+ path: "hosted_mcp"
566
+ });
567
+ }
568
+ }) },
569
+ readOnly: profile.readOnly
570
+ }) : createMcpServerAdapter({
571
+ version: config.version,
572
+ ...hosted,
573
+ delivery: "embedded"
574
+ });
575
+ }, {
576
+ legacy: "stateless",
577
+ responseMode: "auto",
578
+ onerror: config.onerror
579
+ });
580
+ };
581
+
582
+ //#endregion
14
583
  //#region src/infrastructure/remote-mcp-http.adapter.ts
15
584
  const SECOND_MS = 1e3;
16
585
  const BAD_REQUEST = 400;
@@ -28,7 +597,7 @@ const metadataFrom = async (config) => {
28
597
  };
29
598
  const authVerifier = (config) => ({ verifyAccessToken: async (token) => {
30
599
  try {
31
- const remote = createHttpRemoteAdapter(config.apiUrl, credentialFor(token, config.configDirectory), createMutationKeyAdapter());
600
+ const remote = createHttpRemoteAdapter(config.apiUrl, credentialFor(token, config.configDirectory), createMutationKeyAdapter(), { path: "hosted_mcp" });
32
601
  const me = getMeOutputSchema.parse(await remote.queryWithToken("person.me", {}, token));
33
602
  if (me.authentication.kind !== "oauth-agent" || me.authentication.resource !== config.resourceUrl) throw new OAuthError(OAuthErrorCode.InvalidToken, "token is not valid for Enhance MCP");
34
603
  return {
@@ -52,7 +621,7 @@ const healthResponse = () => Response.json({
52
621
  service: "enhance-mcp"
53
622
  }, { status: 200 });
54
623
  const notFoundResponse = () => Response.json({ error: "Not Found" }, { status: 404 });
55
- const securedHandler = (config, resourceUrl, oauthMetadata, handler) => {
624
+ const securedHandler = (config, resourceUrl, oauthMetadata, handlers) => {
56
625
  const authenticate = requireBearerAuth({
57
626
  verifier: authVerifier(config),
58
627
  requiredScopes: [MCP_AUTH_SCOPE],
@@ -70,9 +639,15 @@ const securedHandler = (config, resourceUrl, oauthMetadata, handler) => {
70
639
  if (url.pathname === "/health") return healthResponse();
71
640
  const hostRejection = hostHeaderValidationResponse(request, [...config.allowedHosts]);
72
641
  if (hostRejection !== void 0) return hostRejection;
73
- const metadata = oauthMetadataResponse(request, metadataOptions);
642
+ let metadataRequest = request;
643
+ for (const endpoint of handlers.keys()) {
644
+ const metadataUrl = getOAuthProtectedResourceMetadataUrl(new URL(endpoint, resourceUrl));
645
+ if (url.pathname === new URL(metadataUrl).pathname) metadataRequest = new Request(getOAuthProtectedResourceMetadataUrl(resourceUrl), request);
646
+ }
647
+ const metadata = oauthMetadataResponse(metadataRequest, metadataOptions);
74
648
  if (metadata !== void 0) return metadata;
75
- if (url.pathname !== resourceUrl.pathname) return notFoundResponse();
649
+ const handler = handlers.get(url.pathname);
650
+ if (handler === void 0) return notFoundResponse();
76
651
  const originRejection = originValidationResponse(request, [...config.allowedOrigins]);
77
652
  if (originRejection !== void 0) return originRejection;
78
653
  const auth = await authenticate(request);
@@ -98,25 +673,27 @@ const close = async (server) => new Promise((resolve, reject) => {
98
673
  });
99
674
  });
100
675
  const hasRequestTarget = (request) => request.method !== void 0 && request.url !== void 0;
101
- const createRemoteMcpHttpAdapter = async (config) => {
676
+ const resourceFor = (config) => {
677
+ if (config.readOnly === true && config.profile !== "canvas") throw new Error("Read-only MCP requires the canvas profile.");
102
678
  const resourceUrl = new URL(config.resourceUrl);
679
+ const canvasPath = config.canvasProfile?.path;
680
+ const resourcePrefix = resourceUrl.pathname.replace(/\/$/u, "");
681
+ if (canvasPath !== void 0 && (canvasPath === resourceUrl.pathname || !canvasPath.startsWith(`${resourcePrefix}/`) || new URL(canvasPath, resourceUrl).pathname !== canvasPath || canvasPath.includes("?") || canvasPath.includes("#"))) throw new Error("The canvas profile path must be a distinct descendant of the OAuth resource.");
682
+ return resourceUrl;
683
+ };
684
+ const createRemoteMcpHttpAdapter = async (config) => {
685
+ const resourceUrl = resourceFor(config);
103
686
  const catalog = createCapabilityCatalogAdapter();
104
687
  const oauthMetadata = await metadataFrom(config);
105
- const handler = createMcpHandler(({ authInfo }) => {
106
- if (authInfo === void 0) throw new Error("authenticated MCP request held no identity");
107
- const credentials = credentialFor(authInfo.token, config.configDirectory);
108
- return createMcpServerAdapter({
109
- version: config.version,
110
- invocation: createMcpInvocationAdapter(config.apiUrl, credentials, config.configDirectory, config.version),
111
- catalog,
112
- delivery: "embedded"
113
- });
114
- }, {
115
- legacy: "stateless",
116
- responseMode: "auto",
117
- onerror: config.onerror
118
- });
119
- const nodeHandler = toNodeHandler(securedHandler(config, resourceUrl, oauthMetadata, handler), { onerror: config.onerror });
688
+ const handlers = /* @__PURE__ */ new Map([[resourceUrl.pathname, createMcpHttpProfileAdapter(config, catalog, (token) => credentialFor(token, config.configDirectory), {
689
+ kind: config.profile ?? "legacy",
690
+ readOnly: config.readOnly ?? false
691
+ })]]);
692
+ if (config.canvasProfile !== void 0) handlers.set(config.canvasProfile.path, createMcpHttpProfileAdapter(config, catalog, (token) => credentialFor(token, config.configDirectory), {
693
+ kind: "canvas",
694
+ readOnly: config.canvasProfile.readOnly
695
+ }));
696
+ const nodeHandler = toNodeHandler(securedHandler(config, resourceUrl, oauthMetadata, handlers), { onerror: config.onerror });
120
697
  const server = createServer((request, response) => {
121
698
  if (!hasRequestTarget(request)) {
122
699
  response.writeHead(BAD_REQUEST);
@@ -128,7 +705,7 @@ const createRemoteMcpHttpAdapter = async (config) => {
128
705
  return {
129
706
  listen: async (port, host) => listen(server, port, host),
130
707
  close: async () => {
131
- await handler.close();
708
+ for (const handler of handlers.values()) await handler.close();
132
709
  await close(server);
133
710
  }
134
711
  };
@@ -138,14 +715,22 @@ const createRemoteMcpHttpAdapter = async (config) => {
138
715
  //#region src/remote-mcp-main.ts
139
716
  const config = readRemoteMcpEnvironment();
140
717
  const server = await createRemoteMcpHttpAdapter({
718
+ ...config.MCP_CANVAS_PATH !== void 0 && { canvasProfile: {
719
+ path: config.MCP_CANVAS_PATH,
720
+ readOnly: config.MCP_CANVAS_READ_ONLY
721
+ } },
722
+ profile: config.ENHANCE_MCP_PROFILE,
723
+ readOnly: config.ENHANCE_MCP_READ_ONLY,
141
724
  apiUrl: config.ENHANCE_API_URL,
142
725
  issuer: config.MCP_AUTH_ISSUER,
143
726
  resourceUrl: config.MCP_RESOURCE_URL,
144
727
  serviceDocumentationUrl: config.MCP_SERVICE_DOCUMENTATION_URL,
145
728
  configDirectory: path.join(os.tmpdir(), "enhance-remote-mcp"),
729
+ fileOrigins: config.MCP_FILE_ORIGINS.split(",").map((value) => value.trim()).filter(Boolean),
146
730
  allowedHosts: config.MCP_ALLOWED_HOSTS.split(",").map((value) => value.trim()),
147
731
  allowedOrigins: config.MCP_ALLOWED_ORIGINS.split(",").map((value) => value.trim()),
148
- version: "0.1.22",
732
+ version: "0.1.33",
733
+ ...config.MCP_UI_URL !== void 0 && { uiUrl: config.MCP_UI_URL },
149
734
  onerror: (error) => process.stderr.write(`${error.message}\n`)
150
735
  });
151
736
  await server.listen(config.PORT, config.MCP_HOST);