text-to-design-mcp 0.1.0 → 0.2.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 +114 -51
  2. package/dist/index.js +289 -36
  3. package/package.json +5 -1
package/README.md CHANGED
@@ -1,88 +1,151 @@
1
- # text-to-design-mcp
1
+ # text-to-design 后台服务
2
2
 
3
- MCP(MCP Model Context Protocol)server:把 AI 客户端桥接到 jsDesign(即时设计)桌面插件。
3
+ 让 AI 助手直接帮你操作即时设计(jsDesign)画布:读取选中内容、按描述画图、改样式、导出图片。装好后不用手动启动任何东西,打开 AI 工具就能用。
4
4
 
5
- 采用生态主流形态:**共享 daemon + 每会话薄 shim**(同 chrome-devtools-mcp 模型)。
5
+ 这里说的「后台服务」,就是负责在 AI 和设计软件插件之间传话的那个小帮手。
6
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
- ```
7
+ ## 能做什么
13
8
 
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、同一插件连接
9
+ - 读取画布当前选中的内容
10
+ - 按你的描述画图:卡片、按钮、文字、形状等
11
+ - 修改已有内容:改位置、颜色、文字、圆角
12
+ - 把多个元素合成一个图形、给图形加轮廓
13
+ - 把图形变成可反复复用的组件
14
+ - 导出图片(PNG / JPG / SVG / PDF)
15
+ - 用本地图片填充图形
20
16
 
21
- 自愈闭环:daemon 空闲退出 → 插件 1s 轮询重连 → 新会话自动拉起新 daemon。
17
+ ## 安装(三步)
22
18
 
23
- ## 快速开始
19
+ **第一步:安装后台服务**(任选一种包管理器)
24
20
 
25
- **前提**:先安装并运行 jsDesign 插件侧(插件代码在仓库内):
21
+ | 管理器 | 命令 |
22
+ | --- | --- |
23
+ | npm | `npm i -g text-to-design-mcp` |
24
+ | pnpm | `pnpm add -g text-to-design-mcp` |
25
+ | yarn | `yarn global add text-to-design-mcp` |
26
26
 
27
- 1. `pnpm install && pnpm build`(构建插件包 `packages/ui/dist/`,含 `ui.html` + `code.js` + `manifest.json`)
28
- 2. jsDesign 客户端 →「插件」→「创建/添加插件」→ 选择仓库根目录的 `manifest.json`
29
- 3. 画布内「运行插件」,UI 面板出现且显示「已连接」即就绪
27
+ **第二步:安装设计软件插件**
30
28
 
31
- **无需手动启动 server**:opencode 打开会话时自动 spawn shim,shim 自动拉起 daemon。插件先运行、会话后开顺序更佳(插件 1s 轮询会自动连上)。
29
+ 先拿到插件包(任选):
32
30
 
33
- ## 客户端配置
31
+ | 管理器 | 命令 |
32
+ | --- | --- |
33
+ | npm | `npm pack text-to-design-ui` |
34
+ | pnpm | `pnpm pack text-to-design-ui` |
35
+ | yarn | `yarn dlx npm pack text-to-design-ui` |
34
36
 
35
- 以 opencode 为例(`opencode.json`),用 `type: local` 由 opencode 自动拉起:
37
+ 解压得到的安装包里有个 `dist` 文件夹。在即时设计里点「插件 → 导入」,选择里面的 `manifest.json`,然后回到画布运行插件。面板显示「已连接」就是准备好了。
38
+
39
+ **第三步:告诉 AI 工具**
40
+
41
+ 在项目根目录的 `opencode.json`(没有就新建)里加:
36
42
 
37
43
  ```json
38
44
  {
39
45
  "mcp": {
40
46
  "text-to-design": {
41
47
  "type": "local",
42
- "command": ["pnpm", "run", "mcp"],
48
+ "command": ["text-to-design-mcp"],
43
49
  "enabled": true
44
50
  }
45
51
  }
46
52
  }
