@tempad-dev/mcp 0.6.2 → 0.7.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 +8 -2
- package/README.zh-Hans.md +8 -2
- package/dist/cli.mjs +1 -1
- package/dist/hub.mjs +536 -203
- package/dist/hub.mjs.map +1 -1
- package/dist/{shared-CRF_okNG.mjs → shared-BAyjEPbx.mjs} +3 -3
- package/dist/{shared-CRF_okNG.mjs.map → shared-BAyjEPbx.mjs.map} +1 -1
- package/package.json +2 -2
package/dist/hub.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import { c as SOCK_PATH, d as log, i as HUB_LOCK_UPDATE_MS, l as ensureDir, n as HUB_LOCK_PATH, o as PACKAGE_VERSION, r as HUB_LOCK_STALE_MS, s as RUNTIME_DIR, t as ASSET_DIR, u as ensureFile } from "./shared-
|
|
1
|
+
import { c as SOCK_PATH, d as log, i as HUB_LOCK_UPDATE_MS, l as ensureDir, n as HUB_LOCK_PATH, o as PACKAGE_VERSION, r as HUB_LOCK_STALE_MS, s as RUNTIME_DIR, t as ASSET_DIR, u as ensureFile } from "./shared-BAyjEPbx.mjs";
|
|
2
2
|
import { connect, createServer } from "node:net";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
-
import { URL } from "node:url";
|
|
4
|
+
import { URL as URL$1 } from "node:url";
|
|
5
5
|
import lockfile from "proper-lockfile";
|
|
6
6
|
import { chmodSync, createReadStream, createWriteStream, existsSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
7
7
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
8
8
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
9
9
|
import { z } from "zod";
|
|
10
|
-
import {
|
|
10
|
+
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
11
11
|
import { WebSocketServer } from "ws";
|
|
12
|
-
import {
|
|
12
|
+
import { nanoid } from "nanoid";
|
|
13
13
|
import { createServer as createServer$1 } from "node:http";
|
|
14
14
|
import { Transform, pipeline } from "node:stream";
|
|
15
15
|
//#region ../shared/dist/index.js
|
|
@@ -23,6 +23,7 @@ const MCP_TOOL_INLINE_BUDGET_BYTES = 64 * 1024;
|
|
|
23
23
|
const MCP_TOOL_TIMEOUT_MS = 15e3;
|
|
24
24
|
const MCP_AUTO_ACTIVATE_GRACE_MS = 1500;
|
|
25
25
|
const MCP_MAX_ASSET_BYTES = 8 * 1024 * 1024;
|
|
26
|
+
const MCP_MAX_ASSET_STORE_BYTES = 256 * 1024 * 1024;
|
|
26
27
|
const MCP_ASSET_TTL_MS = 720 * 60 * 60 * 1e3;
|
|
27
28
|
const MCP_HASH_PATTERN = new RegExp(`^[a-f0-9]{8}$`, "i");
|
|
28
29
|
const TEMPAD_MCP_ERROR_CODES = {
|
|
@@ -34,8 +35,18 @@ const TEMPAD_MCP_ERROR_CODES = {
|
|
|
34
35
|
ASSET_SERVER_NOT_CONFIGURED: "ASSET_SERVER_NOT_CONFIGURED",
|
|
35
36
|
TRANSPORT_NOT_CONNECTED: "TRANSPORT_NOT_CONNECTED"
|
|
36
37
|
};
|
|
38
|
+
const TempadMcpErrorPayloadSchema = z.object({
|
|
39
|
+
code: z.enum(TEMPAD_MCP_ERROR_CODES).optional(),
|
|
40
|
+
message: z.string().min(1)
|
|
41
|
+
}).strict();
|
|
42
|
+
const TOOL_RESULT_OUTCOME_ERROR = "Tool results must contain exactly one defined payload or error.";
|
|
43
|
+
function hasToolResultOutcome(result) {
|
|
44
|
+
return result.payload !== void 0 !== (result.error !== void 0);
|
|
45
|
+
}
|
|
46
|
+
const TEMPAD_MCP_BROWSER_SOURCE = "tempad-dev:mcp";
|
|
47
|
+
const MCP_MAX_ASSET_BASE64_LENGTH = 4 * Math.ceil(MCP_MAX_ASSET_BYTES / 3);
|
|
37
48
|
const MessageBaseSchema = z.object({
|
|
38
|
-
source: z.literal(
|
|
49
|
+
source: z.literal(TEMPAD_MCP_BROWSER_SOURCE),
|
|
39
50
|
version: z.literal(1)
|
|
40
51
|
}).strict();
|
|
41
52
|
const PageMessageBaseSchema = MessageBaseSchema.extend({ sessionId: z.string().min(1) }).strict();
|
|
@@ -45,17 +56,13 @@ function messageSchema(base, type, shape) {
|
|
|
45
56
|
...shape
|
|
46
57
|
}).strict();
|
|
47
58
|
}
|
|
48
|
-
const ToolErrorSchema = z.object({
|
|
49
|
-
code: z.enum(TEMPAD_MCP_ERROR_CODES).optional(),
|
|
50
|
-
message: z.string()
|
|
51
|
-
}).strict();
|
|
52
59
|
const AssetMetadataSchema = z.object({
|
|
53
60
|
height: z.number().int().positive().optional(),
|
|
54
61
|
themeable: z.boolean().optional(),
|
|
55
62
|
width: z.number().int().positive().optional()
|
|
56
63
|
}).strict();
|
|
57
64
|
const AssetUploadPayloadSchema = z.object({
|
|
58
|
-
base64: z.string().min(1),
|
|
65
|
+
base64: z.string().min(1).max(MCP_MAX_ASSET_BASE64_LENGTH),
|
|
59
66
|
hash: z.string().regex(MCP_HASH_PATTERN),
|
|
60
67
|
metadata: AssetMetadataSchema.optional(),
|
|
61
68
|
mimeType: z.string().min(1)
|
|
@@ -65,7 +72,7 @@ const PageDisableMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.disab
|
|
|
65
72
|
const PageActivateSessionMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.activateSession", {});
|
|
66
73
|
const PageToolResultMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.toolResult", {
|
|
67
74
|
callId: z.string().min(1),
|
|
68
|
-
error:
|
|
75
|
+
error: TempadMcpErrorPayloadSchema.optional(),
|
|
69
76
|
payload: z.unknown().optional()
|
|
70
77
|
});
|
|
71
78
|
const PageAssetUploadMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.uploadAsset", {
|
|
@@ -78,7 +85,9 @@ z.discriminatedUnion("type", [
|
|
|
78
85
|
PageActivateSessionMessageSchema,
|
|
79
86
|
PageToolResultMessageSchema,
|
|
80
87
|
PageAssetUploadMessageSchema
|
|
81
|
-
])
|
|
88
|
+
]).refine((message) => {
|
|
89
|
+
return message.type !== "mcp.toolResult" || hasToolResultOutcome(message);
|
|
90
|
+
}, { message: TOOL_RESULT_OUTCOME_ERROR });
|
|
82
91
|
const McpBrowserStateStatusSchema = z.enum([
|
|
83
92
|
"disabled",
|
|
84
93
|
"connecting",
|
|
@@ -101,7 +110,7 @@ const BridgeToolCallMessageSchema = messageSchema(MessageBaseSchema, "mcp.toolCa
|
|
|
101
110
|
}).strict()
|
|
102
111
|
});
|
|
103
112
|
const BridgeAssetUploadResultMessageSchema = messageSchema(MessageBaseSchema, "mcp.assetUploadResult", {
|
|
104
|
-
error:
|
|
113
|
+
error: TempadMcpErrorPayloadSchema.optional(),
|
|
105
114
|
requestId: z.string().min(1),
|
|
106
115
|
sessionId: z.string().min(1)
|
|
107
116
|
});
|
|
@@ -202,7 +211,7 @@ const MCP_CLIENTS_BY_ID = {
|
|
|
202
211
|
MCP_CLIENTS_BY_ID.vscode, MCP_CLIENTS_BY_ID.cursor, MCP_CLIENTS_BY_ID.claude, MCP_CLIENTS_BY_ID.codex, MCP_CLIENTS_BY_ID.trae;
|
|
203
212
|
const RegisteredMessageSchema = z.object({
|
|
204
213
|
type: z.literal("registered"),
|
|
205
|
-
id: z.string()
|
|
214
|
+
id: z.string().min(1)
|
|
206
215
|
}).strict();
|
|
207
216
|
const StateMessageSchema = z.object({
|
|
208
217
|
type: z.literal("state"),
|
|
@@ -215,7 +224,7 @@ const ToolCallPayloadSchema = z.object({
|
|
|
215
224
|
}).strict();
|
|
216
225
|
const ToolCallMessageSchema = z.object({
|
|
217
226
|
type: z.literal("toolCall"),
|
|
218
|
-
id: z.string(),
|
|
227
|
+
id: z.string().min(1),
|
|
219
228
|
payload: ToolCallPayloadSchema
|
|
220
229
|
}).strict();
|
|
221
230
|
z.discriminatedUnion("type", [
|
|
@@ -226,12 +235,12 @@ z.discriminatedUnion("type", [
|
|
|
226
235
|
const ActivateMessageSchema = z.object({ type: z.literal("activate") }).strict();
|
|
227
236
|
const ToolResultMessageSchema = z.object({
|
|
228
237
|
type: z.literal("toolResult"),
|
|
229
|
-
id: z.string(),
|
|
238
|
+
id: z.string().min(1),
|
|
230
239
|
payload: z.unknown().optional(),
|
|
231
|
-
error:
|
|
232
|
-
}).strict();
|
|
240
|
+
error: TempadMcpErrorPayloadSchema.optional()
|
|
241
|
+
}).strict().refine(hasToolResultOutcome, { message: TOOL_RESULT_OUTCOME_ERROR });
|
|
233
242
|
const PingMessageSchema = z.object({ type: z.literal("ping") }).strict();
|
|
234
|
-
const MessageFromExtensionSchema = z.
|
|
243
|
+
const MessageFromExtensionSchema = z.union([
|
|
235
244
|
ActivateMessageSchema,
|
|
236
245
|
ToolResultMessageSchema,
|
|
237
246
|
PingMessageSchema
|
|
@@ -309,7 +318,7 @@ function describeScreenshot(result) {
|
|
|
309
318
|
return `Screenshot ${result.width}x${result.height} @${result.scale}x (${formatBytes(result.bytes)})`;
|
|
310
319
|
}
|
|
311
320
|
const AssetDescriptorSchema = z.object({
|
|
312
|
-
hash: z.string().
|
|
321
|
+
hash: z.string().regex(MCP_HASH_PATTERN),
|
|
313
322
|
url: z.string().url(),
|
|
314
323
|
mimeType: z.string().min(1),
|
|
315
324
|
size: z.number().int().nonnegative(),
|
|
@@ -335,7 +344,7 @@ const GetStructureParametersSchema = z.object({
|
|
|
335
344
|
const GetAssetsParametersSchema = z.object({ hashes: z.array(z.string().regex(MCP_HASH_PATTERN)).min(1).describe("Asset hashes returned from get_code (or other tools) to download/resolve exact bytes for rasterized images or SVGs before routing through your asset pipeline.") });
|
|
336
345
|
const GetAssetsResultSchema = z.object({
|
|
337
346
|
assets: z.array(AssetDescriptorSchema),
|
|
338
|
-
missing: z.array(z.string().
|
|
347
|
+
missing: z.array(z.string().regex(MCP_HASH_PATTERN))
|
|
339
348
|
});
|
|
340
349
|
//#endregion
|
|
341
350
|
//#region src/asset-utils.ts
|
|
@@ -388,6 +397,15 @@ function resolveMaxAssetSizeBytes() {
|
|
|
388
397
|
function resolveAssetTtlMs() {
|
|
389
398
|
return parseNonNegativeInt(process.env.TEMPAD_MCP_ASSET_TTL_MS, MCP_ASSET_TTL_MS);
|
|
390
399
|
}
|
|
400
|
+
function resolveMaxAssetStoreBytes() {
|
|
401
|
+
return parsePositiveInt(process.env.TEMPAD_MCP_MAX_ASSET_STORE_BYTES, MCP_MAX_ASSET_STORE_BYTES);
|
|
402
|
+
}
|
|
403
|
+
function resolveMaxConcurrentAssetUploads() {
|
|
404
|
+
return parsePositiveInt(process.env.TEMPAD_MCP_MAX_CONCURRENT_ASSET_UPLOADS, 4);
|
|
405
|
+
}
|
|
406
|
+
function resolveMaxExtensionConnections() {
|
|
407
|
+
return parsePositiveInt(process.env.TEMPAD_MCP_MAX_EXTENSION_CONNECTIONS, 16);
|
|
408
|
+
}
|
|
391
409
|
function getMcpServerConfig() {
|
|
392
410
|
return {
|
|
393
411
|
wsPortCandidates: [...MCP_PORT_CANDIDATES],
|
|
@@ -395,17 +413,81 @@ function getMcpServerConfig() {
|
|
|
395
413
|
maxPayloadBytes: MCP_MAX_PAYLOAD_BYTES,
|
|
396
414
|
autoActivateGraceMs: resolveAutoActivateGraceMs(),
|
|
397
415
|
maxAssetSizeBytes: resolveMaxAssetSizeBytes(),
|
|
416
|
+
maxAssetStoreBytes: resolveMaxAssetStoreBytes(),
|
|
417
|
+
maxConcurrentAssetUploads: resolveMaxConcurrentAssetUploads(),
|
|
418
|
+
maxExtensionConnections: resolveMaxExtensionConnections(),
|
|
419
|
+
allowedExtensionOrigins: process.env.TEMPAD_MCP_ALLOWED_EXTENSION_ORIGINS,
|
|
398
420
|
assetTtlMs: resolveAssetTtlMs()
|
|
399
421
|
};
|
|
400
422
|
}
|
|
401
423
|
//#endregion
|
|
424
|
+
//#region src/security.ts
|
|
425
|
+
const CHROME_EXTENSION_ORIGIN_PATTERN = /^chrome-extension:\/\/[a-p]{32}$/;
|
|
426
|
+
function createCapabilityToken() {
|
|
427
|
+
return randomBytes(32).toString("base64url");
|
|
428
|
+
}
|
|
429
|
+
function createExtensionOriginPolicy(value) {
|
|
430
|
+
const configuredOrigins = (value ?? "").split(",").map((origin) => origin.trim().toLowerCase()).filter(Boolean);
|
|
431
|
+
const invalidOrigin = configuredOrigins.find((origin) => !isChromeExtensionOrigin(origin));
|
|
432
|
+
if (invalidOrigin) throw new Error(`Invalid allowed extension Origin: ${invalidOrigin}`);
|
|
433
|
+
const exactOrigins = new Set(configuredOrigins);
|
|
434
|
+
return {
|
|
435
|
+
exactOrigins,
|
|
436
|
+
mode: exactOrigins.size ? "exact" : "any-extension"
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
function isAllowedExtensionOrigin(origin, policy) {
|
|
440
|
+
if (!origin) return false;
|
|
441
|
+
const normalized = origin.toLowerCase();
|
|
442
|
+
if (!isChromeExtensionOrigin(normalized)) return false;
|
|
443
|
+
return policy.mode === "any-extension" || policy.exactOrigins.has(normalized);
|
|
444
|
+
}
|
|
445
|
+
function isAllowedWebSocketRequest(origin, requestUrl, policy) {
|
|
446
|
+
if (!isAllowedExtensionOrigin(origin, policy)) return false;
|
|
447
|
+
if (!requestUrl) return false;
|
|
448
|
+
try {
|
|
449
|
+
const baseUrl = "ws://127.0.0.1";
|
|
450
|
+
const url = new URL(requestUrl, baseUrl);
|
|
451
|
+
return url.origin === baseUrl && url.pathname === "/" && url.search === "";
|
|
452
|
+
} catch {
|
|
453
|
+
return false;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
function secretsEqual(candidate, expected) {
|
|
457
|
+
const candidateBuffer = Buffer.from(candidate);
|
|
458
|
+
const expectedBuffer = Buffer.from(expected);
|
|
459
|
+
return candidateBuffer.length === expectedBuffer.length && timingSafeEqual(candidateBuffer, expectedBuffer);
|
|
460
|
+
}
|
|
461
|
+
function isChromeExtensionOrigin(origin) {
|
|
462
|
+
return CHROME_EXTENSION_ORIGIN_PATTERN.test(origin);
|
|
463
|
+
}
|
|
464
|
+
//#endregion
|
|
402
465
|
//#region src/asset-http-server.ts
|
|
403
466
|
const LOOPBACK_HOST = "127.0.0.1";
|
|
404
467
|
const HASH_HEX_PATTERN = new RegExp(`^[a-f0-9]{8}$`, "i");
|
|
405
|
-
const
|
|
406
|
-
|
|
468
|
+
const ASSET_REQUEST_TIMEOUT_MS = 15e3;
|
|
469
|
+
const ASSET_HEADERS_TIMEOUT_MS = 5e3;
|
|
470
|
+
const ASSET_KEEP_ALIVE_TIMEOUT_MS = 5e3;
|
|
471
|
+
const ASSET_MAX_HEADERS = 32;
|
|
472
|
+
const ASSET_MAX_CONNECTIONS = 128;
|
|
473
|
+
const ASSET_MAX_CONCURRENT_DOWNLOADS = 128;
|
|
474
|
+
function createAssetHttpServer(store, options = {}) {
|
|
475
|
+
const config = getMcpServerConfig();
|
|
476
|
+
const accessToken = options.accessToken ?? createCapabilityToken();
|
|
477
|
+
const maxAssetSizeBytes = options.maxAssetSizeBytes ?? config.maxAssetSizeBytes;
|
|
478
|
+
const maxAssetStoreBytes = options.maxAssetStoreBytes ?? config.maxAssetStoreBytes;
|
|
479
|
+
const maxConcurrentUploads = options.maxConcurrentUploads ?? config.maxConcurrentAssetUploads;
|
|
480
|
+
const originPolicy = createExtensionOriginPolicy(config.allowedExtensionOrigins);
|
|
407
481
|
const server = createServer$1(handleRequest);
|
|
482
|
+
server.requestTimeout = ASSET_REQUEST_TIMEOUT_MS;
|
|
483
|
+
server.headersTimeout = ASSET_HEADERS_TIMEOUT_MS;
|
|
484
|
+
server.keepAliveTimeout = ASSET_KEEP_ALIVE_TIMEOUT_MS;
|
|
485
|
+
server.maxHeadersCount = ASSET_MAX_HEADERS;
|
|
486
|
+
server.maxConnections = ASSET_MAX_CONNECTIONS;
|
|
408
487
|
let port = null;
|
|
488
|
+
let activeDownloads = 0;
|
|
489
|
+
let activeUploads = 0;
|
|
490
|
+
let reservedUploadBytes = 0;
|
|
409
491
|
async function start() {
|
|
410
492
|
if (port !== null) return;
|
|
411
493
|
await new Promise((resolve, reject) => {
|
|
@@ -434,36 +516,44 @@ function createAssetHttpServer(store) {
|
|
|
434
516
|
}
|
|
435
517
|
function getBaseUrl() {
|
|
436
518
|
if (port === null) throw new Error("Asset HTTP server is not running.");
|
|
437
|
-
return `http://${LOOPBACK_HOST}:${port}`;
|
|
519
|
+
return `http://${LOOPBACK_HOST}:${port}/${accessToken}`;
|
|
438
520
|
}
|
|
439
521
|
function handleRequest(req, res) {
|
|
440
522
|
const startedAt = Date.now();
|
|
441
523
|
res.on("finish", () => {
|
|
442
524
|
log.info({
|
|
443
525
|
method: req.method,
|
|
444
|
-
|
|
526
|
+
route: redactAssetRequestUrl(req.url),
|
|
445
527
|
status: res.statusCode,
|
|
446
528
|
durationMs: Date.now() - startedAt
|
|
447
529
|
}, "HTTP asset request completed.");
|
|
448
530
|
});
|
|
449
|
-
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
450
|
-
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
451
|
-
res.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Asset-Width, X-Asset-Height, X-Asset-Themeable");
|
|
452
|
-
if (req.method === "OPTIONS") {
|
|
453
|
-
res.writeHead(204);
|
|
454
|
-
res.end();
|
|
455
|
-
return;
|
|
456
|
-
}
|
|
457
531
|
if (!req.url) {
|
|
458
532
|
sendError(res, 400, "Missing URL");
|
|
459
533
|
return;
|
|
460
534
|
}
|
|
461
|
-
const segments = new URL(req.url, getBaseUrl()).pathname.split("/").filter(Boolean);
|
|
462
|
-
if (segments.length !==
|
|
535
|
+
const segments = new URL$1(req.url, getBaseUrl()).pathname.split("/").filter(Boolean);
|
|
536
|
+
if (segments.length !== 3 || !secretsEqual(segments[0] ?? "", accessToken) || segments[1] !== "assets") {
|
|
463
537
|
sendError(res, 404, "Not Found");
|
|
464
538
|
return;
|
|
465
539
|
}
|
|
466
|
-
const
|
|
540
|
+
const origin = getHeader(req, "origin");
|
|
541
|
+
if (origin && (!isAllowedExtensionOrigin(origin, originPolicy) || options.authorizeExtensionOrigin && !options.authorizeExtensionOrigin(origin))) {
|
|
542
|
+
sendError(res, 403, "Forbidden");
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
if (origin) {
|
|
546
|
+
res.setHeader("Access-Control-Allow-Origin", origin);
|
|
547
|
+
res.setHeader("Vary", "Origin");
|
|
548
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
549
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Asset-Width, X-Asset-Height, X-Asset-Themeable");
|
|
550
|
+
}
|
|
551
|
+
if (req.method === "OPTIONS") {
|
|
552
|
+
res.writeHead(204);
|
|
553
|
+
res.end();
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
const filename = segments[2];
|
|
467
557
|
const hash = getHashFromAssetFilename(filename);
|
|
468
558
|
if (!hash) {
|
|
469
559
|
sendError(res, 404, "Not Found");
|
|
@@ -501,10 +591,29 @@ function createAssetHttpServer(store) {
|
|
|
501
591
|
}
|
|
502
592
|
return;
|
|
503
593
|
}
|
|
594
|
+
if (activeDownloads >= ASSET_MAX_CONCURRENT_DOWNLOADS) {
|
|
595
|
+
res.setHeader("Connection", "close");
|
|
596
|
+
sendError(res, 429, "Too Many Concurrent Downloads");
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
activeDownloads += 1;
|
|
600
|
+
let released = false;
|
|
601
|
+
const release = () => {
|
|
602
|
+
if (released) return;
|
|
603
|
+
released = true;
|
|
604
|
+
activeDownloads -= 1;
|
|
605
|
+
};
|
|
606
|
+
res.once("finish", release);
|
|
607
|
+
res.once("close", release);
|
|
608
|
+
res.setTimeout(ASSET_REQUEST_TIMEOUT_MS, () => res.destroy());
|
|
504
609
|
res.writeHead(200, {
|
|
505
610
|
"Content-Type": record.mimeType,
|
|
506
611
|
"Content-Length": stat.size.toString(),
|
|
507
|
-
"Cache-Control": "
|
|
612
|
+
"Cache-Control": "private, max-age=31536000, immutable",
|
|
613
|
+
"Content-Disposition": `attachment; filename="${buildAssetFilename(hash, record.mimeType)}"`,
|
|
614
|
+
"Content-Security-Policy": "default-src 'none'; sandbox",
|
|
615
|
+
"Referrer-Policy": "no-referrer",
|
|
616
|
+
"X-Content-Type-Options": "nosniff"
|
|
508
617
|
});
|
|
509
618
|
const stream = createReadStream(record.filePath);
|
|
510
619
|
stream.on("error", (error) => {
|
|
@@ -526,13 +635,22 @@ function createAssetHttpServer(store) {
|
|
|
526
635
|
sendError(res, 400, "Invalid Hash");
|
|
527
636
|
return;
|
|
528
637
|
}
|
|
529
|
-
const
|
|
530
|
-
|
|
638
|
+
const declaredSize = parseContentLength(req);
|
|
639
|
+
if (declaredSize === "invalid") {
|
|
640
|
+
req.resume();
|
|
641
|
+
sendError(res, 400, "Invalid Content-Length");
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
if (declaredSize !== null && declaredSize > maxAssetSizeBytes) {
|
|
645
|
+
req.resume();
|
|
646
|
+
sendError(res, 413, "Payload Too Large");
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
const mimeType = normalizeMimeType(getHeader(req, "content-type"));
|
|
531
650
|
const filePath = join(ASSET_DIR, buildAssetFilename(hash, mimeType));
|
|
532
|
-
const width = parseInt(req
|
|
533
|
-
const height = parseInt(req
|
|
534
|
-
const
|
|
535
|
-
const themeable = (Array.isArray(themeableHeader) ? themeableHeader[0] : themeableHeader) === "true";
|
|
651
|
+
const width = parseInt(getHeader(req, "x-asset-width") ?? "", 10);
|
|
652
|
+
const height = parseInt(getHeader(req, "x-asset-height") ?? "", 10);
|
|
653
|
+
const themeable = getHeader(req, "x-asset-themeable") === "true";
|
|
536
654
|
const metadata = {};
|
|
537
655
|
if (Number.isFinite(width) && width > 0) metadata.width = width;
|
|
538
656
|
if (Number.isFinite(height) && height > 0) metadata.height = height;
|
|
@@ -563,14 +681,28 @@ function createAssetHttpServer(store) {
|
|
|
563
681
|
if (existing.mimeType !== mimeType) existing.mimeType = mimeType;
|
|
564
682
|
existing.lastAccess = Date.now();
|
|
565
683
|
store.upsert(existing);
|
|
566
|
-
|
|
684
|
+
sendJson(res, 200, { message: "Asset Already Exists" });
|
|
567
685
|
return;
|
|
568
686
|
}
|
|
569
687
|
}
|
|
688
|
+
if (activeUploads >= maxConcurrentUploads) {
|
|
689
|
+
req.resume();
|
|
690
|
+
res.setHeader("Connection", "close");
|
|
691
|
+
sendError(res, 429, "Too Many Concurrent Uploads");
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
const reservationBytes = declaredSize ?? maxAssetSizeBytes;
|
|
695
|
+
if (getStoredAssetBytes(store, hash) + reservedUploadBytes + reservationBytes > maxAssetStoreBytes) {
|
|
696
|
+
req.resume();
|
|
697
|
+
sendError(res, 507, "Asset Store Quota Exceeded");
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
570
700
|
const tmpPath = `${filePath}.tmp.${nanoid()}`;
|
|
571
701
|
const writeStream = createWriteStream(tmpPath);
|
|
572
702
|
const hasher = createHash("sha256");
|
|
573
703
|
let size = 0;
|
|
704
|
+
activeUploads += 1;
|
|
705
|
+
reservedUploadBytes += reservationBytes;
|
|
574
706
|
const cleanup = () => {
|
|
575
707
|
if (existsSync(tmpPath)) try {
|
|
576
708
|
unlinkSync(tmpPath);
|
|
@@ -590,6 +722,8 @@ function createAssetHttpServer(store) {
|
|
|
590
722
|
hasher.update(chunk);
|
|
591
723
|
callback(null, chunk);
|
|
592
724
|
} }), writeStream, (err) => {
|
|
725
|
+
activeUploads -= 1;
|
|
726
|
+
reservedUploadBytes -= reservationBytes;
|
|
593
727
|
if (err) {
|
|
594
728
|
cleanup();
|
|
595
729
|
if (err.message === "PayloadTooLarge") sendError(res, 413, "Payload Too Large");
|
|
@@ -610,6 +744,11 @@ function createAssetHttpServer(store) {
|
|
|
610
744
|
sendError(res, 400, "Hash Mismatch");
|
|
611
745
|
return;
|
|
612
746
|
}
|
|
747
|
+
if (getStoredAssetBytes(store, hash) + reservedUploadBytes + size > maxAssetStoreBytes) {
|
|
748
|
+
cleanup();
|
|
749
|
+
sendError(res, 507, "Asset Store Quota Exceeded");
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
613
752
|
try {
|
|
614
753
|
renameSync(tmpPath, filePath);
|
|
615
754
|
} catch (error) {
|
|
@@ -632,25 +771,32 @@ function createAssetHttpServer(store) {
|
|
|
632
771
|
hash,
|
|
633
772
|
size
|
|
634
773
|
}, "Stored uploaded asset via HTTP.");
|
|
635
|
-
|
|
774
|
+
sendJson(res, 201, {
|
|
775
|
+
message: "Created",
|
|
636
776
|
hash,
|
|
637
777
|
size
|
|
638
778
|
});
|
|
639
779
|
});
|
|
640
780
|
}
|
|
781
|
+
function redactAssetRequestUrl(requestUrl) {
|
|
782
|
+
if (!requestUrl) return requestUrl;
|
|
783
|
+
try {
|
|
784
|
+
const segments = new URL$1(requestUrl, `http://${LOOPBACK_HOST}`).pathname.split("/").filter(Boolean);
|
|
785
|
+
if (segments.length >= 1 && secretsEqual(segments[0] ?? "", accessToken)) segments[0] = "<capability>";
|
|
786
|
+
return `/${segments.join("/")}`;
|
|
787
|
+
} catch {
|
|
788
|
+
return "<invalid>";
|
|
789
|
+
}
|
|
790
|
+
}
|
|
641
791
|
function sendError(res, status, message, details) {
|
|
642
|
-
|
|
643
|
-
res.end(JSON.stringify({
|
|
792
|
+
sendJson(res, status, {
|
|
644
793
|
error: message,
|
|
645
794
|
...details
|
|
646
|
-
})
|
|
795
|
+
});
|
|
647
796
|
}
|
|
648
|
-
function
|
|
797
|
+
function sendJson(res, status, payload) {
|
|
649
798
|
if (!res.headersSent) res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
650
|
-
res.end(JSON.stringify(
|
|
651
|
-
message,
|
|
652
|
-
...data
|
|
653
|
-
}));
|
|
799
|
+
res.end(JSON.stringify(payload));
|
|
654
800
|
}
|
|
655
801
|
return {
|
|
656
802
|
start,
|
|
@@ -658,6 +804,23 @@ function createAssetHttpServer(store) {
|
|
|
658
804
|
getBaseUrl
|
|
659
805
|
};
|
|
660
806
|
}
|
|
807
|
+
function getHeader(req, name) {
|
|
808
|
+
const value = req.headers[name];
|
|
809
|
+
return Array.isArray(value) ? value[0] : value;
|
|
810
|
+
}
|
|
811
|
+
function parseContentLength(req) {
|
|
812
|
+
const value = getHeader(req, "content-length");
|
|
813
|
+
if (value === void 0) return null;
|
|
814
|
+
if (!/^\d+$/.test(value)) return "invalid";
|
|
815
|
+
const parsed = Number(value);
|
|
816
|
+
return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : "invalid";
|
|
817
|
+
}
|
|
818
|
+
function getStoredAssetBytes(store, excludeHash) {
|
|
819
|
+
return store.list().reduce((total, record) => {
|
|
820
|
+
if (record.hash === excludeHash) return total;
|
|
821
|
+
return Number.isFinite(record.size) && record.size > 0 ? total + record.size : total;
|
|
822
|
+
}, 0);
|
|
823
|
+
}
|
|
661
824
|
//#endregion
|
|
662
825
|
//#region src/asset-store.ts
|
|
663
826
|
const INDEX_FILENAME = "assets.json";
|
|
@@ -819,6 +982,166 @@ function createAssetStore(options = {}) {
|
|
|
819
982
|
};
|
|
820
983
|
}
|
|
821
984
|
//#endregion
|
|
985
|
+
//#region src/extension-registry.ts
|
|
986
|
+
var ExtensionRegistry = class {
|
|
987
|
+
#autoActivateGraceMs;
|
|
988
|
+
#extensions = [];
|
|
989
|
+
#activeId = null;
|
|
990
|
+
#autoActivateTimer = null;
|
|
991
|
+
constructor(autoActivateGraceMs) {
|
|
992
|
+
this.#autoActivateGraceMs = autoActivateGraceMs;
|
|
993
|
+
}
|
|
994
|
+
get size() {
|
|
995
|
+
return this.#extensions.length;
|
|
996
|
+
}
|
|
997
|
+
add(extension) {
|
|
998
|
+
if (this.#extensions.some(({ id }) => id === extension.id)) throw new Error(`Extension connection already registered: ${extension.id}`);
|
|
999
|
+
this.#extensions.push(extension);
|
|
1000
|
+
}
|
|
1001
|
+
remove(id) {
|
|
1002
|
+
const index = this.#extensions.findIndex((extension) => extension.id === id);
|
|
1003
|
+
if (index < 0) return null;
|
|
1004
|
+
this.clearAutoActivation();
|
|
1005
|
+
const extension = this.#extensions[index];
|
|
1006
|
+
this.#extensions.splice(index, 1);
|
|
1007
|
+
const wasActive = this.#activeId === id;
|
|
1008
|
+
if (wasActive) this.#activeId = null;
|
|
1009
|
+
return {
|
|
1010
|
+
extension,
|
|
1011
|
+
wasActive
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
activate(id) {
|
|
1015
|
+
const target = this.#extensions.find((extension) => extension.id === id);
|
|
1016
|
+
if (!target) return false;
|
|
1017
|
+
const active = this.getActive();
|
|
1018
|
+
if (active && active.id !== target.id && active.origin !== target.origin) return false;
|
|
1019
|
+
this.#activeId = id;
|
|
1020
|
+
return true;
|
|
1021
|
+
}
|
|
1022
|
+
getActive() {
|
|
1023
|
+
return this.#extensions.find((extension) => extension.id === this.#activeId);
|
|
1024
|
+
}
|
|
1025
|
+
getActiveId() {
|
|
1026
|
+
return this.#activeId;
|
|
1027
|
+
}
|
|
1028
|
+
list() {
|
|
1029
|
+
return this.#extensions;
|
|
1030
|
+
}
|
|
1031
|
+
scheduleAutoActivation(onActivated) {
|
|
1032
|
+
this.clearAutoActivation();
|
|
1033
|
+
if (this.#extensions.length !== 1 || this.getActive()) return;
|
|
1034
|
+
const targetId = this.#extensions[0].id;
|
|
1035
|
+
this.#autoActivateTimer = setTimeout(() => {
|
|
1036
|
+
this.#autoActivateTimer = null;
|
|
1037
|
+
if (this.#extensions.length !== 1 || this.getActiveId() || !this.activate(targetId)) return;
|
|
1038
|
+
onActivated(targetId);
|
|
1039
|
+
}, this.#autoActivateGraceMs);
|
|
1040
|
+
unrefTimer$1(this.#autoActivateTimer);
|
|
1041
|
+
}
|
|
1042
|
+
clearAutoActivation() {
|
|
1043
|
+
if (!this.#autoActivateTimer) return;
|
|
1044
|
+
clearTimeout(this.#autoActivateTimer);
|
|
1045
|
+
this.#autoActivateTimer = null;
|
|
1046
|
+
}
|
|
1047
|
+
dispose() {
|
|
1048
|
+
this.clearAutoActivation();
|
|
1049
|
+
}
|
|
1050
|
+
};
|
|
1051
|
+
function unrefTimer$1(timer) {
|
|
1052
|
+
if (typeof timer !== "object" || timer === null) return;
|
|
1053
|
+
const handle = timer;
|
|
1054
|
+
if (typeof handle.unref === "function") handle.unref();
|
|
1055
|
+
}
|
|
1056
|
+
//#endregion
|
|
1057
|
+
//#region src/extension-socket.ts
|
|
1058
|
+
function attachExtensionSocket(ws, options) {
|
|
1059
|
+
const extension = {
|
|
1060
|
+
id: options.createId(),
|
|
1061
|
+
origin: options.origin.toLowerCase(),
|
|
1062
|
+
ws
|
|
1063
|
+
};
|
|
1064
|
+
options.registry.add(extension);
|
|
1065
|
+
options.onConnected?.(extension.id);
|
|
1066
|
+
const registered = {
|
|
1067
|
+
id: extension.id,
|
|
1068
|
+
type: "registered"
|
|
1069
|
+
};
|
|
1070
|
+
ws.send(JSON.stringify(registered));
|
|
1071
|
+
options.onStateChange();
|
|
1072
|
+
scheduleAutoActivation(options);
|
|
1073
|
+
ws.on("message", (raw, isBinary) => {
|
|
1074
|
+
if (isBinary) {
|
|
1075
|
+
options.onProtocolWarning?.({
|
|
1076
|
+
extensionId: extension.id,
|
|
1077
|
+
kind: "binary"
|
|
1078
|
+
});
|
|
1079
|
+
return;
|
|
1080
|
+
}
|
|
1081
|
+
let parsedJson;
|
|
1082
|
+
try {
|
|
1083
|
+
parsedJson = JSON.parse(rawDataToBuffer(raw).toString("utf-8"));
|
|
1084
|
+
} catch (error) {
|
|
1085
|
+
options.onProtocolWarning?.({
|
|
1086
|
+
error,
|
|
1087
|
+
extensionId: extension.id,
|
|
1088
|
+
kind: "json"
|
|
1089
|
+
});
|
|
1090
|
+
return;
|
|
1091
|
+
}
|
|
1092
|
+
const parseResult = MessageFromExtensionSchema.safeParse(parsedJson);
|
|
1093
|
+
if (!parseResult.success) {
|
|
1094
|
+
options.onProtocolWarning?.({
|
|
1095
|
+
error: parseResult.error.flatten(),
|
|
1096
|
+
extensionId: extension.id,
|
|
1097
|
+
kind: "schema"
|
|
1098
|
+
});
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
const message = parseResult.data;
|
|
1102
|
+
switch (message.type) {
|
|
1103
|
+
case "activate":
|
|
1104
|
+
if (options.registry.activate(extension.id)) {
|
|
1105
|
+
options.onActivated?.(extension.id);
|
|
1106
|
+
options.onStateChange();
|
|
1107
|
+
scheduleAutoActivation(options);
|
|
1108
|
+
} else {
|
|
1109
|
+
const activeExtensionId = options.registry.getActiveId();
|
|
1110
|
+
if (activeExtensionId) options.onActivationRejected?.(extension.id, activeExtensionId);
|
|
1111
|
+
}
|
|
1112
|
+
break;
|
|
1113
|
+
case "toolResult":
|
|
1114
|
+
if (message.error !== void 0) options.onToolError(message.id, extension.id, message.error);
|
|
1115
|
+
else options.onToolResult(message.id, extension.id, message.payload);
|
|
1116
|
+
break;
|
|
1117
|
+
case "ping": break;
|
|
1118
|
+
}
|
|
1119
|
+
});
|
|
1120
|
+
ws.on("error", (error) => {
|
|
1121
|
+
options.onSocketError?.(extension.id, error);
|
|
1122
|
+
});
|
|
1123
|
+
ws.once("close", () => {
|
|
1124
|
+
const removed = options.registry.remove(extension.id);
|
|
1125
|
+
if (!removed) return;
|
|
1126
|
+
options.onDisconnected?.(extension.id, removed.wasActive);
|
|
1127
|
+
options.onStateChange();
|
|
1128
|
+
scheduleAutoActivation(options);
|
|
1129
|
+
});
|
|
1130
|
+
return extension;
|
|
1131
|
+
}
|
|
1132
|
+
function scheduleAutoActivation(options) {
|
|
1133
|
+
options.registry.scheduleAutoActivation((extensionId) => {
|
|
1134
|
+
options.onAutoActivated?.(extensionId);
|
|
1135
|
+
options.onStateChange();
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
function rawDataToBuffer(raw) {
|
|
1139
|
+
if (typeof raw === "string") return Buffer.from(raw);
|
|
1140
|
+
if (Buffer.isBuffer(raw)) return raw;
|
|
1141
|
+
if (raw instanceof ArrayBuffer) return Buffer.from(raw);
|
|
1142
|
+
return Buffer.concat(raw);
|
|
1143
|
+
}
|
|
1144
|
+
//#endregion
|
|
822
1145
|
//#region src/instructions.md?raw
|
|
823
1146
|
var instructions_default = "You are connected to a Figma design file via TemPad Dev MCP.\n\nTreat tool outputs as design facts. Refactor only to match the user’s repo conventions; do not invent key style values.\n\nRules:\n\n- Never output any `data-hint-*` attributes from tool outputs (hints only).\n- If `get_code` warns `depth-cap`, keep the returned parent code as composition evidence and use returned `data-hint-id` values to choose narrower `get_code` follow-ups.\n- If `get_code` warns `shell`, read the inline code comment for omitted direct child ids, then call `get_code` for those ids in order and fill the results back into the returned shell.\n- Use `get_structure` only to resolve layout/overlap uncertainty; do not derive numeric values from images.\n- Tokens: `get_code.tokens` keys are canonical names (`--...`). Multi‑mode values use `${collectionName}:${modeName}`. Nodes may hint per-node overrides via `data-hint-variable-mode=\"Collection=Mode;...\"`.\n- Vectors: `vectorMode=smart` is the default. Treat the emitted markup as the source of truth for the current response; vector code is emitted as `<svg data-src=\"...\">` placeholders, but if asset upload fails after export the tool may inline the SVG as a fallback to preserve source of truth.\n- Themeable vectors: `themeable=true` means the SVG can safely adopt one contextual color channel. In `smart` mode, that color is typically already evidenced on the emitted `svg` root markup for the placeholder. It does not mean the SVG exposes multiple independent color parameters.\n- Assets: download bytes via `asset.url`. Asset resources are not exposed via MCP `resources/read`. Use `asset.themeable` only when an SVG still needs repo asset handling after you account for the Host app's vector policy.\n";
|
|
824
1147
|
//#endregion
|
|
@@ -847,18 +1170,34 @@ function register(extensionId, timeout) {
|
|
|
847
1170
|
requestId
|
|
848
1171
|
};
|
|
849
1172
|
}
|
|
850
|
-
function resolve(requestId, payload) {
|
|
1173
|
+
function resolve(requestId, extensionId, payload) {
|
|
851
1174
|
const call = pendingCalls.get(requestId);
|
|
852
1175
|
if (call) {
|
|
1176
|
+
if (call.extensionId !== extensionId) {
|
|
1177
|
+
log.warn({
|
|
1178
|
+
reqId: requestId,
|
|
1179
|
+
expectedExtId: call.extensionId,
|
|
1180
|
+
receivedExtId: extensionId
|
|
1181
|
+
}, "Ignored tool result from the wrong extension.");
|
|
1182
|
+
return;
|
|
1183
|
+
}
|
|
853
1184
|
const { timer, resolve: finish } = call;
|
|
854
1185
|
clearTimeout(timer);
|
|
855
1186
|
finish(payload);
|
|
856
1187
|
pendingCalls.delete(requestId);
|
|
857
1188
|
} else log.warn({ reqId: requestId }, "Received result for unknown/timed-out call.");
|
|
858
1189
|
}
|
|
859
|
-
function reject(requestId, error) {
|
|
1190
|
+
function reject(requestId, extensionId, error) {
|
|
860
1191
|
const call = pendingCalls.get(requestId);
|
|
861
1192
|
if (call) {
|
|
1193
|
+
if (call.extensionId !== extensionId) {
|
|
1194
|
+
log.warn({
|
|
1195
|
+
reqId: requestId,
|
|
1196
|
+
expectedExtId: call.extensionId,
|
|
1197
|
+
receivedExtId: extensionId
|
|
1198
|
+
}, "Ignored tool error from the wrong extension.");
|
|
1199
|
+
return;
|
|
1200
|
+
}
|
|
862
1201
|
const { timer, reject: fail } = call;
|
|
863
1202
|
clearTimeout(timer);
|
|
864
1203
|
fail(error);
|
|
@@ -898,6 +1237,7 @@ const CONNECTIVITY_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
|
898
1237
|
TEMPAD_MCP_ERROR_CODES.TRANSPORT_NOT_CONNECTED
|
|
899
1238
|
]);
|
|
900
1239
|
const SELECTION_ERROR_CODES = /* @__PURE__ */ new Set([TEMPAD_MCP_ERROR_CODES.INVALID_SELECTION, TEMPAD_MCP_ERROR_CODES.NODE_NOT_VISIBLE]);
|
|
1240
|
+
const KNOWN_ERROR_CODES = new Set(Object.values(TEMPAD_MCP_ERROR_CODES));
|
|
901
1241
|
const CONNECTIVITY_TROUBLESHOOTING_LINES = [
|
|
902
1242
|
"Troubleshooting:",
|
|
903
1243
|
"- In Figma, open TemPad Dev panel and enable the MCP server in Preferences → Agent integration.",
|
|
@@ -957,9 +1297,12 @@ const TOOL_DEFS = [
|
|
|
957
1297
|
];
|
|
958
1298
|
function extractToolErrorCode(error) {
|
|
959
1299
|
const code = getRecordProperty$1(error, "code");
|
|
960
|
-
if (
|
|
1300
|
+
if (isTempadMcpErrorCode(code)) return code;
|
|
961
1301
|
const causeCode = getRecordProperty$1(getRecordProperty$1(error, "cause"), "code");
|
|
962
|
-
if (
|
|
1302
|
+
if (isTempadMcpErrorCode(causeCode)) return causeCode;
|
|
1303
|
+
}
|
|
1304
|
+
function isTempadMcpErrorCode(value) {
|
|
1305
|
+
return typeof value === "string" && KNOWN_ERROR_CODES.has(value);
|
|
963
1306
|
}
|
|
964
1307
|
function extractToolErrorMessage(error) {
|
|
965
1308
|
if (error instanceof Error) return error.message || "Unknown error occurred.";
|
|
@@ -1067,14 +1410,68 @@ function getBudgetRetryGuidance(toolName) {
|
|
|
1067
1410
|
}
|
|
1068
1411
|
}
|
|
1069
1412
|
//#endregion
|
|
1413
|
+
//#region src/websocket-server.ts
|
|
1414
|
+
async function startExtensionWebSocketServer({ maxPayloadBytes, maxConnections, originPolicy, portCandidates, onPortInUse, onConnectionLimit, onRejectedHandshake }) {
|
|
1415
|
+
for (const candidate of portCandidates) {
|
|
1416
|
+
const server = new WebSocketServer({
|
|
1417
|
+
host: "127.0.0.1",
|
|
1418
|
+
port: candidate,
|
|
1419
|
+
maxPayload: maxPayloadBytes,
|
|
1420
|
+
verifyClient: (info) => {
|
|
1421
|
+
if (server.clients.size >= maxConnections) {
|
|
1422
|
+
onConnectionLimit?.(maxConnections);
|
|
1423
|
+
return false;
|
|
1424
|
+
}
|
|
1425
|
+
const allowed = isAllowedWebSocketRequest(info.origin, info.req.url, originPolicy);
|
|
1426
|
+
if (!allowed) onRejectedHandshake?.(info.origin, info.req.url);
|
|
1427
|
+
return allowed;
|
|
1428
|
+
}
|
|
1429
|
+
});
|
|
1430
|
+
try {
|
|
1431
|
+
await waitForListening(server);
|
|
1432
|
+
return {
|
|
1433
|
+
server,
|
|
1434
|
+
port: resolveListeningPort(server, candidate)
|
|
1435
|
+
};
|
|
1436
|
+
} catch (error) {
|
|
1437
|
+
server.close();
|
|
1438
|
+
const errno = error;
|
|
1439
|
+
if (errno.code === "EADDRINUSE") {
|
|
1440
|
+
onPortInUse?.(candidate);
|
|
1441
|
+
continue;
|
|
1442
|
+
}
|
|
1443
|
+
throw errno;
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
throw new Error(`Unable to start WebSocket server on candidate ports: ${portCandidates.join(", ")}.`);
|
|
1447
|
+
}
|
|
1448
|
+
function waitForListening(server) {
|
|
1449
|
+
return new Promise((resolve, reject) => {
|
|
1450
|
+
const onError = (error) => {
|
|
1451
|
+
server.off("listening", onListening);
|
|
1452
|
+
reject(error);
|
|
1453
|
+
};
|
|
1454
|
+
const onListening = () => {
|
|
1455
|
+
server.off("error", onError);
|
|
1456
|
+
resolve();
|
|
1457
|
+
};
|
|
1458
|
+
server.once("error", onError);
|
|
1459
|
+
server.once("listening", onListening);
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
function resolveListeningPort(server, candidate) {
|
|
1463
|
+
const address = server.address();
|
|
1464
|
+
return address && typeof address === "object" ? address.port : candidate;
|
|
1465
|
+
}
|
|
1466
|
+
//#endregion
|
|
1070
1467
|
//#region src/hub.ts
|
|
1071
1468
|
const SHUTDOWN_TIMEOUT = 2e3;
|
|
1072
1469
|
const SOCKET_PROBE_TIMEOUT_MS = 300;
|
|
1073
|
-
const { wsPortCandidates, toolTimeoutMs, maxPayloadBytes, autoActivateGraceMs, assetTtlMs } = getMcpServerConfig();
|
|
1470
|
+
const { wsPortCandidates, toolTimeoutMs, maxPayloadBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig();
|
|
1471
|
+
const extensionOriginPolicy = createExtensionOriginPolicy(allowedExtensionOrigins);
|
|
1074
1472
|
log.info({ version: PACKAGE_VERSION }, "TemPad MCP Hub starting...");
|
|
1075
|
-
const
|
|
1473
|
+
const extensionRegistry = new ExtensionRegistry(autoActivateGraceMs);
|
|
1076
1474
|
let consumerCount = 0;
|
|
1077
|
-
let autoActivateTimer = null;
|
|
1078
1475
|
let selectedWsPort = 0;
|
|
1079
1476
|
let releaseHubLock = null;
|
|
1080
1477
|
let shuttingDown = false;
|
|
@@ -1207,7 +1604,7 @@ function getToolDefinition(name) {
|
|
|
1207
1604
|
return TOOL_BY_NAME[name];
|
|
1208
1605
|
}
|
|
1209
1606
|
const assetStore = createAssetStore();
|
|
1210
|
-
const assetHttpServer = createAssetHttpServer(assetStore);
|
|
1607
|
+
const assetHttpServer = createAssetHttpServer(assetStore, { authorizeExtensionOrigin: (origin) => extensionRegistry.getActive()?.origin === origin.toLowerCase() });
|
|
1211
1608
|
function scheduleAssetCleanup() {
|
|
1212
1609
|
if (assetTtlMs <= 0) {
|
|
1213
1610
|
log.info("Asset TTL cleanup disabled (TEMPAD_MCP_ASSET_TTL_MS=0).");
|
|
@@ -1279,7 +1676,7 @@ function registerProxiedTool(mcp, tool) {
|
|
|
1279
1676
|
let requestId;
|
|
1280
1677
|
try {
|
|
1281
1678
|
const parsedArgs = schema.parse(args);
|
|
1282
|
-
const activeExt =
|
|
1679
|
+
const activeExt = extensionRegistry.getActive();
|
|
1283
1680
|
if (!activeExt) throw createCodedError(TEMPAD_MCP_ERROR_CODES.NO_ACTIVE_EXTENSION, "No active TemPad Dev extension available.");
|
|
1284
1681
|
const registration = register(activeExt.id, toolTimeoutMs);
|
|
1285
1682
|
requestId = registration.requestId;
|
|
@@ -1377,33 +1774,6 @@ async function handleGetAssets({ hashes }) {
|
|
|
1377
1774
|
missing: unique.filter((hash) => !found.has(hash))
|
|
1378
1775
|
}));
|
|
1379
1776
|
}
|
|
1380
|
-
function getActiveId() {
|
|
1381
|
-
return extensions.find((e) => e.active)?.id ?? null;
|
|
1382
|
-
}
|
|
1383
|
-
function setActive(targetId) {
|
|
1384
|
-
extensions.forEach((e) => {
|
|
1385
|
-
e.active = targetId !== null && e.id === targetId;
|
|
1386
|
-
});
|
|
1387
|
-
}
|
|
1388
|
-
function clearAutoActivateTimer() {
|
|
1389
|
-
if (autoActivateTimer) {
|
|
1390
|
-
clearTimeout(autoActivateTimer);
|
|
1391
|
-
autoActivateTimer = null;
|
|
1392
|
-
}
|
|
1393
|
-
}
|
|
1394
|
-
function scheduleAutoActivate() {
|
|
1395
|
-
clearAutoActivateTimer();
|
|
1396
|
-
if (extensions.length !== 1 || getActiveId()) return;
|
|
1397
|
-
const target = extensions[0];
|
|
1398
|
-
autoActivateTimer = setTimeout(() => {
|
|
1399
|
-
autoActivateTimer = null;
|
|
1400
|
-
if (extensions.length === 1 && !getActiveId()) {
|
|
1401
|
-
setActive(target.id);
|
|
1402
|
-
log.info({ id: target.id }, "Auto-activated sole extension after grace period.");
|
|
1403
|
-
broadcastState();
|
|
1404
|
-
}
|
|
1405
|
-
}, autoActivateGraceMs);
|
|
1406
|
-
}
|
|
1407
1777
|
function unrefTimer(timer) {
|
|
1408
1778
|
if (typeof timer === "object" && timer !== null) {
|
|
1409
1779
|
const handle = timer;
|
|
@@ -1411,24 +1781,18 @@ function unrefTimer(timer) {
|
|
|
1411
1781
|
}
|
|
1412
1782
|
}
|
|
1413
1783
|
function broadcastState() {
|
|
1414
|
-
const activeId = getActiveId();
|
|
1784
|
+
const activeId = extensionRegistry.getActiveId();
|
|
1415
1785
|
const message = {
|
|
1416
1786
|
type: "state",
|
|
1417
1787
|
activeId,
|
|
1418
1788
|
assetServerUrl: assetHttpServer.getBaseUrl()
|
|
1419
1789
|
};
|
|
1420
|
-
|
|
1790
|
+
extensionRegistry.list().forEach((ext) => ext.ws.send(JSON.stringify(message)));
|
|
1421
1791
|
log.debug({
|
|
1422
1792
|
activeId,
|
|
1423
|
-
count:
|
|
1793
|
+
count: extensionRegistry.size
|
|
1424
1794
|
}, "Broadcasted state.");
|
|
1425
1795
|
}
|
|
1426
|
-
function rawDataToBuffer(raw) {
|
|
1427
|
-
if (typeof raw === "string") return Buffer.from(raw);
|
|
1428
|
-
if (Buffer.isBuffer(raw)) return raw;
|
|
1429
|
-
if (raw instanceof ArrayBuffer) return Buffer.from(raw);
|
|
1430
|
-
return Buffer.concat(raw);
|
|
1431
|
-
}
|
|
1432
1796
|
function shutdown() {
|
|
1433
1797
|
if (shuttingDown) return;
|
|
1434
1798
|
shuttingDown = true;
|
|
@@ -1440,6 +1804,7 @@ function shutdown() {
|
|
|
1440
1804
|
});
|
|
1441
1805
|
consumerSessions.clear();
|
|
1442
1806
|
assetStore.flush();
|
|
1807
|
+
extensionRegistry.dispose();
|
|
1443
1808
|
assetHttpServer.stop();
|
|
1444
1809
|
netServer.close(() => log.info("Net server closed."));
|
|
1445
1810
|
wss?.close(() => log.info("WebSocket server closed."));
|
|
@@ -1515,40 +1880,24 @@ function listenConsumerSocket() {
|
|
|
1515
1880
|
});
|
|
1516
1881
|
}
|
|
1517
1882
|
async function startWebSocketServer() {
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
server.once("error", onError);
|
|
1535
|
-
server.once("listening", onListening);
|
|
1536
|
-
});
|
|
1537
|
-
return {
|
|
1538
|
-
server,
|
|
1539
|
-
port: candidate
|
|
1540
|
-
};
|
|
1541
|
-
} catch (err) {
|
|
1542
|
-
server.close();
|
|
1543
|
-
const errno = err;
|
|
1544
|
-
if (errno.code === "EADDRINUSE") {
|
|
1545
|
-
log.warn({ port: candidate }, "WebSocket port in use, trying next candidate.");
|
|
1546
|
-
continue;
|
|
1547
|
-
}
|
|
1548
|
-
throw errno;
|
|
1883
|
+
return startExtensionWebSocketServer({
|
|
1884
|
+
maxConnections: maxExtensionConnections,
|
|
1885
|
+
maxPayloadBytes,
|
|
1886
|
+
originPolicy: extensionOriginPolicy,
|
|
1887
|
+
portCandidates: wsPortCandidates,
|
|
1888
|
+
onPortInUse: (port) => {
|
|
1889
|
+
log.warn({ port }, "WebSocket port in use, trying next candidate.");
|
|
1890
|
+
},
|
|
1891
|
+
onConnectionLimit: (limit) => {
|
|
1892
|
+
log.warn({ limit }, "Rejected WebSocket handshake at the extension connection limit.");
|
|
1893
|
+
},
|
|
1894
|
+
onRejectedHandshake: (origin, path) => {
|
|
1895
|
+
log.warn({
|
|
1896
|
+
origin: origin || "<missing>",
|
|
1897
|
+
path: path || "<missing>"
|
|
1898
|
+
}, "Rejected unauthorized WebSocket handshake.");
|
|
1549
1899
|
}
|
|
1550
|
-
}
|
|
1551
|
-
throw new Error(`Unable to start WebSocket server on candidate ports: ${wsPortCandidates.join(", ")}.`);
|
|
1900
|
+
});
|
|
1552
1901
|
}
|
|
1553
1902
|
async function startHubRuntime() {
|
|
1554
1903
|
await initializeHubRuntime();
|
|
@@ -1573,84 +1922,68 @@ activeWss.on("error", (err) => {
|
|
|
1573
1922
|
log.error({ err }, "WebSocket server critical error. Exiting.");
|
|
1574
1923
|
process.exit(1);
|
|
1575
1924
|
});
|
|
1576
|
-
activeWss.on("connection", (ws) => {
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
extensions.push(ext);
|
|
1583
|
-
log.info({ id: ext.id }, `Extension connected. Total: ${extensions.length}`);
|
|
1584
|
-
const message = {
|
|
1585
|
-
type: "registered",
|
|
1586
|
-
id: ext.id
|
|
1587
|
-
};
|
|
1588
|
-
ws.send(JSON.stringify(message));
|
|
1589
|
-
broadcastState();
|
|
1590
|
-
scheduleAutoActivate();
|
|
1591
|
-
ws.on("message", (raw, isBinary) => {
|
|
1592
|
-
if (isBinary) {
|
|
1593
|
-
log.warn({ extId: ext.id }, "Unexpected binary message received.");
|
|
1594
|
-
return;
|
|
1595
|
-
}
|
|
1596
|
-
const messageBuffer = rawDataToBuffer(raw);
|
|
1597
|
-
let parsedJson;
|
|
1598
|
-
try {
|
|
1599
|
-
parsedJson = JSON.parse(messageBuffer.toString("utf-8"));
|
|
1600
|
-
} catch (e) {
|
|
1925
|
+
activeWss.on("connection", (ws, request) => {
|
|
1926
|
+
attachExtensionSocket(ws, {
|
|
1927
|
+
createId: randomUUID,
|
|
1928
|
+
origin: request.headers.origin ?? "",
|
|
1929
|
+
registry: extensionRegistry,
|
|
1930
|
+
onActivationRejected: (extensionId, activeExtensionId) => {
|
|
1601
1931
|
log.warn({
|
|
1602
|
-
|
|
1603
|
-
|
|
1932
|
+
activeId: activeExtensionId,
|
|
1933
|
+
id: extensionId
|
|
1934
|
+
}, "Rejected activation from a different extension Origin.");
|
|
1935
|
+
},
|
|
1936
|
+
onActivated: (extensionId) => {
|
|
1937
|
+
log.info({ id: extensionId }, "Extension activated.");
|
|
1938
|
+
},
|
|
1939
|
+
onAutoActivated: (extensionId) => {
|
|
1940
|
+
log.info({ id: extensionId }, "Auto-activated sole extension after grace period.");
|
|
1941
|
+
},
|
|
1942
|
+
onConnected: (extensionId) => {
|
|
1943
|
+
log.info({ id: extensionId }, `Extension connected. Total: ${extensionRegistry.size}`);
|
|
1944
|
+
},
|
|
1945
|
+
onDisconnected: (extensionId, wasActive) => {
|
|
1946
|
+
log.info({ id: extensionId }, `Extension disconnected. Remaining: ${extensionRegistry.size}`);
|
|
1947
|
+
cleanupForExtension(extensionId);
|
|
1948
|
+
if (wasActive) log.warn({ id: extensionId }, "Active extension disconnected.");
|
|
1949
|
+
},
|
|
1950
|
+
onProtocolWarning: (warning) => {
|
|
1951
|
+
if (warning.kind === "binary") log.warn({ extId: warning.extensionId }, "Unexpected binary message received.");
|
|
1952
|
+
else if (warning.kind === "json") log.warn({
|
|
1953
|
+
err: warning.error,
|
|
1954
|
+
extId: warning.extensionId
|
|
1604
1955
|
}, "Failed to parse message.");
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
if (!parseResult.success) {
|
|
1609
|
-
log.warn({
|
|
1610
|
-
error: parseResult.error.flatten(),
|
|
1611
|
-
extId: ext.id
|
|
1956
|
+
else log.warn({
|
|
1957
|
+
error: warning.error,
|
|
1958
|
+
extId: warning.extensionId
|
|
1612
1959
|
}, "Invalid message shape.");
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
reject(id, normalized);
|
|
1634
|
-
} else resolve(id, payload);
|
|
1635
|
-
break;
|
|
1636
|
-
}
|
|
1637
|
-
case "ping": break;
|
|
1638
|
-
}
|
|
1639
|
-
});
|
|
1640
|
-
ws.on("close", () => {
|
|
1641
|
-
const index = extensions.findIndex((e) => e.id === ext.id);
|
|
1642
|
-
if (index > -1) extensions.splice(index, 1);
|
|
1643
|
-
log.info({ id: ext.id }, `Extension disconnected. Remaining: ${extensions.length}`);
|
|
1644
|
-
cleanupForExtension(ext.id);
|
|
1645
|
-
if (ext.active) {
|
|
1646
|
-
log.warn({ id: ext.id }, "Active extension disconnected.");
|
|
1647
|
-
setActive(null);
|
|
1960
|
+
},
|
|
1961
|
+
onSocketError: (extensionId, error) => {
|
|
1962
|
+
log.warn({
|
|
1963
|
+
err: error,
|
|
1964
|
+
extId: extensionId
|
|
1965
|
+
}, "Extension WebSocket error.");
|
|
1966
|
+
},
|
|
1967
|
+
onStateChange: broadcastState,
|
|
1968
|
+
onToolError: (requestId, extensionId, error) => {
|
|
1969
|
+
const normalized = coerceToolError(error);
|
|
1970
|
+
log.warn({
|
|
1971
|
+
toolReq: requestId,
|
|
1972
|
+
extId: extensionId,
|
|
1973
|
+
code: getRecordProperty(normalized, "code"),
|
|
1974
|
+
message: normalized.message
|
|
1975
|
+
}, "Received tool error from extension.");
|
|
1976
|
+
reject(requestId, extensionId, normalized);
|
|
1977
|
+
},
|
|
1978
|
+
onToolResult: (requestId, extensionId, payload) => {
|
|
1979
|
+
resolve(requestId, extensionId, payload);
|
|
1648
1980
|
}
|
|
1649
|
-
broadcastState();
|
|
1650
|
-
scheduleAutoActivate();
|
|
1651
1981
|
});
|
|
1652
1982
|
});
|
|
1653
|
-
log.info({
|
|
1983
|
+
log.info({
|
|
1984
|
+
port: selectedWsPort,
|
|
1985
|
+
extensionOriginPolicy: extensionOriginPolicy.mode
|
|
1986
|
+
}, "WebSocket server ready.");
|
|
1654
1987
|
process.on("SIGINT", shutdown);
|
|
1655
1988
|
process.on("SIGTERM", shutdown);
|
|
1656
1989
|
//#endregion
|