@tempad-dev/mcp 0.8.0 → 0.10.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 -4
- package/README.zh-Hans.md +6 -2
- package/dist/cli.mjs +3 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/hub.mjs +78 -66
- package/dist/hub.mjs.map +1 -1
- package/dist/{shared--YD93aQ6.mjs → shared-Dh112Muy.mjs} +96 -43
- package/dist/shared-Dh112Muy.mjs.map +1 -0
- package/package.json +5 -5
- package/dist/shared--YD93aQ6.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -28,8 +28,10 @@ Supported tools/resources:
|
|
|
28
28
|
definitions on accessible pages plus local or directly referenced variable, collection/mode,
|
|
29
29
|
style, and shader definitions without inspecting canvas usage. Cursor continuation exposes
|
|
30
30
|
omitted definitions; exact-ref lookup returns one bounded definition. `scope: "fonts"` queries
|
|
31
|
-
available font families and exact native styles without reading file resources.
|
|
32
|
-
|
|
31
|
+
available font families and exact native styles without reading file resources. `scope: "pages"`
|
|
32
|
+
lists page IDs without scanning components; a resource call with `pageId` scans only that page's
|
|
33
|
+
components while retaining file-wide variable, style, and shader definitions.
|
|
34
|
+
- `manage_design_task` (`begin`, `resume`, `complete`, `cancel`) and `set_design_anchor`: Bind canvas writes to
|
|
33
35
|
a design task, resume a paused task, place its status controls, and finish or cancel the task.
|
|
34
36
|
Stop permanently fences the old task across reconnects. Native Codex App comments support Queue
|
|
35
37
|
and Steer; confirmed admission clears submitted drafts before execution finishes. See the
|
|
@@ -50,8 +52,8 @@ Notes:
|
|
|
50
52
|
- Tool responses use a shared `64 KiB` inline budget measured on the `CallToolResult` body. When a selection is too large for the `get_code` budget, TemPad Dev may return a shell response instead of failing. The shell keeps the current node wrapper and lists omitted direct child ids in an inline code comment so agents can request them one by one. The accompanying warning stays lightweight and only points agents to that comment.
|
|
51
53
|
- `apply_canvas` is available whenever MCP access is enabled and the current Figma Design file is
|
|
52
54
|
editable. Dev Mode and view-only files remain read-only.
|
|
53
|
-
- MCP **0.
|
|
54
|
-
|
|
55
|
+
- MCP **0.10.0** pairs with extension **0.22.0** and Agent Plugin **0.3.0**. Extension 0.22.0
|
|
56
|
+
needs no update for this release. Update the plugin or installed skills, replace any alpha-pinned MCP configuration with `@tempad-dev/mcp@latest`,
|
|
55
57
|
then reconnect the MCP client and start a new task. See the
|
|
56
58
|
[upgrade guide](https://github.com/ecomfe/tempad-dev/tree/main/agent-plugin/src#upgrading).
|
|
57
59
|
- Assets are ephemeral and tool-linked. Local stdio clients receive `asset.localPath` when the Hub
|
|
@@ -69,6 +71,8 @@ Optional environment variables:
|
|
|
69
71
|
|
|
70
72
|
- `TEMPAD_MCP_TOOL_TIMEOUT`: General tool call timeout in milliseconds (default `15000`).
|
|
71
73
|
- `TEMPAD_MCP_GET_CODE_TIMEOUT`: `get_code` timeout in milliseconds (default `30000`; falls back to `TEMPAD_MCP_TOOL_TIMEOUT` when that override is set).
|
|
74
|
+
- `TEMPAD_MCP_GET_DESIGN_SYSTEM_TIMEOUT`: Initial `get_design_system` resource-discovery timeout in milliseconds (default `45000`; continuation, exact-ref, font, and page-list reads use the general timeout). Falls back to `TEMPAD_MCP_TOOL_TIMEOUT` when that override is set.
|
|
75
|
+
- `TEMPAD_MCP_PAGE_STRUCTURE_TIMEOUT`: `get_structure` timeout for an explicit page ID or key, which may require loading a cold Figma page (default `45000` milliseconds; node and selection reads use the general timeout). Falls back to `TEMPAD_MCP_TOOL_TIMEOUT` when that override is set.
|
|
72
76
|
- `TEMPAD_MCP_APPLY_CANVAS_TIMEOUT`: `apply_canvas` slow-call warning threshold in milliseconds (default `120000`; falls back to `TEMPAD_MCP_TOOL_TIMEOUT` when that override is set). After the threshold, the Hub keeps waiting for a definitive result or extension disconnect so a completed mutation is never reported as a timeout.
|
|
73
77
|
- `TEMPAD_MCP_AUTO_ACTIVATE_GRACE`: Delay before auto-activating the sole connected extension (default `1500`).
|
|
74
78
|
- `TEMPAD_MCP_MAX_ASSET_BYTES`: Maximum upload size for captured assets/screenshots in bytes (default `8388608`).
|
package/README.zh-Hans.md
CHANGED
|
@@ -26,7 +26,9 @@ TemPad Dev 的 MCP server 将 coding agent 连接到浏览器中打开的 Figma
|
|
|
26
26
|
组件定义,以及本地或被定义直接引用的变量、集合/模式、样式和 shader 定义,不扫描画布
|
|
27
27
|
中的使用情况。游标可继续读取遗漏定义;使用同一目录精确查询某个引用时,返回该资源的
|
|
28
28
|
有界定义。使用 `scope: "fonts"` 可查询当前可用字体家族和精确原生样式,不读取文件资源。
|
|
29
|
-
|
|
29
|
+
`scope: "pages"` 无需扫描组件即可列出页面 ID;资源读取传入 `pageId` 时只扫描该页组件,
|
|
30
|
+
变量、样式和 shader 定义仍按文件范围读取。
|
|
31
|
+
- `manage_design_task`(`begin`、`resume`、`complete`、`cancel`)和 `set_design_anchor`:将画布写入绑定到设计任务,
|
|
30
32
|
恢复暂停的任务、设置状态栏锚点,以及结束或取消任务。Stop 会永久禁止旧任务写入,重新连接也不会恢复。
|
|
31
33
|
兼容 Codex App 的原生评论支持 Queue 和 Steer;确认接收后清空已提交草稿,无需等待执行完成。
|
|
32
34
|
详细行为与宿主验证范围见[评论指南](https://github.com/ecomfe/tempad-dev/blob/main/agent-plugin/src/README.zh-Hans.md#使用)。
|
|
@@ -45,7 +47,7 @@ TemPad Dev 的 MCP server 将 coding agent 连接到浏览器中打开的 Figma
|
|
|
45
47
|
- 工具响应共用 `64 KiB` 的 inline budget,按 `CallToolResult` 整体响应体积计算。若选区过大而超出 `get_code` 的预算,TemPad Dev 可能返回 shell response 而不是直接失败。shell 会保留当前节点的包裹结构,并在内联代码注释中列出被省略的直接子节点 id,方便 agent 逐个继续拉取;配套 warning 只保留最小化的提示信息,用来指向这条注释。
|
|
46
48
|
- 启用 MCP access 且当前 Figma Design 文件可编辑时,`apply_canvas` 即可使用;Dev Mode 和
|
|
47
49
|
只读文件仍不可写。
|
|
48
|
-
- MCP **0.
|
|
50
|
+
- MCP **0.10.0** 应配套使用扩展 **0.22.0** 和 Agent Plugin **0.3.0**。扩展 0.22.0 无需为本次发布更新。请更新 plugin 或已安装的 skill,
|
|
49
51
|
将固定 alpha 版本的 MCP 配置改为 `@tempad-dev/mcp@latest`,然后重新连接 MCP client 并新建任务。
|
|
50
52
|
详见[升级指南](https://github.com/ecomfe/tempad-dev/blob/main/agent-plugin/src/README.zh-Hans.md#升级)。
|
|
51
53
|
- 资源是临时且与工具调用关联的。本地 stdio client 在 Hub 持有字节时会收到
|
|
@@ -62,6 +64,8 @@ TemPad Dev 的 MCP server 将 coding agent 连接到浏览器中打开的 Figma
|
|
|
62
64
|
|
|
63
65
|
- `TEMPAD_MCP_TOOL_TIMEOUT`:常规工具调用超时时间(毫秒,默认 `15000`)。
|
|
64
66
|
- `TEMPAD_MCP_GET_CODE_TIMEOUT`:`get_code` 超时时间(毫秒,默认 `30000`;设置 `TEMPAD_MCP_TOOL_TIMEOUT` 时以其作为回退值)。
|
|
67
|
+
- `TEMPAD_MCP_GET_DESIGN_SYSTEM_TIMEOUT`:`get_design_system` 首次资源目录发现的超时时间(毫秒,默认 `45000`;续页、精确引用、字体和页面列表读取仍使用常规超时)。设置 `TEMPAD_MCP_TOOL_TIMEOUT` 时以其作为回退值。
|
|
68
|
+
- `TEMPAD_MCP_PAGE_STRUCTURE_TIMEOUT`:指定页面 ID 或 key 的 `get_structure` 超时时间(毫秒,默认 `45000`;冷页面可能需要先加载,节点和当前选择的读取仍使用常规超时)。设置 `TEMPAD_MCP_TOOL_TIMEOUT` 时以其作为回退值。
|
|
65
69
|
- `TEMPAD_MCP_APPLY_CANVAS_TIMEOUT`:`apply_canvas` 慢调用告警阈值(毫秒,默认 `120000`;设置 `TEMPAD_MCP_TOOL_TIMEOUT` 时以其作为回退值)。超过阈值后,Hub 会继续等待明确结果或扩展断开,避免把已经完成的画布变更误报为超时。
|
|
66
70
|
- `TEMPAD_MCP_AUTO_ACTIVATE_GRACE`:仅一个扩展连接时自动激活前的延迟(默认 `1500`)。
|
|
67
71
|
- `TEMPAD_MCP_MAX_ASSET_BYTES`:截图/资源捕获的最大上传体积(字节,默认 `8388608`)。
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { _ as runtimeIdentity, c as RUNTIME_DIR, l as SOCK_PATH, o as LOCK_PATH, p as log, s as PACKAGE_VERSION, u as ensureDir } from "./shared
|
|
2
|
+
import { _ as runtimeIdentity, c as RUNTIME_DIR, l as SOCK_PATH, o as LOCK_PATH, p as log, s as PACKAGE_VERSION, u as ensureDir } from "./shared-Dh112Muy.mjs";
|
|
3
3
|
import { spawn } from "node:child_process";
|
|
4
4
|
import { connect } from "node:net";
|
|
5
5
|
import { join } from "node:path";
|
|
@@ -30,7 +30,8 @@ process.on("SIGTERM", () => shutdownCli("SIGTERM received."));
|
|
|
30
30
|
const HUB_STARTUP_TIMEOUT = 5e3;
|
|
31
31
|
const CONNECT_RETRY_DELAY = 200;
|
|
32
32
|
const FAILED_RESTART_DELAY = 5e3;
|
|
33
|
-
const
|
|
33
|
+
const HERE = fileURLToPath(new URL(".", import.meta.url));
|
|
34
|
+
const HUB_ENTRY = join(HERE, "hub.mjs");
|
|
34
35
|
ensureDir(RUNTIME_DIR);
|
|
35
36
|
function bridge(socket) {
|
|
36
37
|
return new Promise((resolve) => {
|
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport type { ChildProcess } from 'node:child_process'\nimport type { Socket } from 'node:net'\n\nimport { spawn } from 'node:child_process'\nimport { connect } from 'node:net'\nimport { join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport lockfile from 'proper-lockfile'\n\nimport { runtimeIdentity } from './agent-clients/identity'\nimport {\n HUB_BUSY_EXIT_CODE,\n PACKAGE_VERSION,\n log,\n LOCK_PATH,\n RUNTIME_DIR,\n SOCK_PATH,\n ensureDir\n} from './shared'\n\nlet activeSocket: Socket | null = null\nlet shuttingDown = false\n\nfunction closeActiveSocket() {\n if (!activeSocket) return\n try {\n activeSocket.end()\n } catch {\n // ignore\n }\n try {\n activeSocket.destroy()\n } catch {\n // ignore\n }\n activeSocket = null\n}\n\nfunction shutdownCli(reason: string) {\n if (shuttingDown) return\n shuttingDown = true\n log.info(`${reason} Shutting down CLI.`)\n closeActiveSocket()\n process.exit(0)\n}\n\nprocess.on('SIGINT', () => shutdownCli('SIGINT received.'))\nprocess.on('SIGTERM', () => shutdownCli('SIGTERM received.'))\n\nconst HUB_STARTUP_TIMEOUT = 5000\nconst CONNECT_RETRY_DELAY = 200\nconst FAILED_RESTART_DELAY = 5000\nconst HERE = fileURLToPath(new URL('.', import.meta.url))\nconst HUB_ENTRY = join(HERE, 'hub.mjs')\n\nensureDir(RUNTIME_DIR)\n\nfunction bridge(socket: Socket): Promise<void> {\n return new Promise((resolve) => {\n log.info('Bridge established with Hub. Forwarding I/O.')\n activeSocket = socket\n\n const onStdinEnd = () => {\n shutdownCli('Consumer stream ended.')\n }\n process.stdin.once('end', onStdinEnd)\n\n const onSocketClose = () => {\n log.warn('Connection to Hub lost. Attempting to reconnect...')\n activeSocket = null\n process.stdin.removeListener('end', onStdinEnd)\n process.stdin.unpipe(socket)\n socket.unpipe(process.stdout)\n socket.removeAllListeners()\n resolve()\n }\n socket.once('close', onSocketClose)\n socket.on('error', (err) => log.warn({ err }, 'Socket error occurred.'))\n\n const binding = runtimeIdentity(process.env)\n socket.write(\n JSON.stringify({\n jsonrpc: '2.0',\n method: 'notifications/tempad/client-event',\n params: {\n event: 'connect',\n kind: binding.client.kind,\n sessionId: binding.client.sessionId\n }\n }) + '\\n'\n )\n\n // The `{ end: false }` option prevents stdin from closing the socket.\n process.stdin.pipe(socket, { end: false }).pipe(process.stdout)\n })\n}\n\nfunction connectHub(): Promise<Socket> {\n return new Promise((resolve, reject) => {\n const socket = connect(SOCK_PATH)\n socket.on('connect', () => {\n socket.removeAllListeners('error')\n resolve(socket)\n })\n socket.on('error', reject)\n })\n}\n\nasync function connectWithRetry(timeout: number): Promise<Socket> {\n const startTime = Date.now()\n let delay = CONNECT_RETRY_DELAY\n while (Date.now() - startTime < timeout) {\n try {\n return await connectHub()\n } catch (err: unknown) {\n if (\n err &&\n typeof err === 'object' &&\n 'code' in err &&\n (err.code === 'ENOENT' || err.code === 'ECONNREFUSED')\n ) {\n const remainingTime = timeout - (Date.now() - startTime)\n const waitTime = Math.min(delay, remainingTime)\n if (waitTime <= 0) break\n await new Promise((r) => setTimeout(r, waitTime))\n delay = Math.min(delay * 1.5, 1000)\n } else {\n throw err\n }\n }\n }\n throw new Error(`Failed to connect to Hub within ${timeout}ms.`)\n}\n\nfunction startHub(): ChildProcess {\n log.info('Spawning new Hub process...')\n return spawn(process.execPath, [HUB_ENTRY], {\n detached: true,\n stdio: 'ignore'\n })\n}\n\nasync function waitForHubStart(child: ChildProcess): Promise<Socket> {\n let foundExistingHub = false\n child.once('exit', (code) => {\n foundExistingHub = code === HUB_BUSY_EXIT_CODE\n })\n\n const socket = await connectWithRetry(HUB_STARTUP_TIMEOUT)\n if (foundExistingHub) {\n log.info('Spawned Hub found an existing lifecycle lock. Using the active Hub.')\n }\n child.unref()\n return socket\n}\n\nasync function tryBecomeLeaderAndStartHub(): Promise<Socket> {\n let releaseLock: (() => Promise<void>) | undefined\n try {\n releaseLock = await lockfile.lock(LOCK_PATH, {\n retries: { retries: 5, factor: 1.2, minTimeout: 50 },\n stale: 15000\n })\n } catch {\n log.info('Another process is starting the Hub. Waiting...')\n return connectWithRetry(HUB_STARTUP_TIMEOUT)\n }\n\n log.info('Acquired lock. Starting Hub as the leader...')\n let child: ChildProcess | null = null\n try {\n try {\n return await connectHub()\n } catch {\n // If the Hub is not running, we proceed to start it.\n log.info('Hub not running. Proceeding to start it...')\n }\n child = startHub()\n child.on('error', (err) => log.error({ err }, 'Hub child process error.'))\n return await waitForHubStart(child)\n } catch (err: unknown) {\n log.error({ err }, 'Failed to start or connect to the Hub.')\n if (child && !child.killed && child.exitCode === null && child.signalCode === null) {\n log.warn(`Killing stale Hub process (PID: ${child.pid})...`)\n child.kill('SIGTERM')\n }\n throw err\n } finally {\n if (releaseLock) await releaseLock()\n }\n}\n\nasync function main() {\n log.info({ version: PACKAGE_VERSION }, 'TemPad MCP Client starting...')\n\n while (true) {\n try {\n const socket = await connectHub().catch(() => {\n log.info('Hub not running. Initiating startup sequence...')\n return tryBecomeLeaderAndStartHub()\n })\n await bridge(socket)\n log.info('Bridge disconnected. Restarting connection process...')\n } catch (err: unknown) {\n log.error(\n { err },\n `Connection attempt failed. Retrying in ${FAILED_RESTART_DELAY / 1000}s...`\n )\n await new Promise((r) => setTimeout(r, FAILED_RESTART_DELAY))\n }\n }\n}\n\nvoid main()\n"],"mappings":";;;;;;;;AAsBA,IAAI,eAA8B;AAClC,IAAI,eAAe;AAEnB,SAAS,oBAAoB;CAC3B,IAAI,CAAC,cAAc;CACnB,IAAI;EACF,aAAa,IAAI;CACnB,QAAQ,CAER;CACA,IAAI;EACF,aAAa,QAAQ;CACvB,QAAQ,CAER;CACA,eAAe;AACjB;AAEA,SAAS,YAAY,QAAgB;CACnC,IAAI,cAAc;CAClB,eAAe;CACf,IAAI,KAAK,GAAG,OAAO,oBAAoB;CACvC,kBAAkB;CAClB,QAAQ,KAAK,CAAC;AAChB;AAEA,QAAQ,GAAG,gBAAgB,YAAY,kBAAkB,CAAC;AAC1D,QAAQ,GAAG,iBAAiB,YAAY,mBAAmB,CAAC;AAE5D,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport type { ChildProcess } from 'node:child_process'\nimport type { Socket } from 'node:net'\n\nimport { spawn } from 'node:child_process'\nimport { connect } from 'node:net'\nimport { join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport lockfile from 'proper-lockfile'\n\nimport { runtimeIdentity } from './agent-clients/identity'\nimport {\n HUB_BUSY_EXIT_CODE,\n PACKAGE_VERSION,\n log,\n LOCK_PATH,\n RUNTIME_DIR,\n SOCK_PATH,\n ensureDir\n} from './shared'\n\nlet activeSocket: Socket | null = null\nlet shuttingDown = false\n\nfunction closeActiveSocket() {\n if (!activeSocket) return\n try {\n activeSocket.end()\n } catch {\n // ignore\n }\n try {\n activeSocket.destroy()\n } catch {\n // ignore\n }\n activeSocket = null\n}\n\nfunction shutdownCli(reason: string) {\n if (shuttingDown) return\n shuttingDown = true\n log.info(`${reason} Shutting down CLI.`)\n closeActiveSocket()\n process.exit(0)\n}\n\nprocess.on('SIGINT', () => shutdownCli('SIGINT received.'))\nprocess.on('SIGTERM', () => shutdownCli('SIGTERM received.'))\n\nconst HUB_STARTUP_TIMEOUT = 5000\nconst CONNECT_RETRY_DELAY = 200\nconst FAILED_RESTART_DELAY = 5000\nconst HERE = fileURLToPath(new URL('.', import.meta.url))\nconst HUB_ENTRY = join(HERE, 'hub.mjs')\n\nensureDir(RUNTIME_DIR)\n\nfunction bridge(socket: Socket): Promise<void> {\n return new Promise((resolve) => {\n log.info('Bridge established with Hub. Forwarding I/O.')\n activeSocket = socket\n\n const onStdinEnd = () => {\n shutdownCli('Consumer stream ended.')\n }\n process.stdin.once('end', onStdinEnd)\n\n const onSocketClose = () => {\n log.warn('Connection to Hub lost. Attempting to reconnect...')\n activeSocket = null\n process.stdin.removeListener('end', onStdinEnd)\n process.stdin.unpipe(socket)\n socket.unpipe(process.stdout)\n socket.removeAllListeners()\n resolve()\n }\n socket.once('close', onSocketClose)\n socket.on('error', (err) => log.warn({ err }, 'Socket error occurred.'))\n\n const binding = runtimeIdentity(process.env)\n socket.write(\n JSON.stringify({\n jsonrpc: '2.0',\n method: 'notifications/tempad/client-event',\n params: {\n event: 'connect',\n kind: binding.client.kind,\n sessionId: binding.client.sessionId\n }\n }) + '\\n'\n )\n\n // The `{ end: false }` option prevents stdin from closing the socket.\n process.stdin.pipe(socket, { end: false }).pipe(process.stdout)\n })\n}\n\nfunction connectHub(): Promise<Socket> {\n return new Promise((resolve, reject) => {\n const socket = connect(SOCK_PATH)\n socket.on('connect', () => {\n socket.removeAllListeners('error')\n resolve(socket)\n })\n socket.on('error', reject)\n })\n}\n\nasync function connectWithRetry(timeout: number): Promise<Socket> {\n const startTime = Date.now()\n let delay = CONNECT_RETRY_DELAY\n while (Date.now() - startTime < timeout) {\n try {\n return await connectHub()\n } catch (err: unknown) {\n if (\n err &&\n typeof err === 'object' &&\n 'code' in err &&\n (err.code === 'ENOENT' || err.code === 'ECONNREFUSED')\n ) {\n const remainingTime = timeout - (Date.now() - startTime)\n const waitTime = Math.min(delay, remainingTime)\n if (waitTime <= 0) break\n await new Promise((r) => setTimeout(r, waitTime))\n delay = Math.min(delay * 1.5, 1000)\n } else {\n throw err\n }\n }\n }\n throw new Error(`Failed to connect to Hub within ${timeout}ms.`)\n}\n\nfunction startHub(): ChildProcess {\n log.info('Spawning new Hub process...')\n return spawn(process.execPath, [HUB_ENTRY], {\n detached: true,\n stdio: 'ignore'\n })\n}\n\nasync function waitForHubStart(child: ChildProcess): Promise<Socket> {\n let foundExistingHub = false\n child.once('exit', (code) => {\n foundExistingHub = code === HUB_BUSY_EXIT_CODE\n })\n\n const socket = await connectWithRetry(HUB_STARTUP_TIMEOUT)\n if (foundExistingHub) {\n log.info('Spawned Hub found an existing lifecycle lock. Using the active Hub.')\n }\n child.unref()\n return socket\n}\n\nasync function tryBecomeLeaderAndStartHub(): Promise<Socket> {\n let releaseLock: (() => Promise<void>) | undefined\n try {\n releaseLock = await lockfile.lock(LOCK_PATH, {\n retries: { retries: 5, factor: 1.2, minTimeout: 50 },\n stale: 15000\n })\n } catch {\n log.info('Another process is starting the Hub. Waiting...')\n return connectWithRetry(HUB_STARTUP_TIMEOUT)\n }\n\n log.info('Acquired lock. Starting Hub as the leader...')\n let child: ChildProcess | null = null\n try {\n try {\n return await connectHub()\n } catch {\n // If the Hub is not running, we proceed to start it.\n log.info('Hub not running. Proceeding to start it...')\n }\n child = startHub()\n child.on('error', (err) => log.error({ err }, 'Hub child process error.'))\n return await waitForHubStart(child)\n } catch (err: unknown) {\n log.error({ err }, 'Failed to start or connect to the Hub.')\n if (child && !child.killed && child.exitCode === null && child.signalCode === null) {\n log.warn(`Killing stale Hub process (PID: ${child.pid})...`)\n child.kill('SIGTERM')\n }\n throw err\n } finally {\n if (releaseLock) await releaseLock()\n }\n}\n\nasync function main() {\n log.info({ version: PACKAGE_VERSION }, 'TemPad MCP Client starting...')\n\n while (true) {\n try {\n const socket = await connectHub().catch(() => {\n log.info('Hub not running. Initiating startup sequence...')\n return tryBecomeLeaderAndStartHub()\n })\n await bridge(socket)\n log.info('Bridge disconnected. Restarting connection process...')\n } catch (err: unknown) {\n log.error(\n { err },\n `Connection attempt failed. Retrying in ${FAILED_RESTART_DELAY / 1000}s...`\n )\n await new Promise((r) => setTimeout(r, FAILED_RESTART_DELAY))\n }\n }\n}\n\nvoid main()\n"],"mappings":"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"}
|
package/dist/hub.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS, A as GetScreenshotParametersSchema, B as MCP_GET_CODE_TIMEOUT_MS, C as DesignTaskSchema, D as GetCodeParametersSchema, E as GetAssetsResultSchema, G as MCP_PORT_CANDIDATES, H as MCP_MAX_ASSET_BYTES, I as MCP_APPLY_CANVAS_TIMEOUT_MS, J as ManageDesignTaskParametersSchema, K as MCP_TOOL_INLINE_BUDGET_BYTES, L as MCP_ASSET_TTL_MS, M as GetTokenDefsParametersSchema, N as LegacyMessageFromExtensionSchema, O as GetDesignSystemParametersSchema, P as LegacyToolCallPayloadSchema, Q as TEMPAD_MCP_BRIDGE_SUBPROTOCOL, R as MCP_AUTO_ACTIVATE_GRACE_MS, S as DesignTaskIdSchema, T as GetAssetsParametersSchema, U as MCP_MAX_ASSET_STORE_BYTES, V as MCP_GET_DESIGN_SYSTEM_TIMEOUT_MS, W as MCP_MAX_PAYLOAD_BYTES, X as RESUMABLE_DESIGN_TASK_STATUSES, Y as MessageFromExtensionSchema, Z as SetDesignAnchorParametersSchema, a as HUB_RUNTIME_IDENTITY_PATH, at as buildGetCodeToolResult, b as ApplyCanvasResultSchema, c as RUNTIME_DIR, ct as buildGetStructureToolResult, d as ensureFile, dt as formatDesignFeedback, et as TEMPAD_MCP_ERROR_CODES, f as getRecordProperty, ft as measureCallToolResultBytes, g as clientDescriptor, h as bindRequestMetadata, i as HUB_LOCK_UPDATE_MS, it as buildGetAssetsToolResult, j as GetStructureParametersSchema, k as GetDesignSystemResultSchema, l as SOCK_PATH, lt as buildGetTokenDefsToolResult, m as ClientEventSchema, n as HUB_LOCK_PATH, nt as UploadAssetResultSchema, ot as buildGetDesignSystemToolResult, p as log, pt as utf8Bytes, q as MCP_TOOL_TIMEOUT_MS, r as HUB_LOCK_STALE_MS, rt as buildApplyCanvasToolResult, s as PACKAGE_VERSION, st as buildGetScreenshotToolResult, t as ASSET_DIR, tt as UploadAssetParametersSchema, u as ensureDir, ut as buildUploadAssetToolResult, v as AGENT_CLIENTS, w as FigmaSessionSchema, x as DesignAnchorSchema, y as ApplyCanvasParametersSchema } from "./shared-Dh112Muy.mjs";
|
|
2
2
|
import { execFile, spawn } from "node:child_process";
|
|
3
3
|
import { connect, createServer } from "node:net";
|
|
4
4
|
import { dirname, join, resolve } from "node:path";
|
|
@@ -70,7 +70,7 @@ var CodexIpc = class CodexIpc {
|
|
|
70
70
|
offset += copied;
|
|
71
71
|
if (this.headerBytes < 4) continue;
|
|
72
72
|
const size = this.header.readUInt32LE(0);
|
|
73
|
-
if (!size || size >
|
|
73
|
+
if (!size || size > 268435456) {
|
|
74
74
|
this.close();
|
|
75
75
|
return;
|
|
76
76
|
}
|
|
@@ -735,7 +735,7 @@ var CodexAppFeedback = class {
|
|
|
735
735
|
]));
|
|
736
736
|
const signature = hash(JSON.stringify(feedback));
|
|
737
737
|
const path = join(this.directory, `${key}.json`);
|
|
738
|
-
const deadline = Date.now() +
|
|
738
|
+
const deadline = Date.now() + 3e5;
|
|
739
739
|
let loaded = false;
|
|
740
740
|
let nativeQueueUnavailable = false;
|
|
741
741
|
await mkdir(this.directory, {
|
|
@@ -1798,6 +1798,7 @@ function getHashFromAssetFilename(filename) {
|
|
|
1798
1798
|
}
|
|
1799
1799
|
//#endregion
|
|
1800
1800
|
//#region src/config.ts
|
|
1801
|
+
const PAGE_STRUCTURE_TIMEOUT_MS = 45e3;
|
|
1801
1802
|
function parsePositiveInt(envValue, fallback) {
|
|
1802
1803
|
const parsed = envValue ? Number.parseInt(envValue, 10) : NaN;
|
|
1803
1804
|
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
@@ -1832,6 +1833,8 @@ function getMcpServerConfig() {
|
|
|
1832
1833
|
wsPortCandidates: [...MCP_PORT_CANDIDATES],
|
|
1833
1834
|
toolTimeoutMs: resolveToolTimeoutMs(),
|
|
1834
1835
|
getCodeTimeoutMs: resolveToolTimeoutMs(process.env.TEMPAD_MCP_GET_CODE_TIMEOUT, MCP_GET_CODE_TIMEOUT_MS),
|
|
1836
|
+
getDesignSystemTimeoutMs: resolveToolTimeoutMs(process.env.TEMPAD_MCP_GET_DESIGN_SYSTEM_TIMEOUT, MCP_GET_DESIGN_SYSTEM_TIMEOUT_MS),
|
|
1837
|
+
pageStructureTimeoutMs: resolveToolTimeoutMs(process.env.TEMPAD_MCP_PAGE_STRUCTURE_TIMEOUT, PAGE_STRUCTURE_TIMEOUT_MS),
|
|
1835
1838
|
applyCanvasTimeoutMs: resolveToolTimeoutMs(process.env.TEMPAD_MCP_APPLY_CANVAS_TIMEOUT, MCP_APPLY_CANVAS_TIMEOUT_MS),
|
|
1836
1839
|
maxPayloadBytes: MCP_MAX_PAYLOAD_BYTES,
|
|
1837
1840
|
autoActivateGraceMs: resolveAutoActivateGraceMs(),
|
|
@@ -2070,7 +2073,8 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
2070
2073
|
return;
|
|
2071
2074
|
}
|
|
2072
2075
|
const mimeType = normalizeMimeType(getHeader(req, "content-type"));
|
|
2073
|
-
const
|
|
2076
|
+
const filename = buildAssetFilename(hash, mimeType);
|
|
2077
|
+
const filePath = join(ASSET_DIR, filename);
|
|
2074
2078
|
const width = parseInt(getHeader(req, "x-asset-width") ?? "", 10);
|
|
2075
2079
|
const height = parseInt(getHeader(req, "x-asset-height") ?? "", 10);
|
|
2076
2080
|
const themeable = getHeader(req, "x-asset-themeable") === "true";
|
|
@@ -2136,7 +2140,7 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
2136
2140
|
}, "Failed to cleanup temp file.");
|
|
2137
2141
|
}
|
|
2138
2142
|
};
|
|
2139
|
-
|
|
2143
|
+
const monitor = new Transform({ transform(chunk, encoding, callback) {
|
|
2140
2144
|
size += chunk.length;
|
|
2141
2145
|
if (size > maxAssetSizeBytes) {
|
|
2142
2146
|
callback(/* @__PURE__ */ new Error("PayloadTooLarge"));
|
|
@@ -2144,7 +2148,8 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
2144
2148
|
}
|
|
2145
2149
|
hasher.update(chunk);
|
|
2146
2150
|
callback(null, chunk);
|
|
2147
|
-
} })
|
|
2151
|
+
} });
|
|
2152
|
+
pipeline(req, monitor, writeStream, (err) => {
|
|
2148
2153
|
activeUploads -= 1;
|
|
2149
2154
|
reservedUploadBytes -= reservationBytes;
|
|
2150
2155
|
if (err) {
|
|
@@ -2286,7 +2291,8 @@ function readIndex(indexPath) {
|
|
|
2286
2291
|
}
|
|
2287
2292
|
}
|
|
2288
2293
|
function writeIndex(indexPath, values) {
|
|
2289
|
-
|
|
2294
|
+
const payload = JSON.stringify(values, null, 2);
|
|
2295
|
+
writeFileSync(indexPath, payload, "utf8");
|
|
2290
2296
|
}
|
|
2291
2297
|
function createAssetStore(options = {}) {
|
|
2292
2298
|
ensureDir(ASSET_DIR);
|
|
@@ -2371,7 +2377,7 @@ function createAssetStore(options = {}) {
|
|
|
2371
2377
|
if (file.includes(".tmp.")) {
|
|
2372
2378
|
try {
|
|
2373
2379
|
const filePath = join(ASSET_DIR, file);
|
|
2374
|
-
if (now - statSync(filePath).mtimeMs >
|
|
2380
|
+
if (now - statSync(filePath).mtimeMs > 36e5) {
|
|
2375
2381
|
rmSync(filePath, { force: true });
|
|
2376
2382
|
log.info({ file }, "Cleaned up stale temp file.");
|
|
2377
2383
|
}
|
|
@@ -2492,11 +2498,12 @@ function fail(code, message) {
|
|
|
2492
2498
|
}
|
|
2493
2499
|
function resolveDesignTarget(tasks, extensions, activeExtensionId, ownerId, taskId, active = true, explicitSessionId) {
|
|
2494
2500
|
const record = taskId ? tasks.owned(taskId, ownerId, active) : void 0;
|
|
2495
|
-
|
|
2501
|
+
if (record && explicitSessionId && explicitSessionId !== record.task.target.sessionId) fail("DESIGN_TARGET_CHANGED", "The requested Figma session does not match this task.");
|
|
2502
|
+
const extension = extensions.find((value) => explicitSessionId && !record ? value.sessions?.sessions.some((session) => session.sessionId === explicitSessionId) : value.id === (record?.extensionId ?? activeExtensionId)) ?? (!active && record ? extensions.find((value) => value.sessions?.sessions.some((session) => session.sessionId === record.task.target.sessionId && session.fileKey === record.task.target.fileKey)) : void 0);
|
|
2496
2503
|
if (extension?.legacy) throw extensionUpgradeRequired();
|
|
2497
2504
|
const sessionId = explicitSessionId ?? record?.task.target.sessionId ?? extension?.sessions?.activeSessionId;
|
|
2498
2505
|
const session = extension?.sessions?.sessions.find((value) => value.sessionId === sessionId);
|
|
2499
|
-
if (!extension || !session) fail("NO_ACTIVE_EXTENSION", record ? "The bound Figma session is unavailable. Begin a new task after reconnecting; no other tab was selected." : "No active Figma session. Activate the intended file with its TemPad Dev MCP badge.");
|
|
2506
|
+
if (!extension || !session) fail("NO_ACTIVE_EXTENSION", record ? "The bound Figma session is unavailable. Begin a new task after reconnecting; no other tab was selected." : explicitSessionId ? `Figma session ${explicitSessionId} is unavailable. Call list_design_sessions for a current sessionId.` : "No active Figma session. Activate the intended file with its TemPad Dev MCP badge.");
|
|
2500
2507
|
if (record && record.task.target.fileKey !== session.fileKey) fail("DESIGN_TARGET_CHANGED", "The task file changed.");
|
|
2501
2508
|
const busy = extensions.some((connection) => connection.sessions?.sessions.some((value) => value.fileKey === session.fileKey && value.busy));
|
|
2502
2509
|
return {
|
|
@@ -2581,7 +2588,7 @@ var DesignTasks = class {
|
|
|
2581
2588
|
if (!record) fail("DESIGN_TASK_INACTIVE", "Unknown or expired task. Begin a new design task and reread its target.");
|
|
2582
2589
|
if (record.ownerId !== ownerId) fail("DESIGN_TASK_OWNER_MISMATCH", "This task belongs to another MCP caller. Begin your own task.");
|
|
2583
2590
|
if (active && record.task.reviewClosed) fail("DESIGN_TASK_INACTIVE", "This review is closed. Begin a new task before writing.");
|
|
2584
|
-
if (active && record.task.status !== "active") fail("DESIGN_TASK_INACTIVE", `Design task is ${record.task.status}. ${record.task.status === "cancelled" ? "Begin a new task with a fresh requestId before writing." : "
|
|
2591
|
+
if (active && record.task.status !== "active") fail("DESIGN_TASK_INACTIVE", `Design task is ${record.task.status}. ${record.task.status === "cancelled" ? "Begin a new task with a fresh requestId before writing." : "Use manage_design_task with action \"resume\" and reread the target before writing; do not replay an old write."}`);
|
|
2585
2592
|
return record;
|
|
2586
2593
|
}
|
|
2587
2594
|
/** Runtime identity may reconnect the same conversation, never a focused/last caller. */
|
|
@@ -2599,7 +2606,7 @@ var DesignTasks = class {
|
|
|
2599
2606
|
}
|
|
2600
2607
|
assertEpoch(taskId, ownerId, epoch) {
|
|
2601
2608
|
const record = this.owned(taskId, ownerId);
|
|
2602
|
-
if ((epoch ?? 0) !== (record.task.epoch ?? 0)) fail("DESIGN_TASK_INACTIVE", "Stale task lease. Read get_design_task for the current epoch,
|
|
2609
|
+
if ((epoch ?? 0) !== (record.task.epoch ?? 0)) fail("DESIGN_TASK_INACTIVE", "Stale task lease. Read get_design_task for the current epoch, use manage_design_task with action \"resume\" if inactive, and reread the canvas before writing.");
|
|
2603
2610
|
return record;
|
|
2604
2611
|
}
|
|
2605
2612
|
resume(taskId, ownerId, epoch, session) {
|
|
@@ -3081,8 +3088,6 @@ function attachExtensionSocket(ws, options) {
|
|
|
3081
3088
|
fingerprint: message.extensionRuntimeFingerprint
|
|
3082
3089
|
};
|
|
3083
3090
|
options.onRuntimeHello?.(extension);
|
|
3084
|
-
break;
|
|
3085
|
-
case "ping": break;
|
|
3086
3091
|
}
|
|
3087
3092
|
});
|
|
3088
3093
|
ws.on("error", (error) => {
|
|
@@ -3111,7 +3116,7 @@ function rawDataToBuffer(raw) {
|
|
|
3111
3116
|
}
|
|
3112
3117
|
//#endregion
|
|
3113
3118
|
//#region src/instructions.md?raw
|
|
3114
|
-
var instructions_default = "You are connected to Figma through TemPad Dev.
|
|
3119
|
+
var instructions_default = "You are connected to Figma through TemPad Dev. An active MCP badge selects the default file;\nbrowser focus does not. When the target is unclear, call `list_design_sessions` and pass the exact\n`sessionId` to `manage_design_task` with action `begin` or an independent read. Task targets never follow browser focus;\ntask-bound reads stay on their task's session. Independent reads need no task. Run calls against\nthe same file sequentially, including reads.\n\nFor new design work, call `manage_design_task` with action `begin` before research or writing,\nthen carry its `taskId`.\nChoose a known Frame with `set_design_anchor` once the region is clear; otherwise the first new\ntop-level Frame anchors automatically. Reads, selections, and later writes never change the anchor\nunless `set_design_anchor` does. Task identity survives turns. A pause or idle lease expiry releases\ncanvas ownership without cancelling the task;\nuse action `resume` with the current `epoch`, carry its returned `epoch` as `taskEpoch`, and reread the\nbound canvas with `get_structure` or `get_code` before writing. Use `get_design_task` for recovery,\nnot routine polling. Never replay a stale write or queue a write against an occupied file.\nActions `complete` and `cancel` require the current `epoch` and end a verified pass or explicitly\nabandon it; they are not for a wait for input.\nCompletion releases ownership but keeps the review and same task open for comments until the user\nclicks Done; resume that task for follow-up comments. Cancelled, closed, or replaced tasks cannot\nresume. The Figma Stop control permanently cancels the current task after its running operation\nsettles; do not resume or automatically replace it. If further work is necessary or requested,\nuse action `begin` with a fresh requestId; no separate\nFigma unlock or user turn is required. No progress or heartbeat calls are needed.\n\nFeedback drafts contain individually numbered elements captured when saved. Reread each exact node\nbefore acting; do not substitute the current selection. Supported hosts deliver submitted feedback\nthrough native conversation messages. Do not poll, launch helpers, or configure a control endpoint.\n\nTreat tool outputs as file-scoped facts. Never invent node IDs, resource refs, library keys, token\norigins, or design-system intent. Tool descriptions give mechanical affordances; the applicable host\nskill governs workflow, representation, and design judgment. For Figma-to-code, use `get_code` as\nvisible implementation evidence. Use `get_structure` only for hierarchy, geometry, managed-key\nuncertainty, or targeted mask, IMAGE paint, layout-grid, and frame-guide read-back via\n`options.native`.\n\nFor canvas authoring, choose the native representation through the skill, then describe one desired\nresult with `apply_canvas`. Canvas HTML serializes ordinary layers; typed fields carry selected\nnative state, resources, and bindings. Never send raw Plugin API operations or arbitrary JavaScript.\n`get_design_system` is optional when existing-resource reuse is relevant and permitted; new local\nresources do not require it. `scope: \"fonts\"` independently reads environment availability.\nFor large files, `scope: \"pages\"` finds a relevant component page before `pageId`-scoped discovery;\nvariables, styles, and shaders remain file-wide. Use catalog CSS names or a call-scoped `theme` for\nvariable utilities and native text-style classes. Load skill references only after choosing a\nnative concept.\n\nWhen design evidence is limited to the current page or an independent system without reuse, stay\non the Direct path: do not discover resource catalogs, inspect other pages, or use catalog refs.\n`scope: \"fonts\"` remains available. Local variables and styles remain file-wide Figma resources,\nand the extension may still check file-wide identities internally for safe reconciliation.\n\nCreates add and automatically place one root. Updates use exact node identity: omission preserves\nlive state; explicit removal removes managed content. Read structural verification and resolve\nwarnings before claiming completion. Use `get_screenshot` when pixels affect a decision and open\nits image before claiming visual verification. Use `asset.localPath` when present, otherwise\n`asset.url`; native media hashes identify assets within one Figma file, not preview bytes. Never\nship `data-hint-*` attributes from read-tool output.\n";
|
|
3115
3120
|
//#endregion
|
|
3116
3121
|
//#region src/request.ts
|
|
3117
3122
|
const pendingCalls = /* @__PURE__ */ new Map();
|
|
@@ -3286,8 +3291,8 @@ const KNOWN_ERROR_CODES = new Set(Object.values(TEMPAD_MCP_ERROR_CODES));
|
|
|
3286
3291
|
const CONNECTIVITY_TROUBLESHOOTING_LINES = [
|
|
3287
3292
|
"Troubleshooting:",
|
|
3288
3293
|
"- In Figma, open TemPad Dev panel and enable the MCP server in Preferences → Agent integration. Enabled permits connection; it does not prove that an extension is active.",
|
|
3289
|
-
"-
|
|
3290
|
-
"- If the
|
|
3294
|
+
"- Badge-default reads require the intended tab's active MCP badge. Exact sessionId reads require that session in list_design_sessions; browser focus does not select a default.",
|
|
3295
|
+
"- If the connection is missing or reports a protocol mismatch, rebuild the affected runtime layers, reload the installed TemPad Dev browser extension, reload the same Figma tab, and start a fresh task."
|
|
3291
3296
|
];
|
|
3292
3297
|
const SELECTION_TROUBLESHOOTING_LINE = "Tip: Select exactly one visible node, or pass nodeId.";
|
|
3293
3298
|
const VERIFICATION_TROUBLESHOOTING_LINE = "Tip: TemPad rolls verification failures back. Correct the reported desired-state mismatch and retry the affected root while preserving unrelated design intent.";
|
|
@@ -3311,33 +3316,17 @@ const TOOL_DEFS = [
|
|
|
3311
3316
|
}),
|
|
3312
3317
|
hubTool({
|
|
3313
3318
|
name: "list_design_sessions",
|
|
3314
|
-
description: "List connected Figma targets before beginning a design. Select an exact sessionId when more than one file is connected.",
|
|
3319
|
+
description: "List connected Figma targets before beginning a design or an exact-session read. Select an exact sessionId when more than one file is connected.",
|
|
3315
3320
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
3316
3321
|
parameters: z.object({}).strict(),
|
|
3317
3322
|
target: "hub",
|
|
3318
3323
|
outputSchema: z.object({ sessions: z.array(FigmaSessionSchema) })
|
|
3319
3324
|
}),
|
|
3320
3325
|
hubTool({
|
|
3321
|
-
name: "
|
|
3322
|
-
description: "
|
|
3323
|
-
annotations: ASSET_WRITE_ANNOTATIONS,
|
|
3324
|
-
parameters: ResumeDesignParametersSchema,
|
|
3325
|
-
target: "hub",
|
|
3326
|
-
outputSchema: DesignTaskSchema
|
|
3327
|
-
}),
|
|
3328
|
-
hubTool({
|
|
3329
|
-
name: "begin_design",
|
|
3330
|
-
description: "Begin a new design task in the active Figma session before design research or writing. Returns a taskId bound to that file and session; pass it on subsequent task calls. No coordinates or progress reports are needed. Idle ownership expires after five minutes. Reuse requestId only when retrying this same begin. Stop a busy task in TemPad Dev before another task takes over. For follow-up comments on an open review, use resume_design on the same task, including after completion. Beginning a new task replaces the previous task for that file.",
|
|
3331
|
-
annotations: ASSET_WRITE_ANNOTATIONS,
|
|
3332
|
-
parameters: BeginDesignParametersSchema,
|
|
3333
|
-
target: "hub",
|
|
3334
|
-
outputSchema: DesignTaskSchema
|
|
3335
|
-
}),
|
|
3336
|
-
hubTool({
|
|
3337
|
-
name: "end_design",
|
|
3338
|
-
description: "Mark this design pass complete after the requested outcome and its verification. Releases file ownership and keeps the same task, design region, and review open for comments. Follow-up comments resume this task; only the user’s Done closes the review. Waiting for input before the outcome is ready or stopping a turn is a pause. Cancel when abandoning a task; already completed writes remain. Retrying within the same epoch is safe. Cancellation waits for a running operation to finish before handing over the file.",
|
|
3326
|
+
name: "manage_design_task",
|
|
3327
|
+
description: "Manage one design task. begin requires title and a fresh UUID requestId, optionally sessionId; reserve the file before research or writing, and reuse requestId only for the same begin retry. Beginning replaces the previous task for that file; idle ownership expires after five minutes. Other actions require taskId and current epoch. resume continues the same open review after pause, expiry, interruption, or completion; pass its returned epoch as taskEpoch on subsequent work and reread the bound canvas before writing. Cancelled, closed, or replaced tasks cannot resume. complete releases ownership after the outcome and verification, keeping the review open until the user clicks Done. cancel permanently abandons the task after any running operation settles; applied changes remain. summary is optional for complete/cancel. Waiting for input is a pause, not completion. No progress or heartbeat calls are needed.",
|
|
3339
3328
|
annotations: ASSET_WRITE_ANNOTATIONS,
|
|
3340
|
-
parameters:
|
|
3329
|
+
parameters: ManageDesignTaskParametersSchema,
|
|
3341
3330
|
target: "hub",
|
|
3342
3331
|
outputSchema: DesignTaskSchema
|
|
3343
3332
|
}),
|
|
@@ -3360,7 +3349,7 @@ const TOOL_DEFS = [
|
|
|
3360
3349
|
}),
|
|
3361
3350
|
extTool({
|
|
3362
3351
|
name: "get_design_system",
|
|
3363
|
-
description: "Discover resources or available fonts. For fonts, use scope: \"fonts\" with query to find families or families to read exact native styles; this reads the environment without scanning file resources and is allowed for independent designs. Resource discovery returns a bounded catalog with component tags, variable cssName and text-style className aliases.
|
|
3352
|
+
description: "Discover resources, file pages, or available fonts. For fonts, use scope: \"fonts\" with query to find families or families to read exact native styles; this reads the environment without scanning file resources and is allowed for independent designs. Resource discovery returns a bounded catalog with component tags, variable cssName and text-style className aliases. When existing-resource reuse is permitted and relevant, scope: \"pages\" lists page IDs cheaply; pageId loads that page and limits component discovery to it while local variables, styles, and shaders remain file-wide. Omit pageId for a quick scan; off-current pages may omit components even if queried successfully. Skip resource and page discovery when the user limits design evidence to the current page or requests an independent system. Continue catalogs by catalogId/cursor or inspect catalogId/ref.",
|
|
3364
3353
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
3365
3354
|
parameters: GetDesignSystemParametersSchema,
|
|
3366
3355
|
target: "extension",
|
|
@@ -3421,7 +3410,8 @@ const TOOL_DEFS = [
|
|
|
3421
3410
|
function extractToolErrorCode(error) {
|
|
3422
3411
|
const code = getRecordProperty(error, "code");
|
|
3423
3412
|
if (isTempadMcpErrorCode(code)) return code;
|
|
3424
|
-
const
|
|
3413
|
+
const cause = getRecordProperty(error, "cause");
|
|
3414
|
+
const causeCode = getRecordProperty(cause, "code");
|
|
3425
3415
|
if (isTempadMcpErrorCode(causeCode)) return causeCode;
|
|
3426
3416
|
}
|
|
3427
3417
|
function isTempadMcpErrorCode(value) {
|
|
@@ -3534,11 +3524,12 @@ function createDesignAnchorToolResponse(payload) {
|
|
|
3534
3524
|
};
|
|
3535
3525
|
}
|
|
3536
3526
|
function createInlineBudgetExceededToolResponse(toolName, actualBytes) {
|
|
3527
|
+
const guidance = getBudgetRetryGuidance(toolName);
|
|
3537
3528
|
return {
|
|
3538
3529
|
isError: true,
|
|
3539
3530
|
content: [{
|
|
3540
3531
|
type: "text",
|
|
3541
|
-
text: `Tool "${toolName}" exceeded the 64 KiB inline budget (${actualBytes} UTF-8 bytes > ${MCP_TOOL_INLINE_BUDGET_BYTES}). ${
|
|
3532
|
+
text: `Tool "${toolName}" exceeded the 64 KiB inline budget (${actualBytes} UTF-8 bytes > ${MCP_TOOL_INLINE_BUDGET_BYTES}). ${guidance}`
|
|
3542
3533
|
}]
|
|
3543
3534
|
};
|
|
3544
3535
|
}
|
|
@@ -3549,9 +3540,7 @@ function getBudgetRetryGuidance(toolName) {
|
|
|
3549
3540
|
switch (toolName) {
|
|
3550
3541
|
case "get_design_task":
|
|
3551
3542
|
case "list_design_sessions":
|
|
3552
|
-
case "
|
|
3553
|
-
case "resume_design":
|
|
3554
|
-
case "end_design":
|
|
3543
|
+
case "manage_design_task":
|
|
3555
3544
|
case "set_design_anchor": return "Retry the same task lifecycle request without changing its identity.";
|
|
3556
3545
|
case "apply_canvas": return "Submit a smaller desired subtree and retry.";
|
|
3557
3546
|
case "get_code": return "Reduce selection size or request a smaller nodeId subtree and retry.";
|
|
@@ -3623,7 +3612,14 @@ function resolveListeningPort(server, candidate) {
|
|
|
3623
3612
|
//#region src/hub.ts
|
|
3624
3613
|
const SHUTDOWN_TIMEOUT = 2e3;
|
|
3625
3614
|
const SOCKET_PROBE_TIMEOUT_MS = 300;
|
|
3626
|
-
const
|
|
3615
|
+
const EXACT_SESSION_READ_TOOLS = /* @__PURE__ */ new Set([
|
|
3616
|
+
"get_code",
|
|
3617
|
+
"get_structure",
|
|
3618
|
+
"get_screenshot",
|
|
3619
|
+
"get_design_system",
|
|
3620
|
+
"get_token_defs"
|
|
3621
|
+
]);
|
|
3622
|
+
const { wsPortCandidates, toolTimeoutMs, getCodeTimeoutMs, getDesignSystemTimeoutMs, pageStructureTimeoutMs, applyCanvasTimeoutMs, maxPayloadBytes, maxAssetSizeBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig();
|
|
3627
3623
|
const extensionOriginPolicy = createExtensionOriginPolicy(allowedExtensionOrigins);
|
|
3628
3624
|
log.info({ version: PACKAGE_VERSION }, "TemPad MCP Hub starting...");
|
|
3629
3625
|
const extensionRegistry = new ExtensionRegistry(autoActivateGraceMs);
|
|
@@ -3752,17 +3748,9 @@ function enrichToolDefinition(tool) {
|
|
|
3752
3748
|
};
|
|
3753
3749
|
}
|
|
3754
3750
|
};
|
|
3755
|
-
case "
|
|
3756
|
-
...tool,
|
|
3757
|
-
handler: handleResumeDesign
|
|
3758
|
-
};
|
|
3759
|
-
case "begin_design": return {
|
|
3751
|
+
case "manage_design_task": return {
|
|
3760
3752
|
...tool,
|
|
3761
|
-
handler:
|
|
3762
|
-
};
|
|
3763
|
-
case "end_design": return {
|
|
3764
|
-
...tool,
|
|
3765
|
-
handler: handleEndDesign
|
|
3753
|
+
handler: handleManageDesignTask
|
|
3766
3754
|
};
|
|
3767
3755
|
case "get_assets": return {
|
|
3768
3756
|
...tool,
|
|
@@ -3816,7 +3804,7 @@ function scheduleAssetCleanup() {
|
|
|
3816
3804
|
return;
|
|
3817
3805
|
}
|
|
3818
3806
|
pruneExpiredAssets(assetTtlMs);
|
|
3819
|
-
const intervalMs = Math.min(assetTtlMs,
|
|
3807
|
+
const intervalMs = Math.min(assetTtlMs, 864e5);
|
|
3820
3808
|
unrefTimer(setInterval(() => {
|
|
3821
3809
|
pruneExpiredAssets(assetTtlMs);
|
|
3822
3810
|
}, intervalMs));
|
|
@@ -3877,6 +3865,26 @@ function publishDesignTask({ task }) {
|
|
|
3877
3865
|
function resolveDesignRoute(ownerId, taskId, active = true, explicitSessionId) {
|
|
3878
3866
|
return resolveDesignTarget(designTasks, extensionRegistry.list(), extensionRegistry.getActiveId(), ownerId, taskId, active, explicitSessionId);
|
|
3879
3867
|
}
|
|
3868
|
+
async function handleManageDesignTask(args, ownerId) {
|
|
3869
|
+
switch (args.action) {
|
|
3870
|
+
case "begin": return handleBeginDesign({
|
|
3871
|
+
title: args.title,
|
|
3872
|
+
requestId: args.requestId,
|
|
3873
|
+
sessionId: args.sessionId
|
|
3874
|
+
}, ownerId);
|
|
3875
|
+
case "resume": return handleResumeDesign({
|
|
3876
|
+
taskId: args.taskId,
|
|
3877
|
+
epoch: args.epoch
|
|
3878
|
+
}, ownerId);
|
|
3879
|
+
case "complete":
|
|
3880
|
+
case "cancel": return handleEndDesign({
|
|
3881
|
+
taskId: args.taskId,
|
|
3882
|
+
taskEpoch: args.epoch,
|
|
3883
|
+
outcome: args.action === "complete" ? "completed" : "cancelled",
|
|
3884
|
+
summary: args.summary
|
|
3885
|
+
}, ownerId);
|
|
3886
|
+
}
|
|
3887
|
+
}
|
|
3880
3888
|
async function handleBeginDesign(args, ownerId) {
|
|
3881
3889
|
let record = designTasks.retry(ownerId, args.requestId);
|
|
3882
3890
|
if (record) {
|
|
@@ -3979,9 +3987,16 @@ function registerProxiedTool(mcp, tool, ownerId) {
|
|
|
3979
3987
|
try {
|
|
3980
3988
|
const parsed = schema.parse(args);
|
|
3981
3989
|
const { taskId, taskEpoch, ...parsedArgs } = parsed;
|
|
3990
|
+
const readSessionId = EXACT_SESSION_READ_TOOLS.has(tool.name) ? getRecordProperty(parsedArgs, "sessionId") : void 0;
|
|
3991
|
+
const explicitSessionId = typeof readSessionId === "string" ? readSessionId : void 0;
|
|
3992
|
+
if (explicitSessionId) delete parsedArgs.sessionId;
|
|
3982
3993
|
if (taskId) designTasks.assertEpoch(taskId, ownerId, taskEpoch);
|
|
3983
|
-
|
|
3984
|
-
|
|
3994
|
+
let timeoutMs = toolTimeoutMs;
|
|
3995
|
+
if (tool.name === "get_code") timeoutMs = getCodeTimeoutMs;
|
|
3996
|
+
else if (tool.name === "get_design_system" && getRecordProperty(parsedArgs, "scope") !== "fonts" && getRecordProperty(parsedArgs, "scope") !== "pages" && !getRecordProperty(parsedArgs, "catalogId")) timeoutMs = getDesignSystemTimeoutMs;
|
|
3997
|
+
else if (tool.name === "get_structure" && (getRecordProperty(parsedArgs, "pageId") || getRecordProperty(parsedArgs, "pageKey"))) timeoutMs = pageStructureTimeoutMs;
|
|
3998
|
+
else if (tool.name === "apply_canvas") timeoutMs = applyCanvasTimeoutMs;
|
|
3999
|
+
const legacy = !taskId && !explicitSessionId ? extensionRegistry.getActive() : void 0;
|
|
3985
4000
|
if (legacy?.legacy) {
|
|
3986
4001
|
const payload = legacyToolPayload(tool.name, parsed);
|
|
3987
4002
|
const registration = register(legacy.id, timeoutMs);
|
|
@@ -3997,7 +4012,7 @@ function registerProxiedTool(mcp, tool, ownerId) {
|
|
|
3997
4012
|
}
|
|
3998
4013
|
return createToolResponse(tool.name, await registration.promise);
|
|
3999
4014
|
}
|
|
4000
|
-
const { extension: activeExt, session } = resolveDesignRoute(ownerId, taskId);
|
|
4015
|
+
const { extension: activeExt, session } = resolveDesignRoute(ownerId, taskId, true, explicitSessionId);
|
|
4001
4016
|
const runtimeIssues = getExtensionRuntimeIssues(activeExt.runtime);
|
|
4002
4017
|
if (runtimeIssues.length) throw createCodedError(TEMPAD_MCP_ERROR_CODES.RUNTIME_IDENTITY_MISMATCH, `${runtimeIssues.join("; ")}. Rebuild/reload the extension and start a fresh agent task.`);
|
|
4003
4018
|
const runtime = tool.name === "apply_canvas" ? buildAuthoringRuntimeEvidence(activeExt) : void 0;
|
|
@@ -4079,11 +4094,7 @@ function registerLocalTool(mcp, tool, ownerId) {
|
|
|
4079
4094
|
try {
|
|
4080
4095
|
const parsed = schema.parse(args);
|
|
4081
4096
|
const taskId = getRecordProperty(parsed, "taskId");
|
|
4082
|
-
if (![
|
|
4083
|
-
"end_design",
|
|
4084
|
-
"resume_design",
|
|
4085
|
-
"get_design_task"
|
|
4086
|
-
].includes(tool.name) && typeof taskId === "string") {
|
|
4097
|
+
if (!["manage_design_task", "get_design_task"].includes(tool.name) && typeof taskId === "string") {
|
|
4087
4098
|
designTasks.assertEpoch(taskId, ownerId, getRecordProperty(parsed, "taskEpoch"));
|
|
4088
4099
|
designTasks.touch(taskId, ownerId);
|
|
4089
4100
|
}
|
|
@@ -4098,16 +4109,16 @@ function registerLocalTool(mcp, tool, ownerId) {
|
|
|
4098
4109
|
};
|
|
4099
4110
|
registerToolFn(tool.name, registrationOptions, registerHandler);
|
|
4100
4111
|
}
|
|
4101
|
-
function createToolResponse(toolName, payload, runtime) {
|
|
4112
|
+
function createToolResponse(toolName, payload, runtime, includeLocalAssetPaths = true) {
|
|
4102
4113
|
const enrichedPayload = (() => {
|
|
4103
|
-
if (toolName === "get_screenshot") {
|
|
4114
|
+
if (toolName === "get_screenshot" && includeLocalAssetPaths) {
|
|
4104
4115
|
const screenshot = payload;
|
|
4105
4116
|
return {
|
|
4106
4117
|
...screenshot,
|
|
4107
4118
|
asset: addLocalAssetPath(screenshot.asset)
|
|
4108
4119
|
};
|
|
4109
4120
|
}
|
|
4110
|
-
if (toolName === "get_code") {
|
|
4121
|
+
if (toolName === "get_code" && includeLocalAssetPaths) {
|
|
4111
4122
|
const code = payload;
|
|
4112
4123
|
return code.assets ? {
|
|
4113
4124
|
...code,
|
|
@@ -4135,6 +4146,7 @@ function createToolResponse(toolName, payload, runtime) {
|
|
|
4135
4146
|
else rawResult = coercePayloadToToolResponse(enrichedPayload);
|
|
4136
4147
|
const resultBytes = measureCallToolResultBytes(rawResult);
|
|
4137
4148
|
if (resultBytes > 65536) {
|
|
4149
|
+
if (includeLocalAssetPaths && (toolName === "get_code" || toolName === "get_screenshot")) return createToolResponse(toolName, payload, runtime, false);
|
|
4138
4150
|
log.warn({
|
|
4139
4151
|
tool: toolName,
|
|
4140
4152
|
resultBytes,
|