47
53
  ```
48
54
 
49
- ## 环境变量
55
+ (没做全局安装的话,把 command 换成 `["npx", "text-to-design-mcp"]` 也可以)
50
56
 
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` 观察) |
57
+ 改完重启 AI 工具会话。
58
+
59
+ ## 怎么用
60
+
61
+ 打开会话后直接说人话,比如:
62
+
63
+ - 「读取当前画布选中的内容」
64
+ - 「在画布中心画一个 300x200 的卡片,标题叫发布页,背景浅灰」
65
+ - 「把选中的按钮导出成 PNG 存到 /tmp/btn.png」
66
+
67
+ 想确认插件通不通,先让它调 `text_to_design_ping`。
68
+
69
+ ## 常见问题
70
+
71
+ - **AI 说连不上插件**:看即时设计里的插件面板是不是「已连接」,没有就重新运行插件,再重启 AI 会话
72
+ - **改了配置没反应**:重启 AI 工具会话
73
+ - **想深入排查**:看文末「给开发者看」的日志部分
74
+ - **旧版升级见下方「升级」**
56
75
 
57
- ## daemon 生命周期
76
+ ## 升级
58
77
 
59
- - 由第一个 shim 自动拉起(detached,不随会话退出)
60
- - 空闲 5 分钟无 HTTP 请求自动退出;插件连接不影响该计时(插件会自动重连)
61
- - 手动清理:`pkill -f "index.ts daemon"`
78
+ 新版起会自动替换:启动时若检测到旧版常驻服务,会自动关停并拉起新版,无需手动操作。
62
79
 
63
- ## 工具
80
+ 仅从旧版(没有自动替换能力)升级时,首次需手动清理一次残留的常驻服务:
64
81
 
65
- | 工具 | 说明 |
82
+ ```bash
83
+ pkill -f text-to-design-mcp
84
+ ```
85
+
86
+ 之后任意一次 AI 调用会自动拉起新版服务。
87
+
88
+ ---
89
+
90
+ ## 给开发者看
91
+
92
+ 以下内容供开发、排查问题的人参考。
93
+
94
+ ### 完整工具清单
95
+
96
+ | 工具 | 用途 |
66
97
  | --- | --- |
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` | 修改选中节点属性(含原生阴影/描边/文本样式/细分圆角) |
98
+ | `text_to_design_ping` | 检查插件是否在线 |
99
+ | `text_to_design_get_selection` | 读取画布当前选中的节点 |
100
+ | `text_to_design_execute` | 按描述创建节点(frame/rect/text 等,支持阴影/描边/渐变/文本样式) |
101
+ | `text_to_design_create_svg` | 直接导入 SVG 字符串(保留 path/矢量数据,不经降级) |
102
+ | `text_to_design_html_to_design` | 把 HTML 转成设计节点 |
103
+ | `text_to_design_update_selection` | 修改选中节点的属性(位置/颜色/文字/圆角等) |
72
104
  | `text_to_design_find` | 按名称/类型查找节点 |
73
105
  | `text_to_design_set_selection` | 设置画布选中节点 |
74
- | `text_to_design_remove` | 删除节点(按 ids/名称/选中) |
106
+ | `text_to_design_remove` | 删除节点 |
75
107
  | `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) |
108
+ | `text_to_design_group` | 编组 / 取消编组 |
109
+ | `text_to_design_flatten` | 把多个节点合并成单个矢量 |
110
+ | `text_to_design_outline_stroke` | 把节点描边转成矢量轮廓 |
111
+ | `text_to_design_reparent` | 移动节点到目标父节点下 |
112
+ | `text_to_design_create_component` | 把节点固化成组件 |
113
+ | `text_to_design_create_instance` | 从组件创建实例 |
114
+ | `text_to_design_swap_component` | 交换实例的组件 |
115
+ | `text_to_design_set_instance_properties` | 设置实例的变体属性 |
116
+ | `text_to_design_import_component` | 按 key 从团队库导入组件 |
117
+ | `text_to_design_combine_as_variants` | 把多个组件合并成组件集 |
118
+ | `text_to_design_detach_instance` | 解绑实例为普通帧 |
119
+ | `text_to_design_export` | 导出节点为 PNG/JPG/SVG/PDF |
120
+ | `text_to_design_list_fonts` | 列出可用字体 |
121
+ | `text_to_design_fill_image` | 用本地图片填充节点 |
122
+
123
+ ### 工作原理(简版)
124
+
125
+ - 一个常驻的轻量服务负责和插件通信,连接即时设计里的插件
126
+ - 每个 AI 会话会自动连上这个服务;会话关掉不影响插件
127
+ - 服务常驻;更新版本时自动替换,无需手动清理(旧版首次升级除外,见「升级」)
128
+ - 多个会话可以同时用,共享同一个插件连接
129
+
130
+ ### 环境变量
131
+
132
+ | 变量 | 默认 | 说明 |
133
+ | --- | --- | --- |
134
+ | `TEXT_TO_DESIGN_MCP_PORT` | `47812` | 与插件通信的端口(被占用会启动失败) |
135
+ | `TEXT_TO_DESIGN_MCP_HTTP_PORT` | `47820` | 内部服务端口(一般不用动) |
136
+ | `TEXT_TO_DESIGN_MCP_LOG` | `/tmp/text-to-design-mcp.log` | 日志文件路径 |
137
+ | `TEXT_TO_DESIGN_MCP_LOG_LEVEL` | `info` | 日志级别:`debug`/`info`/`warn`/`error` |
138
+
139
+ ### 日志排查
140
+
141
+ - 看日志:`tail -f /tmp/text-to-design-mcp.log`(请求/响应耗时、HTTP 状态码、插件连接、二进制组装都会记)
142
+ - 要更细的连接日志,启动时设 `TEXT_TO_DESIGN_MCP_LOG_LEVEL=debug`(默认 info)
143
+ - 插件面板自带连接状态和日志,也能帮定位
80
144
 
