@tempad-dev/mcp 0.5.1 → 0.6.1

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 CHANGED
@@ -17,9 +17,8 @@
17
17
 
18
18
  Quick setup helpers:
19
19
 
20
- - VS Code / Cursor / TRAE: use the deep links in TemPad Dev (Preferences → MCP server).
21
- - Windsurf: copy the JSON snippet from the same panel.
22
- - CLI: `claude mcp add --transport stdio "TemPad Dev" -- npx -y @tempad-dev/mcp@latest` or `codex mcp add "TemPad Dev" -- npx -y @tempad-dev/mcp@latest`.
20
+ - VS Code / Cursor / TRAE: use the deep links in TemPad Dev (Preferences → Agent integration).
21
+ - Claude Code / Codex CLI: copy or run the CLI command from the same panel.
23
22
 
24
23
  Supported tools/resources:
25
24
 
@@ -47,4 +46,4 @@ Optional environment variables:
47
46
 
48
47
  ## Requirements
49
48
 
50
- - Node.js 18+
49
+ - Node.js 18.20.0+
package/README.zh-Hans.md CHANGED
@@ -15,9 +15,8 @@
15
15
 
16
16
  快速配置方式:
17
17
 
18
- - VS Code / Cursor / TRAE:使用 TemPad Dev(Preferences → MCP server)中的深链接。
19
- - Windsurf:从同一面板复制 JSON 片段。
20
- - CLI:`claude mcp add --transport stdio "TemPad Dev" -- npx -y @tempad-dev/mcp@latest` 或 `codex mcp add "TemPad Dev" -- npx -y @tempad-dev/mcp@latest`。
18
+ - VS Code / Cursor / TRAE:使用 TemPad Dev(Preferences → Agent integration)中的深链接。
19
+ - Claude Code / Codex CLI:从同一面板复制或运行 CLI 命令。
21
20
 
22
21
  支持的工具和资源:
23
22
 
@@ -45,4 +44,4 @@
45
44
 
46
45
  ## 要求
47
46
 
48
- - Node.js 18+
47
+ - Node.js 18.20.0+
package/dist/cli.mjs CHANGED
@@ -1,11 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { a as SOCK_PATH, c as log, i as RUNTIME_DIR, n as LOCK_PATH, o as ensureDir, r as PACKAGE_VERSION } from "./shared-BljdV6bG.mjs";
2
+ import { a as LOCK_PATH, c as SOCK_PATH, d as log, l as ensureDir, o as PACKAGE_VERSION, s as RUNTIME_DIR } from "./shared-CcBuKkWC.mjs";
3
3
  import { spawn } from "node:child_process";
4
4
  import { connect } from "node:net";
5
5
  import { join } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import lockfile from "proper-lockfile";
8
-
9
8
  //#region src/cli.ts
10
9
  let activeSocket = null;
11
10
  let shuttingDown = false;
@@ -88,6 +87,16 @@ function startHub() {
88
87
  stdio: "ignore"
89
88
  });
90
89
  }
