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