text-to-design-mcp 0.1.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.
Files changed (3) hide show
  1. package/README.md +88 -0
  2. package/dist/index.js +1072 -0
  3. package/package.json +40 -0
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # text-to-design-mcp
2
+
3
+ MCP(MCP Model Context Protocol)server:把 AI 客户端桥接到 jsDesign(即时设计)桌面插件。
4
+
5
+ 采用生态主流形态:**共享 daemon + 每会话薄 shim**(同 chrome-devtools-mcp 模型)。
6
+
7
+ ```
8
+ jsDesign 插件 ──WS 47812──▶ daemon(独立常驻:WS server + MCP HTTP 47820)
9
+ ▲ ▲
10
+ opencode 会话A ──stdio──▶ shim A ──┘ HTTP ───────┤
11
+ opencode 会话B ──stdio──▶ shim B ──┘ HTTP ───────┘
12
+ ```
13
+
14
+ - **daemon**:插件 WS(47812)+ MCP streamable HTTP(47820),无 stdio。独立于任何会话进程,**会话关闭不影响插件连接**;空闲 5 分钟无请求自动退出
15
+ - **shim**:每个 opencode 会话由 `type: local` spawn 一个,探测 47820:
16
+ - 已有 daemon → 直接代理(自家 stdio 透传到 daemon HTTP 端点,不启 WS)
17
+ - 无 daemon → detached 自动拉起 daemon,等待就绪后代理
18
+ - 端口被外来服务占用 → fail-fast 明确报错
19
+ - 多个 opencode 会话**同时可用**,全部经各自 shim 共享同一 daemon、同一插件连接
20
+
21
+ 自愈闭环:daemon 空闲退出 → 插件 1s 轮询重连 → 新会话自动拉起新 daemon。
22
+
23
+ ## 快速开始
24
+
25
+ **前提**:先安装并运行 jsDesign 插件侧(插件代码在仓库内):
26
+
27
+ 1. `pnpm install && pnpm build`(构建插件包 `packages/ui/dist/`,含 `ui.html` + `code.js` + `manifest.json`)
28
+ 2. jsDesign 客户端 →「插件」→「创建/添加插件」→ 选择仓库根目录的 `manifest.json`
29
+ 3. 画布内「运行插件」,UI 面板出现且显示「已连接」即就绪
30
+
31
+ **无需手动启动 server**:opencode 打开会话时自动 spawn shim,shim 自动拉起 daemon。插件先运行、会话后开顺序更佳(插件 1s 轮询会自动连上)。
32
+
33
+ ## 客户端配置
34
+
35
+ 以 opencode 为例(`opencode.json`),用 `type: local` 由 opencode 自动拉起:
36
+
37
+ ```json
38
+ {
39
+ "mcp": {
40
+ "text-to-design": {
41
+ "type": "local",
42
+ "command": ["pnpm", "run", "mcp"],
43
+ "enabled": true
44
+ }
45
+ }
46
+ }
47
+ ```
48
+
49
+ ## 环境变量
50
+
51
+ | 变量 | 默认 | 说明 |
52
+ | --- | --- | --- |
53
+ | `TEXT_TO_DESIGN_MCP_PORT` | `47812` | 插件桥接 WebSocket 端口(固定,被占即启动失败) |
54
+ | `TEXT_TO_DESIGN_MCP_HTTP_PORT` | `47820` | MCP streamable HTTP 端点端口(shim 连接 daemon 用) |
55
+ | `TEXT_TO_DESIGN_MCP_LOG` | `/tmp/text-to-design-mcp.log` | daemon 日志文件路径(detached 启动 stderr 不可见,消息收发/超时/未匹配全部落盘;`tail -f` 观察) |
56
+
57
+ ## daemon 生命周期
58
+
59
+ - 由第一个 shim 自动拉起(detached,不随会话退出)
60
+ - 空闲 5 分钟无 HTTP 请求自动退出;插件连接不影响该计时(插件会自动重连)
61
+ - 手动清理:`pkill -f "index.ts daemon"`
62
+
63
+ ## 工具
64
+
65
+ | 工具 | 说明 |
66
+ | --- | --- |
67
+ | `text_to_design_ping` | 检查 jsDesign 插件是否在线 |
68
+ | `text_to_design_get_selection` | 获取画布当前选中节点信息 |
69
+ | `text_to_design_execute` | 在画布执行声明式设计指令(op 节点树,支持 frame/rect/ellipse/line/polygon/star/vector/text,阴影/描边/渐变/文本样式) |
70
+ | `text_to_design_html_to_design` | 将 HTML 转换为设计节点(SVG 保真路线) |
71
+ | `text_to_design_update_selection` | 修改选中节点属性(含原生阴影/描边/文本样式/细分圆角) |
72
+ | `text_to_design_find` | 按名称/类型查找节点 |
73
+ | `text_to_design_set_selection` | 设置画布选中节点 |
74
+ | `text_to_design_remove` | 删除节点(按 ids/名称/选中) |
75
+ | `text_to_design_clone` | 复制节点 |
76
+ | `text_to_design_group` | 编组/取消编组 |
77
+ | `text_to_design_export` | 导出节点为 PNG/JPG/SVG/PDF(二进制通道;可 savePath 落盘或 includeDataUrl 生成 base64) |
78
+ | `text_to_design_list_fonts` | 列出可用字体族 |
79
+ | `text_to_design_fill_image` | 将本地图片文件字节填充到节点(IMAGE fill) |
80
+
81
+ ## 开发
82
+
83
+ ```bash
84
+ pnpm install
85
+ pnpm dev # watch 构建 ui/code(ui 包内并行)
86
+ pnpm mcp # 直接启动 mcp-server(shim 角色;加 daemon 参数则以 daemon 角色运行)
87
+ pnpm --filter text-to-design-mcp start # 或直接进 packages/mcp-server 跑 start
88
+ ```
package/dist/index.js ADDED
@@ -0,0 +1,1072 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { createServer } from "node:http";
5
+ import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
6
+ import { localhostHostValidation, localhostOriginValidation, toNodeHandler } from "@modelcontextprotocol/node";
7
+ import { McpServer, SUPPORTED_PROTOCOL_VERSIONS, createMcpHandler, fromJsonSchema } from "@modelcontextprotocol/server";
8
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
9
+ import { z } from "zod";
10
+ import { WebSocket, WebSocketServer } from "ws";
11
+ import { isTag } from "domhandler";
12
+ import { parseDocument } from "htmlparser2";
13
+ //#region src/logger.ts
14
+ var FILE = process.env.TEXT_TO_DESIGN_MCP_LOG ?? "/tmp/text-to-design-mcp.log";
15
+ /** 追加一行日志到文件(daemon detached + stdio ignored,stderr 不可见,必须落盘) */
16
+ function log(line) {
17
+ try {
18
+ appendFileSync(FILE, `${(/* @__PURE__ */ new Date()).toISOString()} [text-to-design-mcp] ${line}\n`);
19
+ } catch {}
20
+ }
21
+ //#endregion
22
+ //#region src/pending.ts
23
+ var DEFAULT_TIMEOUT = 3e4;
24
+ /** 请求关联:发出发送、pending 表、响应/二进制帧组装、超时与整体拒绝 */
25
+ var PendingManager = class {
26
+ pending = /* @__PURE__ */ new Map();
27
+ seq = 0;
28
+ binaryTarget = null;
29
+ sendFn;
30
+ constructor(send) {
31
+ this.sendFn = send;
32
+ }
33
+ request(method, params, timeout = DEFAULT_TIMEOUT) {
34
+ const id = `r${++this.seq}`;
35
+ const binary = params && typeof params === "object" && "bytes" in params ? params.bytes : null;
36
+ const payload = binary != null ? {
37
+ type: "request",
38
+ id,
39
+ method,
40
+ params: {
41
+ ...params,
42
+ hasBinary: true,
43
+ bytes: void 0
44
+ }
45
+ } : {
46
+ type: "request",
47
+ id,
48
+ method,
49
+ params
50
+ };
51
+ return new Promise((resolve, reject) => {
52
+ const timer = setTimeout(() => {
53
+ this.pending.delete(id);
54
+ log(`请求超时: ${id} ${method}`);
55
+ reject(/* @__PURE__ */ new Error(`请求超时: ${method}`));
56
+ }, timeout);
57
+ this.pending.set(id, {
58
+ id,
59
+ resolve,
60
+ reject,
61
+ timer,
62
+ waitBinary: false,
63
+ binaryCount: 0,
64
+ buffers: []
65
+ });
66
+ log(`发出请求: ${id} ${method}${binary != null ? ` +binary(${binary.byteLength}B)` : ""}`);
67
+ this.sendFn(JSON.stringify(payload), binary != null ? Buffer.from(binary) : void 0);
68
+ });
69
+ }
70
+ onText(raw) {
71
+ let msg;
72
+ try {
73
+ msg = JSON.parse(raw.toString());
74
+ } catch {
75
+ log(`WS 文本解析失败: ${raw.toString().slice(0, 100)}`);
76
+ return;
77
+ }
78
+ if (msg.type === "request") {
79
+ if (msg.method === "ping") {
80
+ log(`收到 ping 请求: ${msg.id} (自动回 pong)`);
81
+ this.sendFn(JSON.stringify({
82
+ type: "response",
83
+ id: msg.id,
84
+ ok: true,
85
+ data: { pong: true }
86
+ }));
87
+ } else log(`收到未知请求: ${msg.id} ${msg.method} (忽略)`);
88
+ return;
89
+ }
90
+ if (msg.type !== "response") {
91
+ log(`收到非响应消息: type=${msg.type}`);
92
+ return;
93
+ }
94
+ const pending = this.pending.get(msg.id);
95
+ if (!pending) {
96
+ log(`未匹配响应: id=${msg.id}(可能已超时或来源不明)`);
97
+ return;
98
+ }
99
+ if (msg.hasBinary && (msg.binaryCount ?? 1) > 0) {
100
+ log(`二进制响应开始: id=${msg.id} count=${msg.binaryCount ?? 1}`);
101
+ pending.waitBinary = true;
102
+ pending.binaryCount = msg.binaryCount ?? 1;
103
+ this.binaryTarget = pending;
104
+ return;
105
+ }
106
+ this.pending.delete(msg.id);
107
+ clearTimeout(pending.timer);
108
+ log(`匹配响应: id=${msg.id} ok=${msg.ok}${msg.ok ? "" : ` error=${msg.error ?? ""}`}`);
109
+ if (msg.ok) pending.resolve(msg.data);
110
+ else pending.reject(new Error(msg.error ?? "plugin error"));
111
+ }
112
+ onBinary(raw) {
113
+ if (!this.binaryTarget) {
114
+ log(`孤儿二进制帧 len=${raw.byteLength}(无待组装响应)`);
115
+ return;
116
+ }
117
+ this.binaryTarget.buffers.push(raw);
118
+ log(`二进制帧: id=${this.binaryTarget.id} ${this.binaryTarget.buffers.length}/${this.binaryTarget.binaryCount}`);
119
+ if (this.binaryTarget.buffers.length >= this.binaryTarget.binaryCount) {
120
+ const target = this.binaryTarget;
121
+ this.binaryTarget = null;
122
+ log(`二进制组装完成: id=${target.id} ${target.buffers.length} 帧`);
123
+ this.settle(target);
124
+ }
125
+ }
126
+ rejectAll(err) {
127
+ for (const [, p] of this.pending) {
128
+ clearTimeout(p.timer);
129
+ p.reject(err);
130
+ }
131
+ this.pending.clear();
132
+ }
133
+ clear() {
134
+ for (const [, p] of this.pending) clearTimeout(p.timer);
135
+ this.pending.clear();
136
+ this.binaryTarget = null;
137
+ }
138
+ settle(pending) {
139
+ this.pending.delete(pending.id);
140
+ clearTimeout(pending.timer);
141
+ const data = pending.buffers.length === 1 ? pending.buffers[0] : pending.buffers;
142
+ pending.resolve(data);
143
+ }
144
+ };
145
+ //#endregion
146
+ //#region src/transport.ts
147
+ /** WSS/HTTP 生命周期(固定端口,被占即失败),消息透传上层 */
148
+ var Transport = class {
149
+ wss = null;
150
+ http = null;
151
+ client = null;
152
+ _port = 0;
153
+ onMessage = null;
154
+ onDisconnect = null;
155
+ get port() {
156
+ return this._port;
157
+ }
158
+ async start(port) {
159
+ this.http = createServer();
160
+ this.wss = new WebSocketServer({ server: this.http });
161
+ this.wss.on("error", () => {});
162
+ this.wss.on("connection", (ws) => {
163
+ this.client = ws;
164
+ process.stderr.write("[text-to-design-mcp] 插件已连接\n");
165
+ log("插件已连接");
166
+ ws.on("message", (raw, isBinary) => {
167
+ const buf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
168
+ log(`收到 WS 消息 len=${buf.length} bin=${isBinary}`);
169
+ this.onMessage?.(buf, isBinary);
170
+ });
171
+ ws.on("close", () => {
172
+ if (this.client === ws) this.client = null;
173
+ process.stderr.write("[text-to-design-mcp] 插件断开\n");
174
+ log("插件断开");
175
+ this.onDisconnect?.(/* @__PURE__ */ new Error("plugin disconnected"));
176
+ });
177
+ ws.on("error", () => {
178
+ if (this.client === ws) this.client = null;
179
+ this.onDisconnect?.(/* @__PURE__ */ new Error("plugin connection error"));
180
+ });
181
+ });
182
+ if (!await this.tryListen(port)) {
183
+ this.http.close();
184
+ throw new Error(`端口 ${port} 已被占用。已有 text-to-design-mcp 实例在运行?请检查残留进程后重试`);
185
+ }
186
+ this._port = port;
187
+ }
188
+ stop() {
189
+ this.wss?.close();
190
+ this.http?.close();
191
+ }
192
+ get isConnected() {
193
+ return this.client !== null && this.client.readyState === WebSocket.OPEN;
194
+ }
195
+ send(data) {
196
+ if (this.client && this.client.readyState === WebSocket.OPEN) this.client.send(data);
197
+ else log(`发送失败: 无客户端连接(${data.length} 字节被丢弃)`);
198
+ }
199
+ tryListen(p) {
200
+ return new Promise((resolve) => {
201
+ const onError = () => {
202
+ cleanup();
203
+ resolve(false);
204
+ };
205
+ const onListening = () => {
206
+ cleanup();
207
+ resolve(true);
208
+ };
209
+ const cleanup = () => {
210
+ this.http?.off("error", onError);
211
+ this.http?.off("listening", onListening);
212
+ };
213
+ this.http?.once("error", onError);
214
+ this.http?.once("listening", onListening);
215
+ this.http?.listen(p);
216
+ });
217
+ }
218
+ };
219
+ //#endregion
220
+ //#region src/bridge.ts
221
+ /** 门面:组合传输层与请求关联层,对外 API 不变 */
222
+ var Bridge = class {
223
+ transport = new Transport();
224
+ pending;
225
+ constructor() {
226
+ this.pending = new PendingManager((text, binary) => {
227
+ this.transport.send(text);
228
+ if (binary) this.transport.send(binary);
229
+ });
230
+ this.transport.onMessage = (raw, isBinary) => {
231
+ if (isBinary) this.pending.onBinary(raw);
232
+ else this.pending.onText(raw);
233
+ };
234
+ this.transport.onDisconnect = (err) => this.pending.rejectAll(err);
235
+ }
236
+ get port() {
237
+ return this.transport.port;
238
+ }
239
+ start(port) {
240
+ return this.transport.start(port);
241
+ }
242
+ stop() {
243
+ this.pending.clear();
244
+ this.transport.stop();
245
+ }
246
+ get isConnected() {
247
+ return this.transport.isConnected;
248
+ }
249
+ request(method, params, timeout) {
250
+ if (!this.transport.isConnected) {
251
+ log(`请求被拒(插件未连接): ${method}`);
252
+ return Promise.reject(/* @__PURE__ */ new Error("jsDesign 插件未连接。请先在即时设计客户端中运行该插件。"));
253
+ }
254
+ return this.pending.request(method, params, timeout);
255
+ }
256
+ };
257
+ //#endregion
258
+ //#region src/htmlToDesign.ts
259
+ var SKIP_TAGS = /* @__PURE__ */ new Set([
260
+ "script",
261
+ "style",
262
+ "head",
263
+ "meta",
264
+ "link",
265
+ "title",
266
+ "noscript"
267
+ ]);
268
+ var COLORS = {
269
+ white: "#ffffff",
270
+ black: "#000000",
271
+ red: "#ff0000",
272
+ green: "#008000",
273
+ blue: "#0000ff",
274
+ gray: "#808080",
275
+ grey: "#808080",
276
+ transparent: "none"
277
+ };
278
+ var FALLBACK_BG = "#f3f4f6";
279
+ function parseStyle(attr) {
280
+ const out = {};
281
+ if (!attr) return out;
282
+ for (const part of attr.split(";")) {
283
+ const i = part.indexOf(":");
284
+ if (i < 0) continue;
285
+ const key = part.slice(0, i).trim().toLowerCase();
286
+ const val = part.slice(i + 1).trim();
287
+ if (key) out[key] = val;
288
+ }
289
+ return out;
290
+ }
291
+ function num(value) {
292
+ if (value == null) return void 0;
293
+ const m = value.match(/^(-?[\d.]+)(px)?$/);
294
+ return m ? parseFloat(m[1]) : void 0;
295
+ }
296
+ function color(value, fallback) {
297
+ if (value == null || value === "") return fallback;
298
+ const v = value.trim();
299
+ if (v === "transparent") return "none";
300
+ const named = COLORS[v.toLowerCase()];
301
+ if (named) return named;
302
+ if (v.startsWith("#") || v.startsWith("rgb")) return v;
303
+ return fallback;
304
+ }
305
+ function parseMargin(style) {
306
+ const parts = (style.margin ?? "").split(/\s+/).filter(Boolean).map((p) => num(p) ?? 0);
307
+ let top = 0, right = 0, bottom = 0, left = 0;
308
+ if (parts.length === 1) top = right = bottom = left = parts[0];
309
+ else if (parts.length === 2) {
310
+ top = bottom = parts[0];
311
+ right = left = parts[1];
312
+ } else if (parts.length === 4) {
313
+ top = parts[0];
314
+ right = parts[1];
315
+ bottom = parts[2];
316
+ left = parts[3];
317
+ }
318
+ top = num(style["margin-top"]) ?? top;
319
+ right = num(style["margin-right"]) ?? right;
320
+ bottom = num(style["margin-bottom"]) ?? bottom;
321
+ left = num(style["margin-left"]) ?? left;
322
+ return {
323
+ top,
324
+ right,
325
+ bottom,
326
+ left
327
+ };
328
+ }
329
+ function parsePadding(style) {
330
+ const parts = (style.padding ?? "").split(/\s+/).filter(Boolean).map((p) => num(p) ?? 0);
331
+ let top = 0, right = 0, bottom = 0, left = 0;
332
+ if (parts.length === 1) top = right = bottom = left = parts[0];
333
+ else if (parts.length === 2) {
334
+ top = bottom = parts[0];
335
+ right = left = parts[1];
336
+ } else if (parts.length === 4) {
337
+ top = parts[0];
338
+ right = parts[1];
339
+ bottom = parts[2];
340
+ left = parts[3];
341
+ }
342
+ top = num(style["padding-top"]) ?? top;
343
+ right = num(style["padding-right"]) ?? right;
344
+ bottom = num(style["padding-bottom"]) ?? bottom;
345
+ left = num(style["padding-left"]) ?? left;
346
+ return {
347
+ top,
348
+ right,
349
+ bottom,
350
+ left
351
+ };
352
+ }
353
+ function parseBorder(style) {
354
+ const none = {
355
+ width: 0,
356
+ color: "#000000"
357
+ };
358
+ const s = style.border;
359
+ if (s && s !== "none" && s !== "0") {
360
+ const m = s.match(/([\d.]+)(?:px)?(?:\s+[^ ]+)?\s+(.+)$/);
361
+ if (m) return {
362
+ width: parseFloat(m[1]) || 1,
363
+ color: color(m[2]) ?? "#000000"
364
+ };
365
+ const m2 = s.match(/([\d.]+)(?:px)?/);
366
+ if (m2) return {
367
+ width: parseFloat(m2[1]),
368
+ color: "#000000"
369
+ };
370
+ }
371
+ if (style["border-width"] && style["border-width"] !== "0" && style["border-width"] !== "none") return {
372
+ width: num(style["border-width"]) ?? 1,
373
+ color: color(style["border-color"]) ?? "#000000"
374
+ };
375
+ return none;
376
+ }
377
+ function px(style, key) {
378
+ return num(style[key]);
379
+ }
380
+ function fontSize(style) {
381
+ return num(style["font-size"]) ?? 16;
382
+ }
383
+ function fontWeight(style) {
384
+ const w = style["font-weight"];
385
+ if (w === "bold") return 700;
386
+ return num(w) ?? 400;
387
+ }
388
+ function lineHeight(style, fs) {
389
+ const lh = style["line-height"];
390
+ const n = num(lh);
391
+ if (n != null) return n;
392
+ if (lh != null && !lh.endsWith("px")) return parseFloat(lh) * fs;
393
+ return fs * 1.4;
394
+ }
395
+ function displayFlex(style) {
396
+ return (style.display ?? "").includes("flex");
397
+ }
398
+ function flexDirection(style) {
399
+ return style["flex-direction"] === "row" ? "row" : "column";
400
+ }
401
+ function gapValue(style) {
402
+ return num(style.gap) ?? num(style["row-gap"]) ?? 0;
403
+ }
404
+ function textAlign(style) {
405
+ const a = style["text-align"];
406
+ if (a === "center") return "center";
407
+ if (a === "right") return "right";
408
+ return "left";
409
+ }
410
+ function estTextWidth(text, fs) {
411
+ let w = 0;
412
+ for (const ch of text) if (ch.charCodeAt(0) > 11904) w += fs;
413
+ else w += fs * .55;
414
+ return w;
415
+ }
416
+ function collectText(node) {
417
+ if (node.type === "text") return node.data;
418
+ if (isTag(node)) {
419
+ if (node.tagName === "br") return "\n";
420
+ return node.children.map(collectText).join("");
421
+ }
422
+ return "";
423
+ }
424
+ function trimCollapse(text) {
425
+ return text.replace(/\s+/g, " ").trim();
426
+ }
427
+ function parseBox(parent, root) {
428
+ const style = parseStyle(parent.attribs.style);
429
+ const box = {
430
+ tag: parent.tagName,
431
+ style,
432
+ children: [],
433
+ isText: false,
434
+ x: 0,
435
+ y: 0,
436
+ w: 0,
437
+ h: 0
438
+ };
439
+ if (parent.tagName === "img") {
440
+ box.w = px(style, "width") ?? 120;
441
+ box.h = px(style, "height") ?? 120;
442
+ return box;
443
+ }
444
+ for (const child of parent.children) {
445
+ if (child.type === "text") {
446
+ const t = trimCollapse(child.data);
447
+ if (!t) continue;
448
+ const last = box.children[box.children.length - 1];
449
+ if (last?.isText) last.text = (last.text ?? "") + t;
450
+ else box.children.push({
451
+ tag: "#text",
452
+ text: t,
453
+ style: inheritTextStyle(style),
454
+ children: [],
455
+ isText: true,
456
+ x: 0,
457
+ y: 0,
458
+ w: 0,
459
+ h: 0
460
+ });
461
+ continue;
462
+ }
463
+ if (!isTag(child)) continue;
464
+ if (SKIP_TAGS.has(child.tagName)) continue;
465
+ if (child.tagName === "br") continue;
466
+ box.children.push(parseBox(child, false));
467
+ }
468
+ if (root && box.children.length === 0) {
469
+ const t = trimCollapse(parent.children.map(collectText).join(""));
470
+ if (t) box.children.push({
471
+ tag: "#text",
472
+ text: t,
473
+ style: inheritTextStyle(style),
474
+ children: [],
475
+ isText: true,
476
+ x: 0,
477
+ y: 0,
478
+ w: 0,
479
+ h: 0
480
+ });
481
+ }
482
+ return box;
483
+ }
484
+ function inheritTextStyle(parent) {
485
+ const out = {};
486
+ for (const k of [
487
+ "color",
488
+ "font-size",
489
+ "font-weight",
490
+ "font-family",
491
+ "line-height",
492
+ "text-align",
493
+ "letter-spacing"
494
+ ]) if (parent[k] != null) out[k] = parent[k];
495
+ return out;
496
+ }
497
+ function layout(box, maxWidth) {
498
+ const style = box.style;
499
+ const pad = parsePadding(style);
500
+ const margin = parseMargin(style);
501
+ const border = parseBorder(style);
502
+ const innerW = Math.max(0, maxWidth - pad.left - pad.right - border.width * 2);
503
+ if (box.tag === "img") {
504
+ box.w = px(style, "width") ?? 120;
505
+ box.h = px(style, "height") ?? 120;
506
+ return {
507
+ width: box.w + margin.left + margin.right,
508
+ height: box.h + margin.top + margin.bottom
509
+ };
510
+ }
511
+ let contentW = innerW;
512
+ let contentH = 0;
513
+ if (box.isText) {
514
+ const fs = fontSize(style);
515
+ const lines = (box.text ?? "").split("\n").map((l) => l.trim()).filter(Boolean);
516
+ box.w = Math.min(innerW, Math.max(...lines.map((l) => estTextWidth(l, fs)), fs));
517
+ box.h = lines.length * lineHeight(style, fs);
518
+ contentH = box.h;
519
+ } else {
520
+ const flex = displayFlex(style);
521
+ const direction = flexDirection(style);
522
+ const gap = gapValue(style);
523
+ const explicitW = px(style, "width");
524
+ const explicitH = px(style, "height");
525
+ if (explicitW != null) contentW = Math.max(0, explicitW - pad.left - pad.right - border.width * 2);
526
+ if (flex && direction === "row") {
527
+ let x = 0;
528
+ let rowH = 0;
529
+ for (const child of box.children) {
530
+ const r = layout(child, contentW - x);
531
+ child.x = x + pad.left + border.width;
532
+ child.y = pad.top + border.width;
533
+ if (child.isText && textAlign(child.style) !== "left") child.w = contentW - x;
534
+ x += r.width;
535
+ x += gap;
536
+ rowH = Math.max(rowH, r.height);
537
+ }
538
+ contentH = rowH;
539
+ box.w = x - (box.children.length ? gap : 0);
540
+ } else {
541
+ let y = 0;
542
+ let maxW = 0;
543
+ for (const child of box.children) {
544
+ const r = layout(child, contentW);
545
+ child.x = pad.left + border.width;
546
+ child.y = y + pad.top + border.width;
547
+ if (child.isText && textAlign(child.style) !== "left") child.w = contentW;
548
+ y += r.height;
549
+ y += gap;
550
+ maxW = Math.max(maxW, r.width);
551
+ }
552
+ contentH = y - (box.children.length ? gap : 0);
553
+ box.w = maxW;
554
+ }
555
+ box.w = explicitW ?? box.w;
556
+ box.h = explicitH ?? contentH;
557
+ contentH = explicitH ?? contentH;
558
+ }
559
+ const padW = pad.left + pad.right + border.width * 2;
560
+ const padH = pad.top + pad.bottom + border.width * 2;
561
+ if (px(style, "width") == null) box.w += padW;
562
+ if (px(style, "height") == null && !box.isText) box.h += padH;
563
+ return {
564
+ width: box.w + margin.left + margin.right,
565
+ height: box.h + margin.top + margin.bottom
566
+ };
567
+ }
568
+ function applyMarginOffset(box) {
569
+ const margin = parseMargin(box.style);
570
+ box.x += margin.left;
571
+ box.y += margin.top;
572
+ }
573
+ function emitSvg(box, rootWidth, rootHeight) {
574
+ const parts = [];
575
+ emit(box, parts, 0, 0);
576
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${rootWidth}" height="${rootHeight}" viewBox="0 0 ${rootWidth} ${rootHeight}">${parts.join("")}</svg>`;
577
+ }
578
+ function emit(box, parts, ox, oy) {
579
+ const style = box.style;
580
+ const x = ox + box.x;
581
+ const y = oy + box.y;
582
+ const w = box.w;
583
+ const h = box.h;
584
+ if (box.isText) {
585
+ const fs = fontSize(style);
586
+ const fill = color(style.color, "#000000");
587
+ const family = style["font-family"] ?? "sans-serif";
588
+ const weight = fontWeight(style);
589
+ const align = textAlign(style);
590
+ const anchor = align === "center" ? "middle" : align === "right" ? "end" : "start";
591
+ const tx = align === "center" ? x + w / 2 : align === "right" ? x + w : x;
592
+ const lineH = lineHeight(style, fs);
593
+ (box.text ?? "").split("\n").filter((l) => l.trim()).forEach((line, i) => {
594
+ parts.push(`<text x="${tx.toFixed(1)}" y="${(y + lineH * i + fs).toFixed(1)}" font-size="${fs}" font-family="${family}" font-weight="${weight}" fill="${fill}" text-anchor="${anchor}">${escapeXml(line)}</text>`);
595
+ });
596
+ return;
597
+ }
598
+ const bg = color(style.background ?? style["background-color"], box.tag === "img" ? FALLBACK_BG : void 0);
599
+ const border = parseBorder(style);
600
+ const radius = num(style["border-radius"]) ?? 0;
601
+ const visible = bg && bg !== "none";
602
+ if (box.tag === "img" || visible || border.width > 0) {
603
+ const attrs = [
604
+ `x="${x.toFixed(1)}"`,
605
+ `y="${y.toFixed(1)}"`,
606
+ `width="${Math.max(0, w).toFixed(1)}"`,
607
+ `height="${Math.max(0, h).toFixed(1)}"`
608
+ ];
609
+ if (radius > 0) attrs.push(`rx="${radius}"`);
610
+ if (visible) attrs.push(`fill="${bg}"`);
611
+ if (border.width > 0) attrs.push(`stroke="${border.color}" stroke-width="${border.width}"`);
612
+ parts.push(`<rect ${attrs.join(" ")} />`);
613
+ }
614
+ for (const child of box.children) {
615
+ applyMarginOffset(child);
616
+ emit(child, parts, x, y);
617
+ }
618
+ }
619
+ function escapeXml(s) {
620
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
621
+ }
622
+ function htmlToSvg(html) {
623
+ const rootEls = parseDocument(html, { decodeEntities: true }).children.filter((n) => isTag(n));
624
+ const bodyEl = rootEls.find((el) => el.tagName === "body") ?? rootEls[0];
625
+ if (!bodyEl) return `<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1" viewBox="0 0 1 1"></svg>`;
626
+ const root = parseBox(bodyEl, true);
627
+ const rootStyle = parseStyle(bodyEl.attribs.style);
628
+ const explicitW = px(rootStyle, "width");
629
+ const explicitH = px(rootStyle, "height");
630
+ const l = layout(root, explicitW ?? 800);
631
+ const width = explicitW ?? Math.min(l.width, 1600);
632
+ const height = explicitH ?? l.height;
633
+ root.x = 0;
634
+ root.y = 0;
635
+ if (explicitW == null) root.w = width;
636
+ if (explicitH == null) root.h = height;
637
+ return emitSvg(root, width, height);
638
+ }
639
+ //#endregion
640
+ //#region src/index.ts
641
+ var PORT = Number(process.env.TEXT_TO_DESIGN_MCP_PORT ?? 47812);
642
+ var HTTP_PORT = Number(process.env.TEXT_TO_DESIGN_MCP_HTTP_PORT ?? 47820);
643
+ var SERVER_NAME = "text-to-design-mcp-server";
644
+ var SERVER_VERSION = "0.0.1";
645
+ var IDLE_TIMEOUT_MS = 3e5;
646
+ var DAEMON_WAIT_MS = 5e3;
647
+ var DAEMON_POLL_MS = 250;
648
+ var bridge = new Bridge();
649
+ function text(content) {
650
+ return { content: [{
651
+ type: "text",
652
+ text: typeof content === "string" ? content : JSON.stringify(content, null, 2)
653
+ }] };
654
+ }
655
+ function err(e) {
656
+ return { content: [{
657
+ type: "text",
658
+ text: `错误: ${e instanceof Error ? e.message : String(e)}`
659
+ }] };
660
+ }
661
+ function buildServer() {
662
+ const server = new McpServer({
663
+ name: SERVER_NAME,
664
+ version: SERVER_VERSION
665
+ }, { supportedProtocolVersions: ["2026-07-28", ...SUPPORTED_PROTOCOL_VERSIONS] });
666
+ server.registerTool("text_to_design_ping", { description: "检查 jsDesign 插件是否在线(需先启动插件并保持运行)" }, async () => {
667
+ try {
668
+ await bridge.request("ping", {});
669
+ return text({ connected: true });
670
+ } catch (e) {
671
+ return text({
672
+ connected: false,
673
+ error: e instanceof Error ? e.message : String(e)
674
+ });
675
+ }
676
+ });
677
+ server.registerTool("text_to_design_get_selection", { description: "获取即时设计画布当前选中的节点信息(名称/类型/尺寸/位置/填充/文本/子树结构)" }, async () => {
678
+ try {
679
+ return text(await bridge.request("get_selection", {}));
680
+ } catch (e) {
681
+ return err(e);
682
+ }
683
+ });
684
+ server.registerTool("text_to_design_execute", {
685
+ description: "在画布执行声明式设计指令。ops 为节点数组,每项: {op:\"frame\"|\"rect\"|\"ellipse\"|\"line\"|\"polygon\"|\"star\"|\"vector\"|\"text\", name?, x?, y?, w?, h?, fill?, radius?, rotation?, opacity?, stroke?, strokeWeight?, shadow?:{color,x,y,radius,spread}, gradient?:{stops:[{color,position}],angle}, pointCount?, fontSize?, fontWeight?, fontFamily?, characters?, textAlign?, lineHeight?, letterSpacing?, layout?:{mode,itemSpacing,padding}, radiusTopLeft?..., children?:[...] }。自动插入到画布中心",
686
+ inputSchema: z.object({ ops: z.array(z.any()).describe("设计指令节点树") })
687
+ }, async ({ ops }) => {
688
+ try {
689
+ return text(await bridge.request("execute", { ops }));
690
+ } catch (e) {
691
+ return err(e);
692
+ }
693
+ });
694
+ server.registerTool("text_to_design_html_to_design", {
695
+ description: "将 HTML 字符串转换为 jsDesign 设计节点(SVG 保真路线,忽略复杂样式),插入画布中心",
696
+ inputSchema: z.object({
697
+ html: z.string().describe("HTML 片段,支持内联 style"),
698
+ name: z.string().optional().describe("生成的图层名,默认 html-design")
699
+ })
700
+ }, async ({ html, name }) => {
701
+ try {
702
+ const svg = htmlToSvg(html);
703
+ return text(await bridge.request("create_svg", {
704
+ svg,
705
+ name: name ?? "html-design"
706
+ }));
707
+ } catch (e) {
708
+ return err(e);
709
+ }
710
+ });
711
+ server.registerTool("text_to_design_update_selection", {
712
+ description: "修改画布中选中的节点(可按 ids 指定,按 matchName 过滤,recursive 递归子节点)。props 支持 name/fill/x/y/w/h/cornerRadius/radiusTopLeft/radiusTopRight/radiusBottomLeft/radiusBottomRight/visible/rotation/opacity/characters/fontSize/fontWeight/fontFamily/textAlign/lineHeight/letterSpacing/stroke/strokeWeight/strokeAlign/shadow/layoutMode/itemSpacing/padding/pointCount",
713
+ inputSchema: z.object({
714
+ ids: z.array(z.string()).optional().describe("指定节点 id,缺省用当前选中"),
715
+ matchName: z.string().optional().describe("按节点 name 过滤,仅命中节点被修改"),
716
+ recursive: z.boolean().optional().describe("是否递归应用到子节点,默认 false"),
717
+ props: z.object({
718
+ name: z.string().optional(),
719
+ fill: z.string().optional().describe("十六进制颜色,如 #ff0000 或 #ff000080(带透明度)"),
720
+ x: z.number().optional(),
721
+ y: z.number().optional(),
722
+ w: z.number().optional(),
723
+ h: z.number().optional(),
724
+ cornerRadius: z.number().optional(),
725
+ radiusTopLeft: z.number().optional(),
726
+ radiusTopRight: z.number().optional(),
727
+ radiusBottomLeft: z.number().optional(),
728
+ radiusBottomRight: z.number().optional(),
729
+ visible: z.boolean().optional(),
730
+ rotation: z.number().optional(),
731
+ opacity: z.number().optional(),
732
+ characters: z.string().optional(),
733
+ fontSize: z.number().optional(),
734
+ fontWeight: z.number().optional(),
735
+ fontFamily: z.string().optional(),
736
+ textAlign: z.enum([
737
+ "LEFT",
738
+ "CENTER",
739
+ "RIGHT",
740
+ "JUSTIFIED"
741
+ ]).optional(),
742
+ lineHeight: z.number().optional(),
743
+ letterSpacing: z.number().optional(),
744
+ stroke: z.string().optional().describe("描边颜色,如 #ffffff"),
745
+ strokeWeight: z.number().optional(),
746
+ strokeAlign: z.enum([
747
+ "CENTER",
748
+ "INSIDE",
749
+ "OUTSIDE"
750
+ ]).optional(),
751
+ shadow: z.object({
752
+ color: z.string().optional(),
753
+ x: z.number().optional(),
754
+ y: z.number().optional(),
755
+ radius: z.number().optional(),
756
+ spread: z.number().optional()
757
+ }).optional().describe("原生阴影(下拉阴影)"),
758
+ layoutMode: z.enum([
759
+ "NONE",
760
+ "HORIZONTAL",
761
+ "VERTICAL"
762
+ ]).optional(),
763
+ itemSpacing: z.number().optional(),
764
+ padding: z.number().optional(),
765
+ pointCount: z.number().optional()
766
+ }).describe("要修改的属性")
767
+ })
768
+ }, async ({ ids, matchName, recursive, props }) => {
769
+ try {
770
+ return text(await bridge.request("update_selection", {
771
+ ids,
772
+ matchName,
773
+ recursive,
774
+ props
775
+ }));
776
+ } catch (e) {
777
+ return err(e);
778
+ }
779
+ });
780
+ const findSchema = z.object({
781
+ name: z.string().optional().describe("按名称模糊匹配(包含)"),
782
+ type: z.string().optional().describe("节点类型,如 FRAME/RECTANGLE/TEXT/ELLIPSE/LINE/POLYGON/STAR"),
783
+ recursive: z.boolean().optional().describe("是否递归查找(默认 true)")
784
+ });
785
+ server.registerTool("text_to_design_find", {
786
+ description: "在当前页面查找节点,可按名称/类型过滤,返回序列化节点列表(最多 100 条)",
787
+ inputSchema: findSchema
788
+ }, async (params) => {
789
+ try {
790
+ return text(await bridge.request("find", params));
791
+ } catch (e) {
792
+ return err(e);
793
+ }
794
+ });
795
+ server.registerTool("text_to_design_set_selection", {
796
+ description: "设置画布当前选中节点(传入节点 ids)",
797
+ inputSchema: z.object({ ids: z.array(z.string()).describe("要选中的节点 id 列表") })
798
+ }, async ({ ids }) => {
799
+ try {
800
+ return text(await bridge.request("set_selection", { ids }));
801
+ } catch (e) {
802
+ return err(e);
803
+ }
804
+ });
805
+ server.registerTool("text_to_design_remove", {
806
+ description: "删除节点(按 ids 或 matchName,缺省删除当前选中)",
807
+ inputSchema: z.object({
808
+ ids: z.array(z.string()).optional().describe("要删除的节点 id 列表,缺省用当前选中"),
809
+ matchName: z.string().optional().describe("按名称精确匹配过滤")
810
+ })
811
+ }, async ({ ids, matchName }) => {
812
+ try {
813
+ return text(await bridge.request("remove", {
814
+ ids,
815
+ matchName
816
+ }));
817
+ } catch (e) {
818
+ return err(e);
819
+ }
820
+ });
821
+ server.registerTool("text_to_design_clone", {
822
+ description: "复制节点到当前页面(原节点右下偏移 24px)",
823
+ inputSchema: z.object({ ids: z.array(z.string()).describe("要复制的节点 id 列表") })
824
+ }, async ({ ids }) => {
825
+ try {
826
+ return text(await bridge.request("clone", { ids }));
827
+ } catch (e) {
828
+ return err(e);
829
+ }
830
+ });
831
+ server.registerTool("text_to_design_group", {
832
+ description: "将多个节点编组(或 ungroup 取消编组)",
833
+ inputSchema: z.object({
834
+ ids: z.array(z.string()).describe("要编组的节点 id 列表"),
835
+ name: z.string().optional().describe("组名"),
836
+ ungroup: z.boolean().optional().describe("true 时取消编组")
837
+ })
838
+ }, async ({ ids, name, ungroup }) => {
839
+ try {
840
+ return text(await bridge.request("group", {
841
+ ids,
842
+ name,
843
+ ungroup
844
+ }));
845
+ } catch (e) {
846
+ return err(e);
847
+ }
848
+ });
849
+ server.registerTool("text_to_design_export", {
850
+ description: "导出节点为图片/文件,返回二进制字节。可传 savePath 落盘本地文件(推荐,配合不支持图像的模型),或 includeDataUrl 生成 base64 dataURL(供支持图像的模型查看)",
851
+ inputSchema: z.object({
852
+ ids: z.array(z.string()).describe("要导出的节点 id 列表"),
853
+ format: z.enum([
854
+ "PNG",
855
+ "JPG",
856
+ "SVG",
857
+ "PDF"
858
+ ]).optional().describe("导出格式,默认 PNG"),
859
+ scale: z.number().optional().describe("缩放倍率(PNG/JPG),默认 1"),
860
+ savePath: z.string().optional().describe("落盘文件绝对路径,如 /tmp/icon.png"),
861
+ includeDataUrl: z.boolean().optional().describe("是否同时返回 base64 dataURL,默认 false")
862
+ })
863
+ }, async ({ ids, format, scale, savePath, includeDataUrl }) => {
864
+ try {
865
+ const exportsMap = (await bridge.request("export", {
866
+ ids,
867
+ format,
868
+ scale
869
+ })).exports ?? {};
870
+ const results = [];
871
+ for (const [nid, item] of Object.entries(exportsMap)) {
872
+ const bytes = item.bytes;
873
+ const mimeType = item.mimeType;
874
+ const out = {
875
+ id: nid,
876
+ name: item.name,
877
+ format: item.format,
878
+ mimeType,
879
+ size: bytes.byteLength
880
+ };
881
+ if (savePath) {
882
+ writeFileSync(savePath, bytes);
883
+ out.path = savePath;
884
+ }
885
+ if (includeDataUrl) out.dataUrl = `data:${mimeType};base64,${bytes.toString("base64")}`;
886
+ results.push(out);
887
+ }
888
+ return text({ exports: results });
889
+ } catch (e) {
890
+ return err(e);
891
+ }
892
+ });
893
+ server.registerTool("text_to_design_fill_image", {
894
+ description: "将本地图片文件字节填充到指定节点(IMAGE fill)。MCP server 读取本地文件,经二进制通道传给插件,插件调用 createImage 后填入节点",
895
+ inputSchema: z.object({
896
+ ids: z.array(z.string()).describe("要填充图片的节点 id 列表"),
897
+ sourcePath: z.string().describe("本地图片文件绝对路径,如 /tmp/poster.png")
898
+ })
899
+ }, async ({ ids, sourcePath }) => {
900
+ try {
901
+ let bytes;
902
+ try {
903
+ bytes = readFileSync(sourcePath);
904
+ } catch (e) {
905
+ return err(/* @__PURE__ */ new Error(`读取文件失败: ${e instanceof Error ? e.message : String(e)}`));
906
+ }
907
+ return text(await bridge.request("fill_image", {
908
+ ids,
909
+ bytes: new Uint8Array(bytes)
910
+ }));
911
+ } catch (e) {
912
+ return err(e);
913
+ }
914
+ });
915
+ server.registerTool("text_to_design_list_fonts", { description: "列出当前环境可用字体族" }, async () => {
916
+ try {
917
+ return text(await bridge.request("list_fonts", {}));
918
+ } catch (e) {
919
+ return err(e);
920
+ }
921
+ });
922
+ return server;
923
+ }
924
+ /** 探测 47820:已有 text-to-design daemon → 返回代理客户端;外来 MCP 服务 → 'foreign';无 → 'none' */
925
+ async function probeUpstream() {
926
+ const client = new Client({
927
+ name: "text-to-design-proxy",
928
+ version: SERVER_VERSION
929
+ }, { versionNegotiation: { mode: "auto" } });
930
+ try {
931
+ await client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${HTTP_PORT}/mcp`)));
932
+ const { tools } = await client.listTools();
933
+ if (tools.length === 0 || !tools.every((t) => t.name.startsWith("text_to_design_"))) {
934
+ await client.close();
935
+ return { state: "foreign" };
936
+ }
937
+ return {
938
+ state: "proxy",
939
+ client
940
+ };
941
+ } catch {
942
+ await client.close().catch(() => {});
943
+ return { state: "none" };
944
+ }
945
+ }
946
+ /** shim 模式:本进程 stdio 透传到 daemon 的 HTTP 端点,不启 WS */
947
+ async function serveProxy(client) {
948
+ const { tools } = await client.listTools();
949
+ const stdioHandle = serveStdio(() => {
950
+ const server = new McpServer({
951
+ name: SERVER_NAME,
952
+ version: SERVER_VERSION
953
+ }, { supportedProtocolVersions: ["2026-07-28", ...SUPPORTED_PROTOCOL_VERSIONS] });
954
+ const register = server.registerTool.bind(server);
955
+ for (const t of tools) register(t.name, {
956
+ description: t.description,
957
+ inputSchema: fromJsonSchema(t.inputSchema)
958
+ }, async (args) => {
959
+ const res = await client.callTool({
960
+ name: t.name,
961
+ arguments: args
962
+ });
963
+ return {
964
+ content: res.content,
965
+ ...res.isError ? { isError: true } : {}
966
+ };
967
+ });
968
+ return server;
969
+ });
970
+ process.stderr.write(`[text-to-design-mcp] shim 模式: stdio → http://127.0.0.1:${HTTP_PORT}/mcp (共享 daemon)\n`);
971
+ process.on("SIGINT", async () => {
972
+ await stdioHandle.close();
973
+ await client.close();
974
+ process.exit(0);
975
+ });
976
+ }
977
+ /** detached 拉起 daemon(独立常驻,不受本会话生命周期影响) */
978
+ function spawnDaemon() {
979
+ const child = spawn(process.execPath, [...process.execArgv, ...process.argv.slice(1)], {
980
+ detached: true,
981
+ stdio: "ignore",
982
+ env: {
983
+ ...process.env,
984
+ TEXT_TO_DESIGN_MCP_ROLE: "daemon"
985
+ }
986
+ });
987
+ child.unref();
988
+ child.on("error", (e) => {
989
+ process.stderr.write(`[text-to-design-mcp] 拉起 daemon 失败: ${e.message}\n`);
990
+ });
991
+ }
992
+ /** daemon 模式:WS 桥(插件) + HTTP MCP(各会话 shim 连接),无 stdio,空闲自退 */
993
+ async function runDaemon() {
994
+ await bridge.start(PORT);
995
+ process.stderr.write(`[text-to-design-mcp] daemon: 插件 WS ws://localhost:${bridge.port}\n`);
996
+ const handler = createMcpHandler(buildServer);
997
+ const nodeHandler = toNodeHandler(handler);
998
+ const validateHost = localhostHostValidation();
999
+ const validateOrigin = localhostOriginValidation();
1000
+ let httpServer = null;
1001
+ let lastActivity = Date.now();
1002
+ await new Promise((resolve, reject) => {
1003
+ httpServer = createServer((req, res) => {
1004
+ lastActivity = Date.now();
1005
+ if (!validateHost(req, res) || !validateOrigin(req, res)) return;
1006
+ nodeHandler(req, res);
1007
+ });
1008
+ httpServer.once("error", reject);
1009
+ httpServer.listen(HTTP_PORT, "127.0.0.1", () => resolve());
1010
+ });
1011
+ process.stderr.write(`[text-to-design-mcp] daemon: MCP HTTP http://127.0.0.1:${HTTP_PORT}/mcp (opencode 会话经 shim 连接)\n`);
1012
+ process.stderr.write(`[text-to-design-mcp] daemon 就绪,${IDLE_TIMEOUT_MS / 6e4} 分钟无请求自动退出\n`);
1013
+ const idleTimer = setInterval(() => {
1014
+ if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) {
1015
+ process.stderr.write("[text-to-design-mcp] daemon 空闲超时,自动退出\n");
1016
+ clearInterval(idleTimer);
1017
+ handler.close();
1018
+ bridge.stop();
1019
+ httpServer?.close();
1020
+ process.exit(0);
1021
+ }
1022
+ }, 6e4);
1023
+ process.on("SIGINT", () => {
1024
+ clearInterval(idleTimer);
1025
+ handler.close();
1026
+ bridge.stop();
1027
+ httpServer?.close();
1028
+ process.exit(0);
1029
+ });
1030
+ }
1031
+ /** shim 模式:探测 daemon;无则拉起并等待就绪 */
1032
+ async function runShim() {
1033
+ const probe = await probeUpstream();
1034
+ if (probe.state === "foreign") {
1035
+ process.stderr.write(`[text-to-design-mcp] 错误: 端口 ${HTTP_PORT} 被非 text-to-design MCP 服务占用,请先释放。\n`);
1036
+ process.exit(1);
1037
+ } else if (probe.state === "proxy") {
1038
+ await serveProxy(probe.client);
1039
+ return;
1040
+ }
1041
+ process.stderr.write("[text-to-design-mcp] 未发现 daemon,自动拉起...\n");
1042
+ spawnDaemon();
1043
+ const deadline = Date.now() + DAEMON_WAIT_MS;
1044
+ while (Date.now() < deadline) {
1045
+ await delay(DAEMON_POLL_MS);
1046
+ const retry = await probeUpstream();
1047
+ if (retry.state === "proxy") {
1048
+ await serveProxy(retry.client);
1049
+ return;
1050
+ }
1051
+ if (retry.state === "foreign") {
1052
+ process.stderr.write(`[text-to-design-mcp] 错误: 端口 ${HTTP_PORT} 被非 text-to-design MCP 服务占用,请先释放。\n`);
1053
+ process.exit(1);
1054
+ }
1055
+ }
1056
+ process.stderr.write(`[text-to-design-mcp] 错误: daemon 启动超时(${DAEMON_WAIT_MS / 1e3}s),请检查残留进程后重试。\n`);
1057
+ process.exit(1);
1058
+ }
1059
+ function delay(ms) {
1060
+ return new Promise((resolve) => setTimeout(resolve, ms));
1061
+ }
1062
+ if (process.env.TEXT_TO_DESIGN_MCP_ROLE === "daemon" || process.argv.includes("daemon")) runDaemon().catch((e) => {
1063
+ bridge.stop();
1064
+ process.stderr.write(`[text-to-design-mcp] daemon 启动失败: ${e instanceof Error ? e.message : String(e)}\n`);
1065
+ process.exit(1);
1066
+ });
1067
+ else runShim().catch((e) => {
1068
+ process.stderr.write(`[text-to-design-mcp] shim 启动失败: ${e instanceof Error ? e.message : String(e)}\n`);
1069
+ process.exit(1);
1070
+ });
1071
+ //#endregion
1072
+ export {};
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "text-to-design-mcp",
3
+ "version": "0.1.0",
4
+ "description": "MCP server bridging AI clients to the jsDesign (即时设计) desktop plugin via a local WebSocket",
5
+ "type": "module",
6
+ "bin": {
7
+ "text-to-design-mcp": "dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "README.md"
12
+ ],
13
+ "engines": {
14
+ "node": ">=20.0.0"
15
+ },
16
+ "license": "MIT",
17
+ "scripts": {
18
+ "build": "vite build --ssr src/index.ts",
19
+ "prepublishOnly": "pnpm build",
20
+ "start": "node dist/index.js",
21
+ "start:dev": "tsx src/index.ts",
22
+ "typecheck": "tsc --noEmit"
23
+ },
24
+ "dependencies": {
25
+ "@modelcontextprotocol/client": "^2.0.0",
26
+ "@modelcontextprotocol/node": "^2.0.0",
27
+ "@modelcontextprotocol/server": "^2.0.0",
28
+ "domhandler": "^5.0.3",
29
+ "htmlparser2": "^10.0.0",
30
+ "ws": "^8.21.1",
31
+ "zod": "^4.4.3"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^24.13.3",
35
+ "@types/ws": "^8.18.1",
36
+ "tsx": "^4.20.0",
37
+ "typescript": "^7.0.2",
38
+ "vite": "^8.2.0"
39
+ }
40
+ }