90
+ async function waitForHubStart(child) {
91
+ let foundExistingHub = false;
92
+ child.once("exit", (code) => {
93
+ foundExistingHub = code === 75;
94
+ });
95
+ const socket = await connectWithRetry(HUB_STARTUP_TIMEOUT);
96
+ if (foundExistingHub) log.info("Spawned Hub found an existing lifecycle lock. Using the active Hub.");
97
+ child.unref();
98
+ return socket;
99
+ }
91
100
  async function tryBecomeLeaderAndStartHub() {
92
101
  let releaseLock;
93
102
  try {
@@ -113,12 +122,10 @@ async function tryBecomeLeaderAndStartHub() {
113
122
  }
114
123
  child = startHub();
115
124
  child.on("error", (err) => log.error({ err }, "Hub child process error."));
116
- const socket = await connectWithRetry(HUB_STARTUP_TIMEOUT);
117
- child.unref();
118
- return socket;
125
+ return await waitForHubStart(child);
119
126
  } catch (err) {
120
127
  log.error({ err }, "Failed to start or connect to the Hub.");
121
- if (child && !child.killed) {
128
+ if (child && !child.killed && child.exitCode === null && child.signalCode === null) {
122
129
  log.warn(`Killing stale Hub process (PID: ${child.pid})...`);
123
130
  child.kill("SIGTERM");
124
131
  }
@@ -141,7 +148,7 @@ async function main() {
141
148
  }
142
149
  }
143
150
  main();
144
-
145
151
  //#endregion
146
- export { };
152
+ export {};
153
+
147
154
  //# sourceMappingURL=cli.mjs.map
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 { PACKAGE_VERSION, log, LOCK_PATH, RUNTIME_DIR, SOCK_PATH, ensureDir } 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 // 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 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 const socket = await connectWithRetry(HUB_STARTUP_TIMEOUT)\n child.unref()\n return socket\n } catch (err: unknown) {\n log.error({ err }, 'Failed to start or connect to the Hub.')\n if (child && !child.killed) {\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\nmain()\n"],"mappings":";;;;;;;;;AAaA,IAAI,eAA8B;AAClC,IAAI,eAAe;AAEnB,SAAS,oBAAoB;AAC3B,KAAI,CAAC,aAAc;AACnB,KAAI;AACF,eAAa,KAAK;SACZ;AAGR,KAAI;AACF,eAAa,SAAS;SAChB;AAGR,gBAAe;;AAGjB,SAAS,YAAY,QAAgB;AACnC,KAAI,aAAc;AAClB,gBAAe;AACf,KAAI,KAAK,GAAG,OAAO,qBAAqB;AACxC,oBAAmB;AACnB,SAAQ,KAAK,EAAE;;AAGjB,QAAQ,GAAG,gBAAgB,YAAY,mBAAmB,CAAC;AAC3D,QAAQ,GAAG,iBAAiB,YAAY,oBAAoB,CAAC;AAE7D,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;AAE7B,MAAM,YAAY,KADL,cAAc,IAAI,IAAI,KAAK,OAAO,KAAK,IAAI,CAAC,EAC5B,UAAU;AAEvC,UAAU,YAAY;AAEtB,SAAS,OAAO,QAA+B;AAC7C,QAAO,IAAI,SAAS,YAAY;AAC9B,MAAI,KAAK,+CAA+C;AACxD,iBAAe;EAEf,MAAM,mBAAmB;AACvB,eAAY,yBAAyB;;AAEvC,UAAQ,MAAM,KAAK,OAAO,WAAW;EAErC,MAAM,sBAAsB;AAC1B,OAAI,KAAK,qDAAqD;AAC9D,kBAAe;AACf,WAAQ,MAAM,eAAe,OAAO,WAAW;AAC/C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C3C,SAAS;IAAE,SAAS;IAAG,QAAQ;IAAK,YAAY;IAAI;GACpD,OAAO;GACR,CAAC;SACI;AACN,MAAI,KAAK,kDAAkD;AAC3D,SAAO,iBAAiB,oBAAoB;;AAG9C,KAAI,KAAK,+CAA+C;CACxD,IAAI,QAA6B;AACjC,KAAI;AACF,MAAI;AACF,UAAO,MAAM,YAAY;UACnB;AAEN,OAAI,KAAK,6CAA6C;;AAExD,UAAQ,UAAU;AAClB,QAAM,GAAG,UAAU,QAAQ,IAAI,MAAM,EAAE,KAAK,EAAE,2BAA2B,CAAC;EAC1E,MAAM,SAAS,MAAM,iBAAiB,oBAAoB;AAC1D,QAAM,OAAO;AACb,SAAO;UACA,KAAc;AACrB,MAAI,MAAM,EAAE,KAAK,EAAE,yCAAyC;AAC5D,MAAI,SAAS,CAAC,MAAM,QAAQ;AAC1B,OAAI,KAAK,mCAAmC,MAAM,IAAI,MAAM;AAC5D,SAAM,KAAK,UAAU;;AAEvB,QAAM;WACE;AACR,MAAI,YAAa,OAAM,aAAa;;;AAIxC,eAAe,OAAO;AACpB,KAAI,KAAK,EAAE,SAAS,iBAAiB,EAAE,gCAAgC;AAEvE,QAAO,KACL,KAAI;AAKF,QAAM,OAJS,MAAM,YAAY,CAAC,YAAY;AAC5C,OAAI,KAAK,kDAAkD;AAC3D,UAAO,4BAA4B;IACnC,CACkB;AACpB,MAAI,KAAK,wDAAwD;UAC1D,KAAc;AACrB,MAAI,MACF,EAAE,KAAK,EACP,0CAA0C,uBAAuB,IAAK,MACvE;AACD,QAAM,IAAI,SAAS,MAAM,WAAW,GAAG,qBAAqB,CAAC;;;AAKnE,MAAM"}
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 {\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 // 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\nmain()\n"],"mappings":";;;;;;;;AAqBA,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;AAE7B,MAAM,YAAY,KADL,cAAc,IAAI,IAAI,KAAK,OAAO,KAAK,GAAG,CAC7B,GAAG,SAAS;AAEtC,UAAU,WAAW;AAErB,SAAS,OAAO,QAA+B;CAC7C,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,KAAK,8CAA8C;EACvD,eAAe;EAEf,MAAM,mBAAmB;GACvB,YAAY,wBAAwB;EACtC;EACA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CAAC,CAAC,YAAY;GAC5C,IAAI,KAAK,iDAAiD;GAC1D,OAAO,2BAA2B;EACpC,CAAC,CACkB;EACnB,IAAI,KAAK,uDAAuD;CAClE,SAAS,KAAc;EACrB,IAAI,MACF,EAAE,IAAI,GACN,0CAA0C,uBAAuB,IAAK,KACxE;EACA,MAAM,IAAI,SAAS,MAAM,WAAW,GAAG,oBAAoB,CAAC;CAC9D;AAEJ;AAEA,KAAK"}
package/dist/hub.mjs CHANGED
@@ -1,7 +1,8 @@
1
- import { a as SOCK_PATH, c as log, i as RUNTIME_DIR, o as ensureDir, r as PACKAGE_VERSION, s as ensureFile, t as ASSET_DIR } from "./shared-BljdV6bG.mjs";
2
- import { createServer } from "node:net";
1
+ import { c as SOCK_PATH, d as log, i as HUB_LOCK_UPDATE_MS, l as ensureDir, n as HUB_LOCK_PATH, o as PACKAGE_VERSION, r as HUB_LOCK_STALE_MS, s as RUNTIME_DIR, t as ASSET_DIR, u as ensureFile } from "./shared-CcBuKkWC.mjs";
2
+ import { connect, createServer } from "node:net";
3
3
  import { join } from "node:path";
4
4
  import { URL } from "node:url";
5
+ import lockfile from "proper-lockfile";
5
6
  import { chmodSync, createReadStream, createWriteStream, existsSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
7
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
8
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -11,7 +12,6 @@ import { WebSocketServer } from "ws";
11
12
  import { createHash } from "node:crypto";
12
13
  import { createServer as createServer$1 } from "node:http";
13
14
  import { Transform, pipeline } from "node:stream";
14
-
15
15
  //#region ../shared/dist/index.js
16
16
  const MCP_PORT_CANDIDATES = [
17
17
  6220,
@@ -24,8 +24,7 @@ const MCP_TOOL_TIMEOUT_MS = 15e3;
24
24
  const MCP_AUTO_ACTIVATE_GRACE_MS = 1500;
25
25
  const MCP_MAX_ASSET_BYTES = 8 * 1024 * 1024;
26
26
  const MCP_ASSET_TTL_MS = 720 * 60 * 60 * 1e3;
27
- const MCP_HASH_HEX_LENGTH = 8;
28
- const MCP_HASH_PATTERN = new RegExp(`^[a-f0-9]{${MCP_HASH_HEX_LENGTH}}$`, "i");
27
+ const MCP_HASH_PATTERN = new RegExp(`^[a-f0-9]{8}$`, "i");
29
28
  const TEMPAD_MCP_ERROR_CODES = {
30
29
  NO_ACTIVE_EXTENSION: "NO_ACTIVE_EXTENSION",
31
30
  EXTENSION_TIMEOUT: "EXTENSION_TIMEOUT",
@@ -68,9 +67,6 @@ function buildCursorDeepLink() {
68
67
  function buildTraeDeepLink(protocol) {
69
68
  return `${protocol}://trae.ai-ide/mcp-import?type=stdio&name=${encodeURIComponent(SERVER_NAME)}&config=${buildCursorConfigBase64()}`;
70
69
  }
71
- function buildWindsurfConfigSnippet() {
72
- return JSON.stringify({ mcpServers: { [SERVER_NAME]: commandConfig } }, null, 2);
73
- }
74
70
  function buildCodexConfigSnippet() {
75
71
  return [
76
72
  `[mcp_servers.${SERVER_NAME}]`,
@@ -83,12 +79,8 @@ function buildCliCommand(prefix) {
83
79
  if (prefix === "claude") return `claude mcp add --transport stdio "${SERVER_NAME}" -- ${args}`;
84
80
  return `codex mcp add "${SERVER_NAME}" -- ${args}`;
85
81
  }
86
- const MCP_SERVER = {
87
- name: SERVER_NAME,
88
- command: SERVER_COMMAND,
89
- args: [...SERVER_ARGS]
90
- };
91
- const MCP_DEFAULT_CONFIG_SNIPPET = JSON.stringify({ [SERVER_NAME]: commandConfig }, null, 2);
82
+ [...SERVER_ARGS];
83
+ JSON.stringify({ [SERVER_NAME]: commandConfig }, null, 2);
92
84
  const MCP_CLIENTS_BY_ID = {
93
85
  vscode: {
94
86
  id: "vscode",
@@ -104,14 +96,6 @@ const MCP_CLIENTS_BY_ID = {
104
96
  supportsDeepLink: true,
105
97
  deepLink: buildCursorDeepLink()
106
98
  },
107
- windsurf: {
108
- id: "windsurf",
109
- name: "Windsurf",
110
- brandColor: ["#0B100F", "#F0F3F2"],
111
- supportsDeepLink: false,
112
- copyText: buildWindsurfConfigSnippet(),
113
- copyKind: "config"
114
- },
115
99
  claude: {
116
100
  id: "claude",
117
101
  name: "Claude Code",
@@ -139,14 +123,7 @@ const MCP_CLIENTS_BY_ID = {
139
123
  fallbackDeepLink: buildTraeDeepLink("trae-cn")
140
124
  }
141
125
  };
142
- const MCP_CLIENTS = [
143
- MCP_CLIENTS_BY_ID.vscode,
144
- MCP_CLIENTS_BY_ID.cursor,
145
- MCP_CLIENTS_BY_ID.windsurf,
146
- MCP_CLIENTS_BY_ID.claude,
147
- MCP_CLIENTS_BY_ID.codex,
148
- MCP_CLIENTS_BY_ID.trae
149
- ];
126
+ MCP_CLIENTS_BY_ID.vscode, MCP_CLIENTS_BY_ID.cursor, MCP_CLIENTS_BY_ID.claude, MCP_CLIENTS_BY_ID.codex, MCP_CLIENTS_BY_ID.trae;
150
127
  const RegisteredMessageSchema = z.object({
151
128
  type: z.literal("registered"),
152
129
  id: z.string()
@@ -167,7 +144,7 @@ const ToolCallMessageSchema = z.object({
167
144
  id: z.string(),
168
145
  payload: ToolCallPayloadSchema
169
146
  });
170
- const MessageToExtensionSchema = z.discriminatedUnion("type", [
147
+ z.discriminatedUnion("type", [
171
148
  RegisteredMessageSchema,
172
149
  StateMessageSchema,
173
150
  ToolCallMessageSchema
@@ -281,10 +258,9 @@ const GetAssetsResultSchema = z.object({
281
258
  assets: z.array(AssetDescriptorSchema),
282
259
  missing: z.array(z.string().min(1))
283
260
  });
284
-
285
261
  //#endregion
286
262
  //#region src/asset-utils.ts
287
- const HASH_FILENAME_PATTERN = new RegExp(`^([a-f0-9]{${MCP_HASH_HEX_LENGTH}})(?:\\.[a-z0-9]+)?$`, "i");
263
+ const HASH_FILENAME_PATTERN = new RegExp(`^([a-f0-9]{8})(?:\\.[a-z0-9]+)?$`, "i");
288
264
  const MIME_EXTENSION_OVERRIDES = new Map([["image/jpeg", "jpg"]]);
289
265
  const SAFE_IMAGE_EXTENSION_PATTERN = /^[a-z0-9-]+$/;
290
266
  function normalizeMimeType(mimeType) {
@@ -311,7 +287,6 @@ function getHashFromAssetFilename(filename) {
311
287
  const match = HASH_FILENAME_PATTERN.exec(filename);
312
288
  return match ? match[1] : null;
313
289
  }
314
-
315
290
  //#endregion
316
291
  //#region src/config.ts
317
292
  function parsePositiveInt(envValue, fallback) {
@@ -344,11 +319,10 @@ function getMcpServerConfig() {
344
319
  assetTtlMs: resolveAssetTtlMs()
345
320
  };
346
321
  }
347
-
348
322
  //#endregion
349
323
  //#region src/asset-http-server.ts
350
324
  const LOOPBACK_HOST = "127.0.0.1";
351
- const HASH_HEX_PATTERN = new RegExp(`^[a-f0-9]{${MCP_HASH_HEX_LENGTH}}$`, "i");
325
+ const HASH_HEX_PATTERN = new RegExp(`^[a-f0-9]{8}$`, "i");
352
326
  const { maxAssetSizeBytes } = getMcpServerConfig();
353
327
  function createAssetHttpServer(store) {
354
328
  const server = createServer$1(handleRequest);
@@ -552,7 +526,7 @@ function createAssetHttpServer(store) {
552
526
  }
553
527
  return;
554
528
  }
555
- if (hasher.digest("hex").slice(0, MCP_HASH_HEX_LENGTH) !== hash) {
529
+ if (hasher.digest("hex").slice(0, 8) !== hash) {
556
530
  cleanup();
557
531
  sendError(res, 400, "Hash Mismatch");
558
532
  return;
@@ -605,7 +579,6 @@ function createAssetHttpServer(store) {
605
579
  getBaseUrl
606
580
  };
607
581
  }
608
-
609
582
  //#endregion
610
583
  //#region src/asset-store.ts
611
584
  const INDEX_FILENAME = "assets.json";
@@ -766,11 +739,9 @@ function createAssetStore(options = {}) {
766
739
  flush
767
740
  };
768
741
  }
769
-
770
742
  //#endregion
771
743
  //#region src/instructions.md?raw
772
744
  var instructions_default = "You are connected to a Figma design file via TemPad Dev MCP.\n\nTreat tool outputs as design facts. Refactor only to match the user’s repo conventions; do not invent key style values.\n\nRules:\n\n- Never output any `data-hint-*` attributes from tool outputs (hints only).\n- If `get_code` warns `depth-cap`, keep the returned parent code as composition evidence and use returned `data-hint-id` values to choose narrower `get_code` follow-ups.\n- If `get_code` warns `shell`, read the inline code comment for omitted direct child ids, then call `get_code` for those ids in order and fill the results back into the returned shell.\n- Use `get_structure` only to resolve layout/overlap uncertainty; do not derive numeric values from images.\n- Tokens: `get_code.tokens` keys are canonical names (`--...`). Multi‑mode values use `${collectionName}:${modeName}`. Nodes may hint per-node overrides via `data-hint-variable-mode=\"Collection=Mode;...\"`.\n- Vectors: `vectorMode=smart` is the default. Treat the emitted markup as the source of truth for the current response; vector code is emitted as `<svg data-src=\"...\">` placeholders, but if asset upload fails after export the tool may inline the SVG as a fallback to preserve source of truth.\n- Themeable vectors: `themeable=true` means the SVG can safely adopt one contextual color channel. In `smart` mode, that color is typically already evidenced on the emitted `svg` root markup for the placeholder. It does not mean the SVG exposes multiple independent color parameters.\n- Assets: download bytes via `asset.url`. Asset resources are not exposed via MCP `resources/read`. Use `asset.themeable` only when an SVG still needs repo asset handling after you account for the Host app's vector policy.\n";
773
-
774
745
  //#endregion
775
746
  //#region src/request.ts
776
747
  const pendingCalls = /* @__PURE__ */ new Map();
@@ -838,7 +809,6 @@ function cleanupAll() {
838
809
  });
839
810
  pendingCalls.clear();
840
811
  }
841
-
842
812
  //#endregion
843
813
  //#region src/tools.ts
844
814
  const CONNECTIVITY_ERROR_CODES = new Set([
@@ -851,9 +821,9 @@ const CONNECTIVITY_ERROR_CODES = new Set([
851
821
  const SELECTION_ERROR_CODES = new Set([TEMPAD_MCP_ERROR_CODES.INVALID_SELECTION, TEMPAD_MCP_ERROR_CODES.NODE_NOT_VISIBLE]);
852
822
  const CONNECTIVITY_TROUBLESHOOTING_LINES = [
853
823
  "Troubleshooting:",
854
- "- In Figma, open TemPad Dev panel and enable MCP (Preferences → MCP server).",
824
+ "- In Figma, open TemPad Dev panel and enable the MCP server in Preferences → Agent integration.",
855
825
  "- If multiple Figma tabs are open, click the MCP badge to activate this tab.",
856
- "- Keep the Figma tab active/foreground while running MCP tools."
826
+ "- Keep the Figma tab active/foreground while using the MCP server."
857
827
  ];
858
828
  const SELECTION_TROUBLESHOOTING_LINE = "Tip: Select exactly one visible node, or pass nodeId.";
859
829
  function getRecordProperty$1(record, key) {
@@ -1017,21 +987,103 @@ function getBudgetRetryGuidance(toolName) {
1017
987
  default: return "Retry with a narrower request.";
1018
988
  }
1019
989
  }
1020
-
1021
990
  //#endregion
1022
991
  //#region src/hub.ts
1023
992
  const SHUTDOWN_TIMEOUT = 2e3;
993
+ const SOCKET_PROBE_TIMEOUT_MS = 300;
1024
994
  const { wsPortCandidates, toolTimeoutMs, maxPayloadBytes, autoActivateGraceMs, assetTtlMs } = getMcpServerConfig();
1025
995
  log.info({ version: PACKAGE_VERSION }, "TemPad MCP Hub starting...");
1026
996
  const extensions = [];
1027
997
  let consumerCount = 0;
1028
998
  let autoActivateTimer = null;
1029
999
  let selectedWsPort = 0;
1000
+ let releaseHubLock = null;
1001
+ let shuttingDown = false;
1002
+ let wss = null;
1030
1003
  const consumerSessions = /* @__PURE__ */ new Set();
1031
1004
  function getRecordProperty(record, key) {
1032
1005
  if (!record || typeof record !== "object") return;
1033
1006
  return Reflect.get(record, key);
1034
1007
  }
1008
+ function classifySocketProbeError(error) {
1009
+ if (error.code === "ENOENT") return "missing";
1010
+ if (error.code === "ECONNREFUSED" || error.code === "ENOTSOCK") return { staleCode: error.code };
1011
+ return null;
1012
+ }
1013
+ function probeHubSocket() {
1014
+ return new Promise((resolve, reject) => {
1015
+ let settled = false;
1016
+ let socket = null;
1017
+ function finish(callback) {
1018
+ if (settled) return;
1019
+ settled = true;
1020
+ clearTimeout(timer);
1021
+ if (socket) {
1022
+ socket.removeAllListeners();
1023
+ socket.destroy();
1024
+ }
1025
+ callback();
1026
+ }
1027
+ const timer = setTimeout(() => {
1028
+ finish(() => reject(/* @__PURE__ */ new Error(`Timed out probing Hub socket after ${SOCKET_PROBE_TIMEOUT_MS}ms.`)));
1029
+ }, SOCKET_PROBE_TIMEOUT_MS);
1030
+ function fail(error) {
1031
+ const result = classifySocketProbeError(error);
1032
+ finish(() => result ? resolve(result) : reject(error));
1033
+ }
1034
+ try {
1035
+ socket = connect(SOCK_PATH);
1036
+ socket.once("connect", () => finish(() => resolve("live")));
1037
+ socket.once("error", fail);
1038
+ } catch (error) {
1039
+ fail(error);
1040
+ }
1041
+ });
1042
+ }
1043
+ async function acquireHubLock() {
1044
+ try {
1045
+ return await lockfile.lock(HUB_LOCK_PATH, {
1046
+ retries: 0,
1047
+ stale: HUB_LOCK_STALE_MS,
1048
+ update: HUB_LOCK_UPDATE_MS,
1049
+ onCompromised: (err) => {
1050
+ log.error({ err }, "Hub lifecycle lock was compromised. Exiting.");
1051
+ process.exit(1);
1052
+ }
1053
+ });
1054
+ } catch (error) {
1055
+ log.info({ err: error }, "Another Hub owns the lifecycle lock. Exiting.");
1056
+ process.exit(75);
1057
+ }
1058
+ }
1059
+ async function releaseHubLockIfNeeded() {
1060
+ if (!releaseHubLock) return;
1061
+ const release = releaseHubLock;
1062
+ releaseHubLock = null;
1063
+ try {
1064
+ await release();
1065
+ } catch (err) {
1066
+ log.warn({ err }, "Failed to release Hub lifecycle lock.");
1067
+ }
1068
+ }
1069
+ async function probeSocketPath() {
1070
+ return process.platform === "win32" || existsSync(SOCK_PATH) ? await probeHubSocket() : "missing";
1071
+ }
1072
+ async function exitExistingHub() {
1073
+ await releaseHubLockIfNeeded();
1074
+ log.info({ sock: SOCK_PATH }, "Existing Hub is reachable. Exiting.");
1075
+ process.exit(75);
1076
+ }
1077
+ async function cleanSocketPath() {
1078
+ const probe = await probeSocketPath();
1079
+ if (probe === "live") return await exitExistingHub();
1080
+ if (probe === "missing" || process.platform === "win32") return;
1081
+ log.warn({
1082
+ sock: SOCK_PATH,
1083
+ code: probe.staleCode
1084
+ }, "Removing stale socket file.");
1085
+ rmSync(SOCK_PATH);
1086
+ }
1035
1087
  function enrichToolDefinition(tool) {
1036
1088
  if (tool.target === "extension") return tool;
1037
1089
  switch (tool.name) {
@@ -1077,8 +1129,6 @@ function getToolDefinition(name) {
1077
1129
  }
1078
1130
  const assetStore = createAssetStore();
1079
1131
  const assetHttpServer = createAssetHttpServer(assetStore);
1080
- await assetHttpServer.start();
1081
- scheduleAssetCleanup();
1082
1132
  function scheduleAssetCleanup() {
1083
1133
  if (assetTtlMs <= 0) {
1084
1134
  log.info("Asset TTL cleanup disabled (TEMPAD_MCP_ASSET_TTL_MS=0).");
@@ -1129,7 +1179,7 @@ function createMcpServer() {
1129
1179
  const mcp = new McpServer({
1130
1180
  name: "tempad-dev-mcp",
1131
1181
  version: PACKAGE_VERSION
1132
- }, instructions_default ? { instructions: instructions_default } : void 0);
1182
+ }, { instructions: instructions_default });
1133
1183
  const registered = [];
1134
1184
  for (const tool of TOOL_DEFINITIONS) {
1135
1185
  if ("exposed" in tool && tool.exposed === false) continue;
@@ -1224,7 +1274,7 @@ function createToolResponse(toolName, payload) {
1224
1274
  return coercePayloadToToolResponse(payload);
1225
1275
  })();
1226
1276
  const resultBytes = measureCallToolResultBytes(rawResult);
1227
- if (resultBytes > MCP_TOOL_INLINE_BUDGET_BYTES) {
1277
+ if (resultBytes > 65536) {
1228
1278
  log.warn({
1229
1279
  tool: toolName,
1230
1280
  resultBytes,
@@ -1303,6 +1353,8 @@ function rawDataToBuffer(raw) {
1303
1353
  return Buffer.concat(raw);
1304
1354
  }
1305
1355
  function shutdown() {
1356
+ if (shuttingDown) return;
1357
+ shuttingDown = true;
1306
1358
  log.info("Hub is shutting down...");
1307
1359
  consumerSessions.forEach((session) => {
1308
1360
  session.close().catch((err) => {
@@ -1315,21 +1367,12 @@ function shutdown() {
1315
1367
  netServer.close(() => log.info("Net server closed."));
1316
1368
  wss?.close(() => log.info("WebSocket server closed."));
1317
1369
  cleanupAll();
1370
+ releaseHubLockIfNeeded();
1318
1371
  unrefTimer(setTimeout(() => {
1319
1372
  log.warn("Shutdown timed out. Forcing exit.");
1320
1373
  process.exit(1);
1321
1374
  }, SHUTDOWN_TIMEOUT));
1322
1375
  }
1323
- try {
1324
- ensureDir(RUNTIME_DIR);
1325
- if (process.platform !== "win32" && existsSync(SOCK_PATH)) {
1326
- log.warn({ sock: SOCK_PATH }, "Removing stale socket file.");
1327
- rmSync(SOCK_PATH);
1328
- }
1329
- } catch (error) {
1330
- log.error({ err: error }, "Failed to initialize runtime environment.");
1331
- process.exit(1);
1332
- }
1333
1376
  const netServer = createServer((sock) => {
1334
1377
  const mcp = createMcpServer();
1335
1378
  consumerSessions.add(mcp);
@@ -1359,19 +1402,41 @@ const netServer = createServer((sock) => {
1359
1402
  }
1360
1403
  });
1361
1404
  });
1362
- netServer.on("error", (err) => {
1363
- log.error({ err }, "Net server error.");
1364
- process.exit(1);
1365
- });
1366
- netServer.listen(SOCK_PATH, () => {
1367
- try {
1368
- if (process.platform !== "win32") chmodSync(SOCK_PATH, 384);
1369
- } catch (err) {
1370
- log.error({ err }, "Failed to set socket permissions. Shutting down.");
1371
- process.exit(1);
1372
- }
1373
- log.info({ sock: SOCK_PATH }, "Hub socket ready.");
1374
- });
1405
+ async function initializeHubRuntime() {
1406
+ ensureDir(RUNTIME_DIR);
1407
+ if (await probeSocketPath() === "live") await exitExistingHub();
1408
+ releaseHubLock = await acquireHubLock();
1409
+ await cleanSocketPath();
1410
+ await assetHttpServer.start();
1411
+ scheduleAssetCleanup();
1412
+ }
1413
+ function listenConsumerSocket() {
1414
+ return new Promise((resolve, reject) => {
1415
+ const cleanup = () => {
1416
+ netServer.off("error", onError);
1417
+ netServer.off("listening", onListening);
1418
+ };
1419
+ const onError = (err) => {
1420
+ cleanup();
1421
+ reject(err);
1422
+ };
1423
+ const onListening = () => {
1424
+ cleanup();
1425
+ try {
1426
+ if (process.platform !== "win32") chmodSync(SOCK_PATH, 384);
1427
+ } catch (err) {
1428
+ netServer.close();
1429
+ reject(err);
1430
+ return;
1431
+ }
1432
+ log.info({ sock: SOCK_PATH }, "Hub socket ready.");
1433
+ resolve();
1434
+ };
1435
+ netServer.once("error", onError);
1436
+ netServer.once("listening", onListening);
1437
+ netServer.listen(SOCK_PATH);
1438
+ });
1439
+ }
1375
1440
  async function startWebSocketServer() {
1376
1441
  for (const candidate of wsPortCandidates) {
1377
1442
  const server = new WebSocketServer({
@@ -1393,7 +1458,7 @@ async function startWebSocketServer() {
1393
1458
  server.once("listening", onListening);
1394
1459
  });
1395
1460
  return {
1396
- wss: server,
1461
+ server,
1397
1462
  port: candidate
1398
1463
  };
1399
1464
  } catch (err) {
@@ -1403,23 +1468,35 @@ async function startWebSocketServer() {
1403
1468
  log.warn({ port: candidate }, "WebSocket port in use, trying next candidate.");
1404
1469
  continue;
1405
1470
  }
1406
- log.error({
1407
- err: errno,
1408
- port: candidate
1409
- }, "Failed to start WebSocket server.");
1410
- process.exit(1);
1471
+ throw errno;
1411
1472
  }
1412
1473
  }
1413
- log.error({ candidates: wsPortCandidates }, "Unable to start WebSocket server on any candidate port.");
1474
+ throw new Error(`Unable to start WebSocket server on candidate ports: ${wsPortCandidates.join(", ")}.`);
1475
+ }
1476
+ async function startHubRuntime() {
1477
+ await initializeHubRuntime();
1478
+ await listenConsumerSocket();
1479
+ netServer.on("error", (err) => {
1480
+ log.error({ err }, "Net server error.");
1481
+ process.exit(1);
1482
+ });
1483
+ const startedWebSocket = await startWebSocketServer();
1484
+ wss = startedWebSocket.server;
1485
+ selectedWsPort = startedWebSocket.port;
1486
+ return startedWebSocket.server;
1487
+ }
1488
+ async function abortStartup(error) {
1489
+ log.error({ err: error }, "Failed to initialize Hub runtime.");
1490
+ assetHttpServer.stop();
1491
+ await releaseHubLockIfNeeded();
1414
1492
  process.exit(1);
1415
1493
  }
1416
- const { wss, port } = await startWebSocketServer();
1417
- selectedWsPort = port;
1418
- wss.on("error", (err) => {
1494
+ const activeWss = await startHubRuntime().catch(abortStartup);
1495
+ activeWss.on("error", (err) => {
1419
1496
  log.error({ err }, "WebSocket server critical error. Exiting.");
1420
1497
  process.exit(1);
1421
1498
  });
1422
- wss.on("connection", (ws) => {
1499
+ activeWss.on("connection", (ws) => {
1423
1500
  const ext = {
1424
1501
  id: nanoid(),
1425
1502
  ws,
@@ -1498,7 +1575,7 @@ wss.on("connection", (ws) => {
1498
1575
  log.info({ port: selectedWsPort }, "WebSocket server ready.");
1499
1576
  process.on("SIGINT", shutdown);
1500
1577
  process.on("SIGTERM", shutdown);
1501
-
1502
1578
  //#endregion
1503
- export { };
1579
+ export {};
1580
+
1504
1581
  //# sourceMappingURL=hub.mjs.map