@tempad-dev/mcp 0.8.0 → 0.9.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 +6 -2
- package/README.zh-Hans.md +5 -1
- package/dist/cli.mjs +3 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/hub.mjs +49 -27
- package/dist/hub.mjs.map +1 -1
- package/dist/{shared--YD93aQ6.mjs → shared-8rz2qWXn.mjs} +63 -41
- package/dist/shared-8rz2qWXn.mjs.map +1 -0
- package/package.json +5 -5
- package/dist/shared--YD93aQ6.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -28,7 +28,9 @@ 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.
|
|
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.
|
|
32
34
|
- `begin_design`, `resume_design`, `set_design_anchor`, and `end_design`: 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
|
|
@@ -50,7 +52,7 @@ 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.
|
|
55
|
+
- MCP **0.9.0** pairs with extension **0.22.0** and Agent Plugin **0.2.1**. Update the extension
|
|
54
56
|
and 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).
|
|
@@ -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,6 +26,8 @@ TemPad Dev 的 MCP server 将 coding agent 连接到浏览器中打开的 Figma
|
|
|
26
26
|
组件定义,以及本地或被定义直接引用的变量、集合/模式、样式和 shader 定义,不扫描画布
|
|
27
27
|
中的使用情况。游标可继续读取遗漏定义;使用同一目录精确查询某个引用时,返回该资源的
|
|
28
28
|
有界定义。使用 `scope: "fonts"` 可查询当前可用字体家族和精确原生样式,不读取文件资源。
|
|
29
|
+
`scope: "pages"` 无需扫描组件即可列出页面 ID;资源读取传入 `pageId` 时只扫描该页组件,
|
|
30
|
+
变量、样式和 shader 定义仍按文件范围读取。
|
|
29
31
|
- `begin_design`、`resume_design`、`set_design_anchor`、`end_design`:将画布写入绑定到设计任务,
|
|
30
32
|
恢复暂停的任务、设置状态栏锚点,以及结束或取消任务。Stop 会永久禁止旧任务写入,重新连接也不会恢复。
|
|
31
33
|
兼容 Codex App 的原生评论支持 Queue 和 Steer;确认接收后清空已提交草稿,无需等待执行完成。
|
|
@@ -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.9.0** 应配套使用扩展 **0.22.0** 和 Agent Plugin **0.2.1**。请更新扩展和已安装的 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-8rz2qWXn.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 SetDesignAnchorParametersSchema, A as GetDesignSystemParametersSchema, B as MCP_AUTO_ACTIVATE_GRACE_MS, C as DesignTaskIdSchema, D as GetAssetsParametersSchema, E as FigmaSessionSchema, F as LegacyMessageFromExtensionSchema, G as MCP_MAX_ASSET_STORE_BYTES, H as MCP_GET_CODE_TIMEOUT_MS, I as LegacyToolCallPayloadSchema, J as MCP_TOOL_INLINE_BUDGET_BYTES, K as MCP_MAX_PAYLOAD_BYTES, M as GetScreenshotParametersSchema, N as GetStructureParametersSchema, O as GetAssetsResultSchema, P as GetTokenDefsParametersSchema, Q as ResumeDesignParametersSchema, R as MCP_APPLY_CANVAS_TIMEOUT_MS, S as DesignAnchorSchema, T as EndDesignParametersSchema, U as MCP_GET_DESIGN_SYSTEM_TIMEOUT_MS, W as MCP_MAX_ASSET_BYTES, X as MessageFromExtensionSchema, Y as MCP_TOOL_TIMEOUT_MS, Z as RESUMABLE_DESIGN_TASK_STATUSES, a as HUB_RUNTIME_IDENTITY_PATH, at as buildApplyCanvasToolResult, b as ApplyCanvasResultSchema, c as RUNTIME_DIR, ct as buildGetDesignSystemToolResult, d as ensureFile, dt as buildGetTokenDefsToolResult, et as TEMPAD_MCP_BRIDGE_SUBPROTOCOL, f as getRecordProperty, ft as buildUploadAssetToolResult, g as clientDescriptor, h as bindRequestMetadata, ht as utf8Bytes, i as HUB_LOCK_UPDATE_MS, it as UploadAssetResultSchema, j as GetDesignSystemResultSchema, k as GetCodeParametersSchema, l as SOCK_PATH, lt as buildGetScreenshotToolResult, m as ClientEventSchema, mt as measureCallToolResultBytes, n as HUB_LOCK_PATH, nt as TEMPAD_MCP_ERROR_CODES, ot as buildGetAssetsToolResult, p as log, pt as formatDesignFeedback, q as MCP_PORT_CANDIDATES, r as HUB_LOCK_STALE_MS, rt as UploadAssetParametersSchema, s as PACKAGE_VERSION, st as buildGetCodeToolResult, t as ASSET_DIR, tt as TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS, u as ensureDir, ut as buildGetStructureToolResult, v as AGENT_CLIENTS, w as DesignTaskSchema, x as BeginDesignParametersSchema, y as ApplyCanvasParametersSchema, z as MCP_ASSET_TTL_MS } from "./shared-8rz2qWXn.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 {
|
|
@@ -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 `begin_design` 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 `begin_design` before research or writing, then 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;\nresume the same task with `resume_design`, 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.\n`end_design` is for a verified completed pass or explicit cancellation, not 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,\nbegin a fresh task with a new 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,7 +3316,7 @@ 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",
|
|
@@ -3360,7 +3365,7 @@ const TOOL_DEFS = [
|
|
|
3360
3365
|
}),
|
|
3361
3366
|
extTool({
|
|
3362
3367
|
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.
|
|
3368
|
+
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
3369
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
3365
3370
|
parameters: GetDesignSystemParametersSchema,
|
|
3366
3371
|
target: "extension",
|
|
@@ -3421,7 +3426,8 @@ const TOOL_DEFS = [
|
|
|
3421
3426
|
function extractToolErrorCode(error) {
|
|
3422
3427
|
const code = getRecordProperty(error, "code");
|
|
3423
3428
|
if (isTempadMcpErrorCode(code)) return code;
|
|
3424
|
-
const
|
|
3429
|
+
const cause = getRecordProperty(error, "cause");
|
|
3430
|
+
const causeCode = getRecordProperty(cause, "code");
|
|
3425
3431
|
if (isTempadMcpErrorCode(causeCode)) return causeCode;
|
|
3426
3432
|
}
|
|
3427
3433
|
function isTempadMcpErrorCode(value) {
|
|
@@ -3534,11 +3540,12 @@ function createDesignAnchorToolResponse(payload) {
|
|
|
3534
3540
|
};
|
|
3535
3541
|
}
|
|
3536
3542
|
function createInlineBudgetExceededToolResponse(toolName, actualBytes) {
|
|
3543
|
+
const guidance = getBudgetRetryGuidance(toolName);
|
|
3537
3544
|
return {
|
|
3538
3545
|
isError: true,
|
|
3539
3546
|
content: [{
|
|
3540
3547
|
type: "text",
|
|
3541
|
-
text: `Tool "${toolName}" exceeded the 64 KiB inline budget (${actualBytes} UTF-8 bytes > ${MCP_TOOL_INLINE_BUDGET_BYTES}). ${
|
|
3548
|
+
text: `Tool "${toolName}" exceeded the 64 KiB inline budget (${actualBytes} UTF-8 bytes > ${MCP_TOOL_INLINE_BUDGET_BYTES}). ${guidance}`
|
|
3542
3549
|
}]
|
|
3543
3550
|
};
|
|
3544
3551
|
}
|
|
@@ -3623,7 +3630,14 @@ function resolveListeningPort(server, candidate) {
|
|
|
3623
3630
|
//#region src/hub.ts
|
|
3624
3631
|
const SHUTDOWN_TIMEOUT = 2e3;
|
|
3625
3632
|
const SOCKET_PROBE_TIMEOUT_MS = 300;
|
|
3626
|
-
const
|
|
3633
|
+
const EXACT_SESSION_READ_TOOLS = /* @__PURE__ */ new Set([
|
|
3634
|
+
"get_code",
|
|
3635
|
+
"get_structure",
|
|
3636
|
+
"get_screenshot",
|
|
3637
|
+
"get_design_system",
|
|
3638
|
+
"get_token_defs"
|
|
3639
|
+
]);
|
|
3640
|
+
const { wsPortCandidates, toolTimeoutMs, getCodeTimeoutMs, getDesignSystemTimeoutMs, pageStructureTimeoutMs, applyCanvasTimeoutMs, maxPayloadBytes, maxAssetSizeBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig();
|
|
3627
3641
|
const extensionOriginPolicy = createExtensionOriginPolicy(allowedExtensionOrigins);
|
|
3628
3642
|
log.info({ version: PACKAGE_VERSION }, "TemPad MCP Hub starting...");
|
|
3629
3643
|
const extensionRegistry = new ExtensionRegistry(autoActivateGraceMs);
|
|
@@ -3816,7 +3830,7 @@ function scheduleAssetCleanup() {
|
|
|
3816
3830
|
return;
|
|
3817
3831
|
}
|
|
3818
3832
|
pruneExpiredAssets(assetTtlMs);
|
|
3819
|
-
const intervalMs = Math.min(assetTtlMs,
|
|
3833
|
+
const intervalMs = Math.min(assetTtlMs, 864e5);
|
|
3820
3834
|
unrefTimer(setInterval(() => {
|
|
3821
3835
|
pruneExpiredAssets(assetTtlMs);
|
|
3822
3836
|
}, intervalMs));
|
|
@@ -3979,9 +3993,16 @@ function registerProxiedTool(mcp, tool, ownerId) {
|
|
|
3979
3993
|
try {
|
|
3980
3994
|
const parsed = schema.parse(args);
|
|
3981
3995
|
const { taskId, taskEpoch, ...parsedArgs } = parsed;
|
|
3996
|
+
const readSessionId = EXACT_SESSION_READ_TOOLS.has(tool.name) ? getRecordProperty(parsedArgs, "sessionId") : void 0;
|
|
3997
|
+
const explicitSessionId = typeof readSessionId === "string" ? readSessionId : void 0;
|
|
3998
|
+
if (explicitSessionId) delete parsedArgs.sessionId;
|
|
3982
3999
|
if (taskId) designTasks.assertEpoch(taskId, ownerId, taskEpoch);
|
|
3983
|
-
|
|
3984
|
-
|
|
4000
|
+
let timeoutMs = toolTimeoutMs;
|
|
4001
|
+
if (tool.name === "get_code") timeoutMs = getCodeTimeoutMs;
|
|
4002
|
+
else if (tool.name === "get_design_system" && getRecordProperty(parsedArgs, "scope") !== "fonts" && getRecordProperty(parsedArgs, "scope") !== "pages" && !getRecordProperty(parsedArgs, "catalogId")) timeoutMs = getDesignSystemTimeoutMs;
|
|
4003
|
+
else if (tool.name === "get_structure" && (getRecordProperty(parsedArgs, "pageId") || getRecordProperty(parsedArgs, "pageKey"))) timeoutMs = pageStructureTimeoutMs;
|
|
4004
|
+
else if (tool.name === "apply_canvas") timeoutMs = applyCanvasTimeoutMs;
|
|
4005
|
+
const legacy = !taskId && !explicitSessionId ? extensionRegistry.getActive() : void 0;
|
|
3985
4006
|
if (legacy?.legacy) {
|
|
3986
4007
|
const payload = legacyToolPayload(tool.name, parsed);
|
|
3987
4008
|
const registration = register(legacy.id, timeoutMs);
|
|
@@ -3997,7 +4018,7 @@ function registerProxiedTool(mcp, tool, ownerId) {
|
|
|
3997
4018
|
}
|
|
3998
4019
|
return createToolResponse(tool.name, await registration.promise);
|
|
3999
4020
|
}
|
|
4000
|
-
const { extension: activeExt, session } = resolveDesignRoute(ownerId, taskId);
|
|
4021
|
+
const { extension: activeExt, session } = resolveDesignRoute(ownerId, taskId, true, explicitSessionId);
|
|
4001
4022
|
const runtimeIssues = getExtensionRuntimeIssues(activeExt.runtime);
|
|
4002
4023
|
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
4024
|
const runtime = tool.name === "apply_canvas" ? buildAuthoringRuntimeEvidence(activeExt) : void 0;
|
|
@@ -4098,16 +4119,16 @@ function registerLocalTool(mcp, tool, ownerId) {
|
|
|
4098
4119
|
};
|
|
4099
4120
|
registerToolFn(tool.name, registrationOptions, registerHandler);
|
|
4100
4121
|
}
|
|
4101
|
-
function createToolResponse(toolName, payload, runtime) {
|
|
4122
|
+
function createToolResponse(toolName, payload, runtime, includeLocalAssetPaths = true) {
|
|
4102
4123
|
const enrichedPayload = (() => {
|
|
4103
|
-
if (toolName === "get_screenshot") {
|
|
4124
|
+
if (toolName === "get_screenshot" && includeLocalAssetPaths) {
|
|
4104
4125
|
const screenshot = payload;
|
|
4105
4126
|
return {
|
|
4106
4127
|
...screenshot,
|
|
4107
4128
|
asset: addLocalAssetPath(screenshot.asset)
|
|
4108
4129
|
};
|
|
4109
4130
|
}
|
|
4110
|
-
if (toolName === "get_code") {
|
|
4131
|
+
if (toolName === "get_code" && includeLocalAssetPaths) {
|
|
4111
4132
|
const code = payload;
|
|
4112
4133
|
return code.assets ? {
|
|
4113
4134
|
...code,
|
|
@@ -4135,6 +4156,7 @@ function createToolResponse(toolName, payload, runtime) {
|
|
|
4135
4156
|
else rawResult = coercePayloadToToolResponse(enrichedPayload);
|
|
4136
4157
|
const resultBytes = measureCallToolResultBytes(rawResult);
|
|
4137
4158
|
if (resultBytes > 65536) {
|
|
4159
|
+
if (includeLocalAssetPaths && (toolName === "get_code" || toolName === "get_screenshot")) return createToolResponse(toolName, payload, runtime, false);
|
|
4138
4160
|
log.warn({
|
|
4139
4161
|
tool: toolName,
|
|
4140
4162
|
resultBytes,
|