81
- ## 开发
145
+ ### 构建与开发
82
146
 
83
147
  ```bash
84
148
  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
149
+ pnpm dev # watch 构建 ui/code
150
+ pnpm mcp # 开发态启动后台服务(tsx 直跑)
88
151
  ```
package/dist/index.js CHANGED
@@ -10,14 +10,31 @@ import { z } from "zod";
10
10
  import { WebSocket, WebSocketServer } from "ws";
11
11
  import { isTag } from "domhandler";
12
12
  import { parseDocument } from "htmlparser2";
13
+ //#region package.json
14
+ var version = "0.2.0";
15
+ //#endregion
13
16
  //#region src/logger.ts
14
17
  var FILE = process.env.TEXT_TO_DESIGN_MCP_LOG ?? "/tmp/text-to-design-mcp.log";
18
+ var LEVEL_ORDER = {
19
+ debug: 0,
20
+ info: 1,
21
+ warn: 2,
22
+ error: 3
23
+ };
24
+ var LEVEL = process.env.TEXT_TO_DESIGN_MCP_LOG_LEVEL ?? "info";
15
25
  /** 追加一行日志到文件(daemon detached + stdio ignored,stderr 不可见,必须落盘) */
16
- function log(line) {
26
+ function write(level, line) {
27
+ if (LEVEL_ORDER[level] < LEVEL_ORDER[LEVEL]) return;
17
28
  try {
18
- appendFileSync(FILE, `${(/* @__PURE__ */ new Date()).toISOString()} [text-to-design-mcp] ${line}\n`);
29
+ appendFileSync(FILE, `${(/* @__PURE__ */ new Date()).toISOString()} [${level.toUpperCase()}] [text-to-design-mcp] ${line}\n`);
19
30
  } catch {}
20
31
  }
32
+ function log(line) {
33
+ write("info", line);
34
+ }
35
+ function debug(line) {
36
+ write("debug", line);
37
+ }
21
38
  //#endregion
22
39
  //#region src/pending.ts
23
40
  var DEFAULT_TIMEOUT = 3e4;
@@ -49,19 +66,22 @@ var PendingManager = class {
49
66
  params
50
67
  };
51
68
  return new Promise((resolve, reject) => {
69
+ const startedAt = Date.now();
52
70
  const timer = setTimeout(() => {
53
71
  this.pending.delete(id);
54
- log(`请求超时: ${id} ${method}`);
72
+ log(`请求超时: ${id} ${method} 耗时=${Date.now() - startedAt}ms`);
55
73
  reject(/* @__PURE__ */ new Error(`请求超时: ${method}`));
56
74
  }, timeout);
57
75
  this.pending.set(id, {
58
76
  id,
77
+ method,
59
78
  resolve,
60
79
  reject,
61
80
  timer,
62
81
  waitBinary: false,
63
82
  binaryCount: 0,
64
- buffers: []
83
+ buffers: [],
84
+ startedAt
65
85
  });
66
86
  log(`发出请求: ${id} ${method}${binary != null ? ` +binary(${binary.byteLength}B)` : ""}`);
67
87
  this.sendFn(JSON.stringify(payload), binary != null ? Buffer.from(binary) : void 0);
@@ -100,12 +120,13 @@ var PendingManager = class {
100
120
  log(`二进制响应开始: id=${msg.id} count=${msg.binaryCount ?? 1}`);
101
121
  pending.waitBinary = true;
102
122
  pending.binaryCount = msg.binaryCount ?? 1;
123
+ pending.data = msg.data;
103
124
  this.binaryTarget = pending;
104
125
  return;
105
126
  }
106
127
  this.pending.delete(msg.id);
107
128
  clearTimeout(pending.timer);
108
- log(`匹配响应: id=${msg.id} ok=${msg.ok}${msg.ok ? "" : ` error=${msg.error ?? ""}`}`);
129
+ log(`响应: ${pending.id} ${pending.method} ok=${msg.ok} 耗时=${Date.now() - pending.startedAt}ms${msg.ok ? "" : ` error=${msg.error ?? ""}`}`);
109
130
  if (msg.ok) pending.resolve(msg.data);
110
131
  else pending.reject(new Error(msg.error ?? "plugin error"));
111
132
  }
@@ -119,7 +140,8 @@ var PendingManager = class {
119
140
  if (this.binaryTarget.buffers.length >= this.binaryTarget.binaryCount) {
120
141
  const target = this.binaryTarget;
121
142
  this.binaryTarget = null;
122
- log(`二进制组装完成: id=${target.id} ${target.buffers.length} 帧`);
143
+ const total = target.buffers.reduce((s, b) => s + b.byteLength, 0);
144
+ log(`二进制组装完成: id=${target.id} ${target.buffers.length} 帧 ${total}B 耗时=${Date.now() - target.startedAt}ms`);
123
145
  this.settle(target);
124
146
  }
125
147
  }
@@ -138,10 +160,33 @@ var PendingManager = class {
138
160
  settle(pending) {
139
161
  this.pending.delete(pending.id);
140
162
  clearTimeout(pending.timer);
141
- const data = pending.buffers.length === 1 ? pending.buffers[0] : pending.buffers;
142
- pending.resolve(data);
163
+ pending.resolve(mergeBytes(pending.data, pending.buffers));
143
164
  }
144
165
  };
166
+ /** 把二进制帧回填进 meta 结构(按帧序与插入序一一对应),兜底返回裸 Buffer */
167
+ function mergeBytes(data, buffers) {
168
+ const single = buffers.length === 1 ? buffers[0] : buffers;
169
+ if (!data || typeof data !== "object") return single;
170
+ const d = data;
171
+ if (d.exports && typeof d.exports === "object") {
172
+ const exports_ = d.exports;
173
+ const out = {};
174
+ Object.entries(exports_).forEach(([k, e], i) => {
175
+ out[k] = {
176
+ ...e,
177
+ bytes: buffers[i]
178
+ };
179
+ });
180
+ return {
181
+ ...d,
182
+ exports: out
183
+ };
184
+ }
185
+ return {
186
+ ...d,
187
+ bytes: single
188
+ };
189
+ }
145
190
  //#endregion
146
191
  //#region src/transport.ts
147
192
  /** WSS/HTTP 生命周期(固定端口,被占即失败),消息透传上层 */
@@ -149,6 +194,7 @@ var Transport = class {
149
194
  wss = null;
150
195
  http = null;
151
196
  client = null;
197
+ heartbeat = null;
152
198
  _port = 0;
153
199
  onMessage = null;
154
200
  onDisconnect = null;
@@ -159,13 +205,29 @@ var Transport = class {
159
205
  this.http = createServer();
160
206
  this.wss = new WebSocketServer({ server: this.http });
161
207
  this.wss.on("error", () => {});
208
+ this.heartbeat = setInterval(() => {
209
+ if (this.client && this.client.readyState === WebSocket.OPEN) {
210
+ this.client.send(JSON.stringify({
211
+ type: "status",
212
+ state: "connected",
213
+ version
214
+ }));
215
+ debug("心跳: 下发状态确认");
216
+ }
217
+ }, 3e4);
162
218
  this.wss.on("connection", (ws) => {
163
219
  this.client = ws;
164
220
  process.stderr.write("[text-to-design-mcp] 插件已连接\n");
165
221
  log("插件已连接");
222
+ ws.send(JSON.stringify({
223
+ type: "status",
224
+ state: "connected",
225
+ version
226
+ }));
227
+ debug("已下发状态确认(status connected)");
166
228
  ws.on("message", (raw, isBinary) => {
167
229
  const buf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
168
- log(`收到 WS 消息 len=${buf.length} bin=${isBinary}`);
230
+ debug(`收到 WS 消息 len=${buf.length} bin=${isBinary}`);
169
231
  this.onMessage?.(buf, isBinary);
170
232
  });
171
233
  ws.on("close", () => {
@@ -186,6 +248,8 @@ var Transport = class {
186
248
  this._port = port;
187
249
  }
188
250
  stop() {
251
+ if (this.heartbeat) clearInterval(this.heartbeat);
252
+ this.heartbeat = null;
189
253
  this.wss?.close();
190
254
  this.http?.close();
191
255
  }
@@ -193,8 +257,10 @@ var Transport = class {
193
257
  return this.client !== null && this.client.readyState === WebSocket.OPEN;
194
258
  }
195
259
  send(data) {
196
- if (this.client && this.client.readyState === WebSocket.OPEN) this.client.send(data);
197
- else log(`发送失败: 无客户端连接(${data.length} 字节被丢弃)`);
260
+ if (this.client && this.client.readyState === WebSocket.OPEN) {
261
+ this.client.send(data);
262
+ debug(`发送 WS 消息 len=${data.length} bin=${typeof data !== "string"}`);
263
+ } else log(`发送失败: 无客户端连接(${data.length} 字节被丢弃)`);
198
264
  }
199
265
  tryListen(p) {
200
266
  return new Promise((resolve) => {
@@ -641,8 +707,7 @@ function htmlToSvg(html) {
641
707
  var PORT = Number(process.env.TEXT_TO_DESIGN_MCP_PORT ?? 47812);
642
708
  var HTTP_PORT = Number(process.env.TEXT_TO_DESIGN_MCP_HTTP_PORT ?? 47820);
643
709
  var SERVER_NAME = "text-to-design-mcp-server";
644
- var SERVER_VERSION = "0.0.1";
645
- var IDLE_TIMEOUT_MS = 3e5;
710
+ var SERVER_VERSION = version;
646
711
  var DAEMON_WAIT_MS = 5e3;
647
712
  var DAEMON_POLL_MS = 250;
648
713
  var bridge = new Bridge();
@@ -682,7 +747,7 @@ function buildServer() {
682
747
  }
683
748
  });
684
749
  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?:[...] }。自动插入到画布中心",
750
+ description: "在画布执行声明式设计指令。ops 为节点数组,每项: {op:\"frame\"|\"rect\"|\"ellipse\"|\"line\"|\"polygon\"|\"star\"|\"vector\"|\"boolean\"|\"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?:[...] }。op 为 vector 时可用 paths 传 SVG path data(单个或数组,如 \"M0 0 L100 0 L100 100 Z\",可含 windingRule);op 为 boolean 时 children 至少 2 个,booleanType 取 UNION|SUBTRACT|INTERSECT|EXCLUDE(默认 UNION)。自动插入到画布中心",
686
751
  inputSchema: z.object({ ops: z.array(z.any()).describe("设计指令节点树") })
687
752
  }, async ({ ops }) => {
688
753
  try {
@@ -691,6 +756,22 @@ function buildServer() {
691
756
  return err(e);
692
757
  }
693
758
  });
759
+ server.registerTool("text_to_design_create_svg", {
760
+ description: "将 SVG 字符串直接导入画布(原生 createNodeFromSvg,完整保留 path/矢量/渐变/描边,不经 htmlToSvg 降级)",
761
+ inputSchema: z.object({
762
+ svg: z.string().describe("完整 SVG 字符串,如 <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"100\"><path d=\"M0 0 L100 0 L100 100 Z\" fill=\"#ff0000\"/></svg>"),
763
+ name: z.string().optional().describe("生成的图层名,默认 svg-design")
764
+ })
765
+ }, async ({ svg, name }) => {
766
+ try {
767
+ return text(await bridge.request("create_svg", {
768
+ svg,
769
+ name: name ?? "svg-design"
770
+ }));
771
+ } catch (e) {
772
+ return err(e);
773
+ }
774
+ });
694
775
  server.registerTool("text_to_design_html_to_design", {
695
776
  description: "将 HTML 字符串转换为 jsDesign 设计节点(SVG 保真路线,忽略复杂样式),插入画布中心",
696
777
  inputSchema: z.object({
@@ -779,7 +860,7 @@ function buildServer() {
779
860
  });
780
861
  const findSchema = z.object({
781
862
  name: z.string().optional().describe("按名称模糊匹配(包含)"),
782
- type: z.string().optional().describe("节点类型,如 FRAME/RECTANGLE/TEXT/ELLIPSE/LINE/POLYGON/STAR"),
863
+ type: z.string().optional().describe("节点类型,如 FRAME/RECTANGLE/TEXT/ELLIPSE/LINE/POLYGON/STAR/VECTOR"),
783
864
  recursive: z.boolean().optional().describe("是否递归查找(默认 true)")
784
865
  });
785
866
  server.registerTool("text_to_design_find", {
@@ -846,6 +927,144 @@ function buildServer() {
846
927
  return err(e);
847
928
  }
848
929
  });
930
+ server.registerTool("text_to_design_flatten", {
931
+ description: "将多个节点合并为单个矢量(VectorNode),原节点被吸收",
932
+ inputSchema: z.object({ ids: z.array(z.string()).describe("要合并的节点 id 列表(至少 2 个)") })
933
+ }, async ({ ids }) => {
934
+ try {
935
+ return text(await bridge.request("flatten", { ids }));
936
+ } catch (e) {
937
+ return err(e);
938
+ }
939
+ });
940
+ server.registerTool("text_to_design_outline_stroke", {
941
+ description: "将节点描边转为矢量轮廓(outlineStroke),返回新矢量节点",
942
+ inputSchema: z.object({ ids: z.array(z.string()).describe("要转描边的节点 id 列表") })
943
+ }, async ({ ids }) => {
944
+ try {
945
+ return text(await bridge.request("outline_stroke", { ids }));
946
+ } catch (e) {
947
+ return err(e);
948
+ }
949
+ });
950
+ server.registerTool("text_to_design_reparent", {
951
+ description: "移动节点到目标父节点下(原生移动,自动脱离原父)。parentId 缺省时用当前选中第一个节点作父;index 可指定插入顺序",
952
+ inputSchema: z.object({
953
+ ids: z.array(z.string()).describe("要移动的节点 id 列表"),
954
+ parentId: z.string().optional().describe("目标父节点 id,缺省用当前选中第一个节点"),
955
+ index: z.number().optional().describe("插入位置,缺省追加到末尾")
956
+ })
957
+ }, async ({ ids, parentId, index }) => {
958
+ try {
959
+ return text(await bridge.request("reparent", {
960
+ ids,
961
+ parentId,
962
+ index
963
+ }));
964
+ } catch (e) {
965
+ return err(e);
966
+ }
967
+ });
968
+ server.registerTool("text_to_design_create_component", {
969
+ description: "将指定节点固化为组件(ComponentNode),原节点移入组件内",
970
+ inputSchema: z.object({
971
+ ids: z.array(z.string()).describe("要固化为组件的节点 id 列表"),
972
+ name: z.string().optional().describe("组件名,默认 component")
973
+ })
974
+ }, async ({ ids, name }) => {
975
+ try {
976
+ return text(await bridge.request("create_component", {
977
+ ids,
978
+ name
979
+ }));
980
+ } catch (e) {
981
+ return err(e);
982
+ }
983
+ });
984
+ server.registerTool("text_to_design_create_instance", {
985
+ description: "从组件节点创建实例(InstanceNode),放到画布中心",
986
+ inputSchema: z.object({ ids: z.array(z.string()).describe("组件(COMPONENT)节点 id 列表,每个生成一个实例") })
987
+ }, async ({ ids }) => {
988
+ try {
989
+ return text(await bridge.request("create_instance", { ids }));
990
+ } catch (e) {
991
+ return err(e);
992
+ }
993
+ });
994
+ server.registerTool("text_to_design_swap_component", {
995
+ description: "交换实例的组件(实例样式整体换成另一个组件)",
996
+ inputSchema: z.object({
997
+ ids: z.array(z.string()).describe("实例(INSTANCE)节点 id 列表"),
998
+ componentId: z.string().describe("目标组件(COMPONENT)节点 id")
999
+ })
1000
+ }, async ({ ids, componentId }) => {
1001
+ try {
1002
+ return text(await bridge.request("swap_component", {
1003
+ ids,
1004
+ componentId
1005
+ }));
1006
+ } catch (e) {
1007
+ return err(e);
1008
+ }
1009
+ });
1010
+ server.registerTool("text_to_design_set_instance_properties", {
1011
+ description: "设置实例的变体属性(如 {\"状态\":\"禁用\",\"尺寸\":\"大\"}),可选值见 find/get_selection 返回的 variantGroupProperties",
1012
+ inputSchema: z.object({
1013
+ ids: z.array(z.string()).describe("实例(INSTANCE)节点 id 列表"),
1014
+ properties: z.record(z.string(), z.string()).describe("变体属性名→值,如 {\"状态\":\"禁用\"}")
1015
+ })
1016
+ }, async ({ ids, properties }) => {
1017
+ try {
1018
+ return text(await bridge.request("set_instance_properties", {
1019
+ ids,
1020
+ properties
1021
+ }));
1022
+ } catch (e) {
1023
+ return err(e);
1024
+ }
1025
+ });
1026
+ server.registerTool("text_to_design_import_component", {
1027
+ description: "从团队库按 key 导入组件到当前页面。key 获取方式:jsDesign 编辑器中右键组件 → 复制链接/组件 Key(如 URL 里 componentKey= 或分享链接中的 key 参数)",
1028
+ inputSchema: z.object({
1029
+ key: z.string().describe("组件 Key"),
1030
+ name: z.string().optional().describe("导入后的组件名")
1031
+ })
1032
+ }, async ({ key, name }) => {
1033
+ try {
1034
+ return text(await bridge.request("import_component", {
1035
+ key,
1036
+ name
1037
+ }));
1038
+ } catch (e) {
1039
+ return err(e);
1040
+ }
1041
+ });
1042
+ server.registerTool("text_to_design_combine_as_variants", {
1043
+ description: "将多个组件合并为组件集(ComponentSetNode),生成变体后可配合 set_instance_properties 切换",
1044
+ inputSchema: z.object({
1045
+ ids: z.array(z.string()).describe("组件(COMPONENT)节点 id 列表(至少 2 个)"),
1046
+ name: z.string().optional().describe("组件集名")
1047
+ })
1048
+ }, async ({ ids, name }) => {
1049
+ try {
1050
+ return text(await bridge.request("combine_as_variants", {
1051
+ ids,
1052
+ name
1053
+ }));
1054
+ } catch (e) {
1055
+ return err(e);
1056
+ }
1057
+ });
1058
+ server.registerTool("text_to_design_detach_instance", {
1059
+ description: "解绑实例(INSTANCE → FrameNode),解绑后可自由编辑内容",
1060
+ inputSchema: z.object({ ids: z.array(z.string()).describe("实例(INSTANCE)节点 id 列表") })
1061
+ }, async ({ ids }) => {
1062
+ try {
1063
+ return text(await bridge.request("detach_instance", { ids }));
1064
+ } catch (e) {
1065
+ return err(e);
1066
+ }
1067
+ });
849
1068
  server.registerTool("text_to_design_export", {
850
1069
  description: "导出节点为图片/文件,返回二进制字节。可传 savePath 落盘本地文件(推荐,配合不支持图像的模型),或 includeDataUrl 生成 base64 dataURL(供支持图像的模型查看)",
851
1070
  inputSchema: z.object({
@@ -923,6 +1142,17 @@ function buildServer() {
923
1142
  }
924
1143
  /** 探测 47820:已有 text-to-design daemon → 返回代理客户端;外来 MCP 服务 → 'foreign';无 → 'none' */
925
1144
  async function probeUpstream() {
1145
+ const health = await fetchDaemonHealth();
1146
+ if (health && health.version !== SERVER_VERSION) {
1147
+ process.stderr.write(`[text-to-design-mcp] 检测到旧版 daemon (${health.version} → ${SERVER_VERSION}),正在替换...\n`);
1148
+ await fetch(`http://127.0.0.1:${HTTP_PORT}/shutdown`, { method: "POST" }).catch(() => {});
1149
+ const deadline = Date.now() + 2e3;
1150
+ while (Date.now() < deadline) {
1151
+ await delay(DAEMON_POLL_MS);
1152
+ if (await fetchDaemonHealth() === null) break;
1153
+ }
1154
+ return { state: "none" };
1155
+ }
926
1156
  const client = new Client({
927
1157
  name: "text-to-design-proxy",
928
1158
  version: SERVER_VERSION
@@ -943,6 +1173,20 @@ async function probeUpstream() {
943
1173
  return { state: "none" };
944
1174
  }
945
1175
  }
1176
+ /** GET daemon /health;无 /health 端点(旧版/外来服务/未启动)或失败 → null */
1177
+ async function fetchDaemonHealth() {
1178
+ try {
1179
+ const res = await fetch(`http://127.0.0.1:${HTTP_PORT}/health`, { signal: AbortSignal.timeout(800) });
1180
+ if (!res.ok) return null;
1181
+ const body = await res.json();
1182
+ return body.name && body.version ? {
1183
+ name: body.name,
1184
+ version: body.version
1185
+ } : null;
1186
+ } catch {
1187
+ return null;
1188
+ }
1189
+ }
946
1190
  /** shim 模式:本进程 stdio 透传到 daemon 的 HTTP 端点,不启 WS */
947
1191
  async function serveProxy(client) {
948
1192
  const { tools } = await client.listTools();
@@ -989,7 +1233,7 @@ function spawnDaemon() {
989
1233
  process.stderr.write(`[text-to-design-mcp] 拉起 daemon 失败: ${e.message}\n`);
990
1234
  });
991
1235
  }
992
- /** daemon 模式:WS 桥(插件) + HTTP MCP(各会话 shim 连接),无 stdio,空闲自退 */
1236
+ /** daemon 模式:WS 桥(插件) + HTTP MCP(各会话 shim 连接),无 stdio,常驻 */
993
1237
  async function runDaemon() {
994
1238
  await bridge.start(PORT);
995
1239
  process.stderr.write(`[text-to-design-mcp] daemon: 插件 WS ws://localhost:${bridge.port}\n`);
@@ -998,35 +1242,44 @@ async function runDaemon() {
998
1242
  const validateHost = localhostHostValidation();
999
1243
  const validateOrigin = localhostOriginValidation();
1000
1244
  let httpServer = null;
1001
- let lastActivity = Date.now();
1245
+ const shutdown = (reason) => {
1246
+ process.stderr.write(`[text-to-design-mcp] daemon 退出: ${reason}\n`);
1247
+ handler.close();
1248
+ bridge.stop();
1249
+ httpServer?.close();
1250
+ process.exit(0);
1251
+ };
1002
1252
  await new Promise((resolve, reject) => {
1003
1253
  httpServer = createServer((req, res) => {
1004
- lastActivity = Date.now();
1005
1254
  if (!validateHost(req, res) || !validateOrigin(req, res)) return;
1255
+ const start = Date.now();
1256
+ const url = req.url ?? "";
1257
+ res.on("finish", () => {
1258
+ log(`HTTP ${req.method} ${url} → ${res.statusCode} (${Date.now() - start}ms)`);
1259
+ });
1260
+ if (req.method === "GET" && url === "/health") {
1261
+ res.writeHead(200, { "content-type": "application/json" });
1262
+ res.end(JSON.stringify({
1263
+ name: SERVER_NAME,
1264
+ version: SERVER_VERSION,
1265
+ pid: process.pid
1266
+ }));
1267
+ return;
1268
+ }
1269
+ if (req.method === "POST" && url === "/shutdown") {
1270
+ res.writeHead(200, { "content-type": "application/json" });
1271
+ res.end(JSON.stringify({ ok: true }));
1272
+ setTimeout(() => shutdown("收到 /shutdown 请求"), 100);
1273
+ return;
1274
+ }
1006
1275
  nodeHandler(req, res);
1007
1276
  });
1008
1277
  httpServer.once("error", reject);
1009
1278
  httpServer.listen(HTTP_PORT, "127.0.0.1", () => resolve());
1010
1279
  });
1011
1280
  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
- });
1281
+ process.stderr.write(`[text-to-design-mcp] daemon 就绪,常驻运行(更新时由版本自检自动替换)\n`);
1282
+ process.on("SIGINT", () => shutdown("SIGINT"));
1030
1283
  }
1031
1284
  /** shim 模式:探测 daemon;无则拉起并等待就绪 */
1032
1285
  async function runShim() {
package/package.json CHANGED
@@ -1,7 +1,11 @@
1
1
  {
2
2
  "name": "text-to-design-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "MCP server bridging AI clients to the jsDesign (即时设计) desktop plugin via a local WebSocket",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/wzrove/text-to-design"
8
+ },
5
9
  "type": "module",
6
10
  "bin": {
7
11
  "text-to-design-mcp": "dist/index.js"