@pairdraw/mcp 0.22.0 → 0.22.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/dist/connect.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import "./rolldown-runtime-ClRpJifh.mjs";
3
- import { a as resolveCORSOrigins, f as pairingFingerprint, i as DEFAULT_CONNECT_APP_URL, n as startServer, t as MCP_VERSION } from "./server-BHPENxBB.mjs";
3
+ import { a as resolveCORSOrigins, f as pairingFingerprint, i as DEFAULT_CONNECT_APP_URL, n as startServer, t as MCP_VERSION } from "./server-Df4-we5n.mjs";
4
4
  import { n as getCompanionDir } from "./paths-BpcXnrbP.mjs";
5
5
  import { t as resolveMCPRoot } from "./root-BzmoiT2g.mjs";
6
6
  import { i as readToolPolicyFromEnv } from "./policy-CVfvvMB7.mjs";
@@ -158,10 +158,78 @@ function isProcessAlive(pid) {
158
158
  return true;
159
159
  }
160
160
  }
161
+ /** Resolves after `ms`, for polling a process that is shutting down. */
162
+ function sleep(ms) {
163
+ const { promise, resolve } = Promise.withResolvers();
164
+ setTimeout(() => resolve(void 0), ms);
165
+ return promise;
166
+ }
167
+ /**
168
+ * The fields that prove a `/health` answer comes from Pairdraw's own MCP server. `tools` is
169
+ * present only when the request carried the token, so a tokenless probe leaves it out.
170
+ */
171
+ const discoveredServerHealthSchema = v.object({
172
+ status: v.picklist(["ok", "no_app"]),
173
+ version: v.string(),
174
+ authRequired: v.boolean(),
175
+ agentSessionEvents: v.literal(true),
176
+ tools: v.optional(v.array(v.unknown()))
177
+ });
178
+ /**
179
+ * Whether the process to stop is the server Pairdraw's discovery file names. A stale file can
180
+ * outlive its server and a reused PID would then name another process, so the server at the
181
+ * recorded port must still answer health with the version the file recorded.
182
+ *
183
+ * A socket-only entry (no TCP port) is refused: the desktop app talks HTTP, and a socket
184
+ * connection cannot authenticate the version the way `/health` does.
185
+ */
186
+ async function isDiscoveredServer(pid, info) {
187
+ if (info.pid !== pid) return false;
188
+ if (info.httpPort <= 0) return false;
189
+ const token = info.authToken?.trim() || null;
190
+ if (info.authRequired && !token) return false;
191
+ try {
192
+ const response = await fetch(`http://127.0.0.1:${info.httpPort}/health`, {
193
+ headers: token ? { Authorization: `Bearer ${token}` } : void 0,
194
+ signal: AbortSignal.timeout(2e3)
195
+ });
196
+ if (!response.ok) return false;
197
+ const parsed = v.safeParse(discoveredServerHealthSchema, await response.json());
198
+ if (!parsed.success) return false;
199
+ const health = parsed.output;
200
+ if (health.version !== info.version) return false;
201
+ if (health.authRequired !== info.authRequired) return false;
202
+ if (token && health.tools === void 0) return false;
203
+ return true;
204
+ } catch {
205
+ return false;
206
+ }
207
+ }
208
+ /**
209
+ * Stops the server recorded in Pairdraw's discovery file, after checking it is the process the
210
+ * file names. Used by `pairdraw-mcp-http --stop <pid>` so the app can replace a server a previous
211
+ * app version left running without killing an unrelated process. Returns false when the file and
212
+ * the answering server do not agree, or the process is still running after `waitMs`.
213
+ */
214
+ async function stopDiscoveredServer(pid, waitMs = 5e3) {
215
+ const info = await readDiscoveryFile();
216
+ if (!info || !await isDiscoveredServer(pid, info)) return false;
217
+ try {
218
+ process.kill(pid, "SIGTERM");
219
+ } catch {
220
+ return false;
221
+ }
222
+ const deadline = Date.now() + waitMs;
223
+ while (isProcessAlive(pid)) {
224
+ if (Date.now() >= deadline) return false;
225
+ await sleep(50);
226
+ }
227
+ return true;
228
+ }
161
229
  function isEnoent(e) {
162
230
  return e instanceof Error && "code" in e && e.code === "ENOENT";
163
231
  }
164
232
  //#endregion
165
- export { writeDiscoveryFile as a, removeStaleSocket as i, readDiscoveryFile as n, removeDiscoveryFile as r, parseDiscoveryInfo as t };
233
+ export { removeDiscoveryFile as a, writeDiscoveryFile as c, readDiscoveryFile as i, isProcessAlive as n, removeStaleSocket as o, parseDiscoveryInfo as r, stopDiscoveredServer as s, isDiscoveredServer as t };
166
234
 
167
- //# sourceMappingURL=discovery-BIJ7923d.mjs.map
235
+ //# sourceMappingURL=discovery-axCcZws7.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discovery-axCcZws7.mjs","names":[],"sources":["../src/transport/discovery.ts"],"sourcesContent":["import { access, constants, lstat, readFile, unlink } from 'node:fs/promises'\nimport { Socket } from 'node:net'\n\nimport * as v from 'valibot'\n\nimport { writeFileAtomic } from '@pairdraw/core/node/fs'\n\nimport { MCP_TOOL_SCOPES, type MCPToolScope } from '#mcp/tool/scope'\nimport { getDiscoveryPath, getSocketPath, platformHasUnixSockets } from '#mcp/transport/paths'\n\n/**\n * Metadata written to the discovery file so clients can auto-locate\n * the running MCP server without knowing the socket path or TCP port.\n *\n * WARNING: The discovery file contains a plaintext auth token. Do not sync\n * this file to cloud storage or include it in backups without encryption.\n * Any process running as the same user can read this file.\n */\nexport interface DiscoveryInfo {\n pid: number\n /** Unix domain socket path, or null on platforms that don't support them (Windows). */\n socketPath: string | null\n httpPort: number\n authRequired: boolean\n authToken: string | null\n version: string\n startedAt: string\n disabledTools?: string[]\n /** What MCP clients can reach; stdio clients started outside the app follow it. */\n scope?: MCPToolScope\n}\n\nconst discoveryInfoSchema = v.pipe(\n v.string(),\n v.parseJson(),\n v.object({\n pid: v.pipe(v.number(), v.integer(), v.minValue(1)),\n version: v.string(),\n httpPort: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(65535)),\n authRequired: v.boolean(),\n startedAt: v.string(),\n socketPath: v.nullable(v.pipe(v.string(), v.nonEmpty())),\n authToken: v.nullable(v.string()),\n disabledTools: v.optional(v.array(v.string()), () => []),\n scope: v.optional(v.picklist(MCP_TOOL_SCOPES), 'document')\n })\n) satisfies v.GenericSchema<string, DiscoveryInfo>\n\n/** Parse discovery file contents, or null when the file is not valid discovery JSON. */\nexport function parseDiscoveryInfo(raw: string): DiscoveryInfo | null {\n const result = v.safeParse(discoveryInfoSchema, raw)\n return result.success ? result.output : null\n}\n\n/**\n * Writes the discovery JSON file at the platform-appropriate location.\n * Overwrites any existing file (from a previous server instance).\n *\n * The file is written all at once with `0o600` permissions, replacing a symlink at the path\n * rather than writing through it, so readers never see half a file and concurrent writers never\n * interleave.\n *\n * WARNING: The auth token is written in plaintext. Do not sync the discovery\n * file to cloud storage or include it in backups without encryption.\n */\nexport async function writeDiscoveryFile(info: DiscoveryInfo): Promise<void> {\n const path = await getDiscoveryPath()\n const json = JSON.stringify(info, null, 2)\n await writeFileAtomic(path, json, { mode: 0o600 })\n}\n\n/**\n * Reads the discovery file. Returns null if:\n * - The file does not exist\n * - The file cannot be parsed\n * - The recorded PID is no longer running (stale file)\n *\n * On success, returns the parsed DiscoveryInfo.\n */\nexport async function readDiscoveryFile(): Promise<DiscoveryInfo | null> {\n const path = await getDiscoveryPath()\n let raw: string\n try {\n raw = await readFile(path, 'utf-8')\n } catch (e) {\n if (!isEnoent(e))\n process.stderr.write(\n ` Discovery: read warning (${e instanceof Error ? e.message : String(e)})\\n`\n )\n return null\n }\n\n const info = parseDiscoveryInfo(raw)\n if (!info) return null\n if (!isProcessAlive(info.pid)) return null\n\n return info\n}\n\n/**\n * Removes the discovery file. Does not throw if the file does not exist.\n */\nexport async function removeDiscoveryFile(): Promise<void> {\n const path = await getDiscoveryPath()\n try {\n await unlink(path)\n } catch (e) {\n if (!isEnoent(e)) throw e\n }\n}\n\n// TCP health check is more reliable than Unix socket connections in some\n// runtimes (Bun on Linux). We read the discovery file directly instead of\n// using readDiscoveryFile() to bypass the isProcessAlive PID check — the\n// TCP fetch is a stronger liveness probe than process.kill(pid, 0).\nasync function isSocketLiveViaTcp(socketPath: string): Promise<boolean> {\n let discoveryPath: string\n try {\n discoveryPath = await getDiscoveryPath()\n } catch {\n return false\n }\n const raw = await readFile(discoveryPath, 'utf-8').catch(() => null)\n if (!raw) return false\n const info = parseDiscoveryInfo(raw)\n if (!info || info.socketPath !== socketPath) return false\n\n // If TCP is disabled (httpPort <= 0), fall back to PID-based liveness check\n if (info.httpPort <= 0) {\n return isProcessAlive(info.pid)\n }\n\n return fetch(`http://127.0.0.1:${info.httpPort}/health`, {\n signal: AbortSignal.timeout(2000)\n })\n .then(() => true)\n .catch((e) => {\n // A timeout means the process is likely alive but slow — don't delete its socket\n if (e instanceof Error && e.name === 'TimeoutError') return true\n return false\n })\n}\n\n/**\n * Direct Unix-socket connection probe. A server binds the socket before\n * writeDiscovery(), so isSocketLiveViaTcp() can return false during that\n * window. This probe connects directly to the socket path — a successful\n * connection or timeout means the socket is live; only ECONNREFUSED means\n * no process is listening.\n */\nfunction probeSocketLive(socketPath: string): Promise<boolean> {\n return new Promise((resolve) => {\n let settled = false\n const socket = new Socket()\n const finish = (result: boolean) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n socket.destroy()\n // oxlint-disable-next-line no-multiple-resolved -- settled flag guarantees single resolution\n resolve(result)\n }\n const timer = setTimeout(() => finish(true), 1000)\n socket.once('connect', () => finish(true))\n socket.once('error', (err) => {\n const code = (err as NodeJS.ErrnoException).code\n finish(code !== 'ECONNREFUSED')\n })\n socket.connect(socketPath)\n })\n}\n\n/**\n * Removes a stale Unix domain socket file if it exists and is not live.\n * A socket is considered stale if no process is listening on it.\n */\nexport async function removeStaleSocket(socketPathOverride?: string): Promise<void> {\n if (!platformHasUnixSockets()) return\n\n const socketPath = socketPathOverride ?? (await getSocketPath())\n let exists: boolean\n try {\n await access(socketPath, constants.F_OK)\n exists = true\n } catch {\n exists = false\n }\n\n if (!exists) return\n\n // Verify the path is actually a socket before unlinking it.\n // A misconfigured PAIRDRAW_MCP_SOCKET could point at a regular file;\n // we must never delete non-socket paths.\n const stat = await lstat(socketPath).catch((e) => {\n if (isEnoent(e)) return null\n throw e\n })\n if (!stat) return\n if (!stat.isSocket()) {\n throw new Error(`Refusing to remove non-socket path: ${socketPath}`)\n }\n\n if (await probeSocketLive(socketPath)) return\n if (await isSocketLiveViaTcp(socketPath)) return\n\n // No live server claims this socket — remove the stale file.\n try {\n await unlink(socketPath)\n } catch (e) {\n if (e instanceof Error && 'code' in e && (e as NodeJS.ErrnoException).code !== 'ENOENT') {\n process.stderr.write(`Failed to remove stale socket: ${e.message}\\n`)\n }\n }\n}\n\n/**\n * Checks if a process with the given PID is still running.\n * Uses process.kill(pid, 0) which doesn't send a signal, just checks existence.\n * Works on both Unix and Windows.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (e) {\n if (e instanceof Error && 'code' in e && (e as NodeJS.ErrnoException).code === 'ESRCH') {\n return false\n }\n return true\n }\n}\n\n/** Resolves after `ms`, for polling a process that is shutting down. */\nfunction sleep(ms: number): Promise<void> {\n const { promise, resolve } = Promise.withResolvers<undefined>()\n setTimeout(() => resolve(undefined), ms)\n return promise\n}\n\n/**\n * The fields that prove a `/health` answer comes from Pairdraw's own MCP server. `tools` is\n * present only when the request carried the token, so a tokenless probe leaves it out.\n */\nconst discoveredServerHealthSchema = v.object({\n status: v.picklist(['ok', 'no_app']),\n version: v.string(),\n authRequired: v.boolean(),\n agentSessionEvents: v.literal(true),\n tools: v.optional(v.array(v.unknown()))\n})\n\n/**\n * Whether the process to stop is the server Pairdraw's discovery file names. A stale file can\n * outlive its server and a reused PID would then name another process, so the server at the\n * recorded port must still answer health with the version the file recorded.\n *\n * A socket-only entry (no TCP port) is refused: the desktop app talks HTTP, and a socket\n * connection cannot authenticate the version the way `/health` does.\n */\nexport async function isDiscoveredServer(pid: number, info: DiscoveryInfo): Promise<boolean> {\n if (info.pid !== pid) return false\n if (info.httpPort <= 0) return false\n const token = info.authToken?.trim() || null\n // A server that needs auth cannot be identified without the token, so never probe it blind.\n if (info.authRequired && !token) return false\n try {\n const response = await fetch(`http://127.0.0.1:${info.httpPort}/health`, {\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n signal: AbortSignal.timeout(2000)\n })\n if (!response.ok) return false\n const parsed = v.safeParse(discoveredServerHealthSchema, await response.json())\n if (!parsed.success) return false\n const health = parsed.output\n if (health.version !== info.version) return false\n if (health.authRequired !== info.authRequired) return false\n if (token && health.tools === undefined) return false\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Stops the server recorded in Pairdraw's discovery file, after checking it is the process the\n * file names. Used by `pairdraw-mcp-http --stop <pid>` so the app can replace a server a previous\n * app version left running without killing an unrelated process. Returns false when the file and\n * the answering server do not agree, or the process is still running after `waitMs`.\n */\nexport async function stopDiscoveredServer(pid: number, waitMs = 5000): Promise<boolean> {\n const info = await readDiscoveryFile()\n if (!info || !(await isDiscoveredServer(pid, info))) return false\n try {\n process.kill(pid, 'SIGTERM')\n } catch {\n return false\n }\n const deadline = Date.now() + waitMs\n while (isProcessAlive(pid)) {\n if (Date.now() >= deadline) return false\n await sleep(50)\n }\n return true\n}\n\nfunction isEnoent(e: unknown): boolean {\n return e instanceof Error && 'code' in e && (e as NodeJS.ErrnoException).code === 'ENOENT'\n}\n"],"mappings":";;;;;;;;AAgCA,MAAM,sBAAsB,EAAE,KAC5B,EAAE,OAAO,GACT,EAAE,UAAU,GACZ,EAAE,OAAO;CACP,KAAK,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,QAAQ,GAAG,EAAE,SAAS,CAAC,CAAC;CAClD,SAAS,EAAE,OAAO;CAClB,UAAU,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,QAAQ,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,SAAS,KAAK,CAAC;CAC1E,cAAc,EAAE,QAAQ;CACxB,WAAW,EAAE,OAAO;CACpB,YAAY,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,SAAS,CAAC,CAAC;CACvD,WAAW,EAAE,SAAS,EAAE,OAAO,CAAC;CAChC,eAAe,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;CACvD,OAAO,EAAE,SAAS,EAAE,SAAS,eAAe,GAAG,UAAU;AAC3D,CAAC,CACH;;AAGA,SAAgB,mBAAmB,KAAmC;CACpE,MAAM,SAAS,EAAE,UAAU,qBAAqB,GAAG;CACnD,OAAO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,QAAW,OAAO;EAChD,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;AAQA,eAAsB,qBAAqB,KAAa,SAAS,KAAwB;CACvF,MAAM,OAAO,MAAM,kBAAkB;CACrC,IAAI,CAAC,QAAQ,CAAE,MAAM,mBAAmB,KAAK,IAAI,GAAI,OAAO;CAC5D,IAAI;EACF,QAAQ,KAAK,KAAK,SAAS;CAC7B,QAAQ;EACN,OAAO;CACT;CACA,MAAM,WAAW,KAAK,IAAI,IAAI;CAC9B,OAAO,eAAe,GAAG,GAAG;EAC1B,IAAI,KAAK,IAAI,KAAK,UAAU,OAAO;EACnC,MAAM,MAAM,EAAE;CAChB;CACA,OAAO;AACT;AAEA,SAAS,SAAS,GAAqB;CACrC,OAAO,aAAa,SAAS,UAAU,KAAM,EAA4B,SAAS;AACpF"}
@@ -54,6 +54,28 @@ declare function removeDiscoveryFile(): Promise<void>;
54
54
  * A socket is considered stale if no process is listening on it.
55
55
  */
56
56
  declare function removeStaleSocket(socketPathOverride?: string): Promise<void>;
57
+ /**
58
+ * Checks if a process with the given PID is still running.
59
+ * Uses process.kill(pid, 0) which doesn't send a signal, just checks existence.
60
+ * Works on both Unix and Windows.
61
+ */
62
+ declare function isProcessAlive(pid: number): boolean;
63
+ /**
64
+ * Whether the process to stop is the server Pairdraw's discovery file names. A stale file can
65
+ * outlive its server and a reused PID would then name another process, so the server at the
66
+ * recorded port must still answer health with the version the file recorded.
67
+ *
68
+ * A socket-only entry (no TCP port) is refused: the desktop app talks HTTP, and a socket
69
+ * connection cannot authenticate the version the way `/health` does.
70
+ */
71
+ declare function isDiscoveredServer(pid: number, info: DiscoveryInfo): Promise<boolean>;
72
+ /**
73
+ * Stops the server recorded in Pairdraw's discovery file, after checking it is the process the
74
+ * file names. Used by `pairdraw-mcp-http --stop <pid>` so the app can replace a server a previous
75
+ * app version left running without killing an unrelated process. Returns false when the file and
76
+ * the answering server do not agree, or the process is still running after `waitMs`.
77
+ */
78
+ declare function stopDiscoveredServer(pid: number, waitMs?: number): Promise<boolean>;
57
79
  //#endregion
58
- export { DiscoveryInfo, parseDiscoveryInfo, readDiscoveryFile, removeDiscoveryFile, removeStaleSocket, writeDiscoveryFile };
80
+ export { DiscoveryInfo, isDiscoveredServer, isProcessAlive, parseDiscoveryInfo, readDiscoveryFile, removeDiscoveryFile, removeStaleSocket, stopDiscoveredServer, writeDiscoveryFile };
59
81
  //# sourceMappingURL=discovery.d.mts.map
@@ -1,2 +1,2 @@
1
- import { a as writeDiscoveryFile, i as removeStaleSocket, n as readDiscoveryFile, r as removeDiscoveryFile, t as parseDiscoveryInfo } from "./discovery-BIJ7923d.mjs";
2
- export { parseDiscoveryInfo, readDiscoveryFile, removeDiscoveryFile, removeStaleSocket, writeDiscoveryFile };
1
+ import { a as removeDiscoveryFile, c as writeDiscoveryFile, i as readDiscoveryFile, n as isProcessAlive, o as removeStaleSocket, r as parseDiscoveryInfo, s as stopDiscoveredServer, t as isDiscoveredServer } from "./discovery-axCcZws7.mjs";
2
+ export { isDiscoveredServer, isProcessAlive, parseDiscoveryInfo, readDiscoveryFile, removeDiscoveryFile, removeStaleSocket, stopDiscoveredServer, writeDiscoveryFile };
package/dist/index.mjs CHANGED
@@ -1,9 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import "./rolldown-runtime-ClRpJifh.mjs";
3
- import { a as resolveCORSOrigins, d as devAgentBridgeFromEnv, n as startServer, t as MCP_VERSION } from "./server-BHPENxBB.mjs";
3
+ import { a as resolveCORSOrigins, d as devAgentBridgeFromEnv, n as startServer, t as MCP_VERSION } from "./server-Df4-we5n.mjs";
4
4
  import { t as resolveMCPRoot } from "./root-BzmoiT2g.mjs";
5
5
  import { i as readToolPolicyFromEnv } from "./policy-CVfvvMB7.mjs";
6
+ import { s as stopDiscoveredServer } from "./discovery-axCcZws7.mjs";
6
7
  //#region src/index.ts
8
+ const stopAt = process.argv.indexOf("--stop");
9
+ if (stopAt !== -1) {
10
+ const pid = Number(process.argv[stopAt + 1]);
11
+ const stopped = Number.isSafeInteger(pid) && pid > 0 ? await stopDiscoveredServer(pid) : false;
12
+ process.exit(stopped ? 0 : 2);
13
+ }
7
14
  if (process.argv.includes("--version")) {
8
15
  process.stdout.write(`${MCP_VERSION}\n`);
9
16
  process.exit(0);
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { devAgentBridgeFromEnv } from '#mcp/agents/index'\nimport { resolveMCPRoot } from '#mcp/root'\nimport { MCP_VERSION, startServer } from '#mcp/server'\nimport { readToolPolicyFromEnv } from '#mcp/tool/policy'\nimport { resolveCORSOrigins } from '#mcp/transport/origins'\n\nif (process.argv.includes('--version')) {\n process.stdout.write(`${MCP_VERSION}\\n`)\n process.exit(0)\n}\n\nif (process.argv.includes('--help') || process.argv.includes('-h')) {\n process.stdout.write(\n `pairdraw-mcp-http\\n\\n` +\n `Start the Pairdraw MCP server.\\n\\n` +\n `On macOS/Linux, the server listens on a Unix domain socket by default\\n` +\n `with optional TCP for browser clients. On Windows, only TCP is available.\\n\\n` +\n `Options:\\n` +\n ` --help, -h Show this help message\\n` +\n ` --version Print the version\\n\\n` +\n `Environment variables:\\n` +\n ` PORT TCP port (default: 7600, set to 0 to disable TCP)\\n` +\n ` PAIRDRAW_MCP_SOCKET Override Unix socket path (recorded in the discovery file)\\n` +\n ` PAIRDRAW_MCP_DISCOVERY_PATH Override discovery file (mcp.json) location; defaults to the\\n` +\n ` platform path. Parent dir created 0o700. Mainly for test isolation.\\n` +\n ` PAIRDRAW_MCP_TCP Deprecated — TCP is controlled by PORT (>0 = on, 0 = off)\\n` +\n ` PAIRDRAW_MCP_AUTH_TOKEN Bearer token for MCP and RPC auth\\n` +\n ` PAIRDRAW_MCP_ROOT Allowed directory for file-scoped tools (default: home directory on Windows, current working directory elsewhere)\\n` +\n ` PAIRDRAW_MCP_EVAL Set to 1 to enable the eval tool\\n` +\n ` PAIRDRAW_MCP_SESSION_IDLE_TIMEOUT_MS\\n` +\n ` Close sessions idle this long, in ms (default: 900000;\\n` +\n ` 0 disables). An open GET/SSE stream is not activity.\\n` +\n ` PAIRDRAW_MCP_DISABLED_TOOLS Comma-separated tool names to omit\\n` +\n ` PAIRDRAW_MCP_SCOPE \"selection\" to let clients read only the selected layers\\n` +\n ` (default: \"document\")\\n` +\n ` PAIRDRAW_MCP_CORS_ORIGIN Allowed CORS origins, comma-separated.\\n` +\n ` Defaults to the desktop app origin, since the app\\n` +\n ` webview is the only view that calls this server.\\n` +\n ` PAIRDRAW_MCP_APP_TIMEOUT_MS If set, close the server and remove its discovery\\n` +\n ` file after no app is attached for this many ms. The\\n` +\n ` grace period starts at startup and after disconnects.\\n` +\n ` Unset/0 disables it (default) — do not set this for\\n` +\n ` manual/CLI use, since nothing may ever register.\\n` +\n ` PAIRDRAW_MCP_EXIT_ON_STDIN_CLOSE Set to 1 to shut down when stdin closes, so a\\n` +\n ` parent that starts the server through a shell wrapper\\n` +\n ` can stop it by closing the pipe. Unset for manual/CLI use.\\n` +\n ` PAIRDRAW_MCP_AGENTS Set to 1, with the two variables below, to start the agent\\n` +\n ` bridge for one browser tab that the parent process gave\\n` +\n ` the same tokens, as \\`bun run dev\\` does; no pairing link.\\n` +\n ` The tokens are never written to the discovery file,\\n` +\n ` and the eval tool stays off.\\n` +\n ` PAIRDRAW_MCP_AGENT_SESSION The tab's session token: 64 lowercase hex characters.\\n` +\n ` PAIRDRAW_MCP_AGENT_TOKEN The token the tab hands its agents, which reaches only\\n` +\n ` /mcp: 64 lowercase hex characters, not the session token.\\n`\n )\n process.exit(0)\n}\n\nconst rawPortText = (process.env.PORT ?? '7600').trim()\n// Reject non-digit strings (including hex like \"0x50\" and partially-numeric like\n// \"7600abc\") — Number.parseInt would silently parse these, masking misconfig.\nif (!/^\\d+$/.test(rawPortText)) {\n process.stderr.write(`Error: PORT must be an integer in 0–65535, got \"${process.env.PORT}\"\\n`)\n process.exit(1)\n}\nconst rawPort = Number.parseInt(rawPortText, 10)\n// Validate PORT: must be an integer in 0–65535. 0 means \"disable TCP\".\nif (rawPort < 0 || rawPort > 65535) {\n process.stderr.write(`Error: PORT must be an integer in 0–65535, got \"${process.env.PORT}\"\\n`)\n process.exit(1)\n}\nconst port = rawPort\n// PAIRDRAW_MCP_TCP is accepted for backward compat but has no effect —\n// the PORT value alone determines whether TCP is enabled (PORT=0 is the kill switch).\nconst withTcp = port > 0\n\nconst MAX_TIMEOUT_MS = 2_147_483_647\n\n/** Read a millisecond timeout from the environment, exiting on an invalid value. */\nfunction readTimeoutEnv(name: string): number | undefined {\n const text = process.env[name]?.trim()\n if (!text) return undefined\n const timeoutMs = Number(text)\n if (!/^\\d+$/.test(text) || timeoutMs > MAX_TIMEOUT_MS) {\n process.stderr.write(\n `Error: ${name} must be an integer in 0–${MAX_TIMEOUT_MS}, got \"${text}\"\\n`\n )\n process.exit(1)\n }\n return timeoutMs\n}\n\nconst appAttachTimeoutMs = readTimeoutEnv('PAIRDRAW_MCP_APP_TIMEOUT_MS')\nconst sessionIdleTimeoutMs = readTimeoutEnv('PAIRDRAW_MCP_SESSION_IDLE_TIMEOUT_MS')\n\nconst toolPolicy = readToolPolicyFromEnv()\n\n// The agent bridge starts programs, so a malformed session leaves it off rather than guessing.\nconst agents = devAgentBridgeFromEnv()\nif (process.env.PAIRDRAW_MCP_AGENTS === '1' && !agents) {\n process.stderr.write(\n 'Warning: PAIRDRAW_MCP_AGENTS=1 needs PAIRDRAW_MCP_AGENT_SESSION and ' +\n 'PAIRDRAW_MCP_AGENT_TOKEN as two different 64-character lowercase hex tokens. ' +\n 'Starting without the agent bridge.\\n'\n )\n}\n// As in `pairdraw-connect`: agents reach `/mcp`, where eval would run any script they send.\nif (agents && toolPolicy.allowEval) {\n process.stderr.write(\n 'Warning: PAIRDRAW_MCP_EVAL=1 is ignored while the agent bridge is on ' +\n '(PAIRDRAW_MCP_AGENTS=1). Starting without the eval tool.\\n'\n )\n}\n\nconst handle = await startServer({\n httpPort: withTcp ? port : 0,\n withTcp,\n socketPath: process.env.PAIRDRAW_MCP_SOCKET?.trim() || null,\n enableEval: toolPolicy.allowEval && !agents,\n disabledTools: toolPolicy.disabledTools,\n scope: toolPolicy.scope,\n mcpRoot: resolveMCPRoot(process.env.PAIRDRAW_MCP_ROOT),\n // Auth token: undefined → auto-generate, empty string → disable auth,\n // non-empty → use trimmed value. Whitespace-only is rejected to prevent a\n // silent fallback to an auto-generated token when the operator intended to\n // set an explicit one.\n authToken: (() => {\n const raw = process.env.PAIRDRAW_MCP_AUTH_TOKEN\n if (raw === undefined) return undefined\n if (raw === '') return null\n const trimmed = raw.trim()\n if (!trimmed) {\n process.stderr.write(\n 'Error: PAIRDRAW_MCP_AUTH_TOKEN is whitespace-only. Set a real token, or use an empty string to disable auth.\\n'\n )\n process.exit(1)\n }\n return trimmed\n })(),\n corsOrigin: resolveCORSOrigins(process.env.PAIRDRAW_MCP_CORS_ORIGIN),\n appAttachTimeoutMs,\n // This process exists for the server it started, and resumed stdin keeps the event loop alive,\n // so a watchdog shutdown must end it rather than leave a process with no listeners.\n onAppAttachTimeout: () => process.exit(0),\n sessionIdleTimeoutMs,\n agents: agents ?? undefined\n})\n\nconst readyMarker = process.env.PAIRDRAW_MCP_READY_MARKER\nif (readyMarker && /^pairdraw-ready:[a-f0-9-]{36}$/.test(readyMarker)) {\n process.stderr.write(`${readyMarker}\\n`)\n}\n\nprocess.stderr.write(`Pairdraw MCP server\\n`)\nif (handle.socketPath) process.stderr.write(` Socket: ${handle.socketPath}\\n`)\nif (handle.httpPort) process.stderr.write(` HTTP: http://127.0.0.1:${handle.httpPort}\\n`)\n\n// Graceful shutdown on signals\nconst shutdown = async () => {\n process.stderr.write('\\nShutting down MCP server...\\n')\n await handle.close()\n process.exit(0)\n}\n\nprocess.on('SIGINT', () => void shutdown().catch(() => process.exit(1)))\nprocess.on('SIGTERM', () => void shutdown().catch(() => process.exit(1)))\n\n// A parent that started this server through a shell wrapper cannot always kill it directly\n// (on Windows, ending `cmd /c` leaves the process it started running), but its end of the\n// stdin pipe closes with it.\nif (process.env.PAIRDRAW_MCP_EXIT_ON_STDIN_CLOSE === '1') {\n let stdinClosed = false\n const onStdinClosed = () => {\n if (stdinClosed) return\n stdinClosed = true\n void shutdown().catch(() => process.exit(1))\n }\n process.stdin.on('end', onStdinClosed)\n process.stdin.on('close', onStdinClosed)\n process.stdin.resume()\n}\n"],"mappings":";;;;;;AAOA,IAAI,QAAQ,KAAK,SAAS,WAAW,GAAG;CACtC,QAAQ,OAAO,MAAM,GAAG,YAAY,GAAG;CACvC,QAAQ,KAAK,CAAC;AAChB;AAEA,IAAI,QAAQ,KAAK,SAAS,QAAQ,KAAK,QAAQ,KAAK,SAAS,IAAI,GAAG;CAClE,QAAQ,OAAO,MACb,i+FAyCF;CACA,QAAQ,KAAK,CAAC;AAChB;AAEA,MAAM,eAAe,QAAQ,IAAI,QAAQ,OAAA,CAAQ,KAAK;AAGtD,IAAI,CAAC,QAAQ,KAAK,WAAW,GAAG;CAC9B,QAAQ,OAAO,MAAM,mDAAmD,QAAQ,IAAI,KAAK,IAAI;CAC7F,QAAQ,KAAK,CAAC;AAChB;AACA,MAAM,UAAU,OAAO,SAAS,aAAa,EAAE;AAE/C,IAAI,UAAU,KAAK,UAAU,OAAO;CAClC,QAAQ,OAAO,MAAM,mDAAmD,QAAQ,IAAI,KAAK,IAAI;CAC7F,QAAQ,KAAK,CAAC;AAChB;AACA,MAAM,OAAO;AAGb,MAAM,UAAU,OAAO;AAEvB,MAAM,iBAAiB;;AAGvB,SAAS,eAAe,MAAkC;CACxD,MAAM,OAAO,QAAQ,IAAI,KAAK,EAAE,KAAK;CACrC,IAAI,CAAC,MAAM,OAAO;CAClB,MAAM,YAAY,OAAO,IAAI;CAC7B,IAAI,CAAC,QAAQ,KAAK,IAAI,KAAK,YAAY,gBAAgB;EACrD,QAAQ,OAAO,MACb,UAAU,KAAK,2BAA2B,eAAe,SAAS,KAAK,IACzE;EACA,Q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,MAAM,OAAO,MAAM;CACnB,QAAQ,KAAK,CAAC;AAChB;AAEA,QAAQ,GAAG,gBAAgB,KAAK,SAAS,CAAC,CAAC,YAAY,QAAQ,KAAK,CAAC,CAAC,CAAC;AACvE,QAAQ,GAAG,iBAAiB,KAAK,SAAS,CAAC,CAAC,YAAY,QAAQ,KAAK,CAAC,CAAC,CAAC;AAKxE,IAAI,QAAQ,IAAI,qCAAqC,KAAK;CACxD,IAAI,cAAc;CAClB,MAAM,sBAAsB;EAC1B,IAAI,aAAa;EACjB,cAAc;EACd,AAAK,SAAS,CAAC,CAAC,YAAY,QAAQ,KAAK,CAAC,CAAC;CAC7C;CACA,QAAQ,MAAM,GAAG,OAAO,aAAa;CACrC,QAAQ,MAAM,GAAG,SAAS,aAAa;CACvC,QAAQ,MAAM,OAAO;AACvB"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { devAgentBridgeFromEnv } from '#mcp/agents/index'\nimport { resolveMCPRoot } from '#mcp/root'\nimport { MCP_VERSION, startServer } from '#mcp/server'\nimport { readToolPolicyFromEnv } from '#mcp/tool/policy'\nimport { stopDiscoveredServer } from '#mcp/transport/discovery'\nimport { resolveCORSOrigins } from '#mcp/transport/origins'\n\n// Replaces a server a previous app version left running: the app starts the installed entry with\n// the PID its own discovery file names, and this process stops it only when the file and the\n// answering server agree (see stopDiscoveredServer).\nconst stopAt = process.argv.indexOf('--stop')\nif (stopAt !== -1) {\n const pid = Number(process.argv[stopAt + 1])\n const stopped = Number.isSafeInteger(pid) && pid > 0 ? await stopDiscoveredServer(pid) : false\n process.exit(stopped ? 0 : 2)\n}\n\nif (process.argv.includes('--version')) {\n process.stdout.write(`${MCP_VERSION}\\n`)\n process.exit(0)\n}\n\nif (process.argv.includes('--help') || process.argv.includes('-h')) {\n process.stdout.write(\n `pairdraw-mcp-http\\n\\n` +\n `Start the Pairdraw MCP server.\\n\\n` +\n `On macOS/Linux, the server listens on a Unix domain socket by default\\n` +\n `with optional TCP for browser clients. On Windows, only TCP is available.\\n\\n` +\n `Options:\\n` +\n ` --help, -h Show this help message\\n` +\n ` --version Print the version\\n\\n` +\n `Environment variables:\\n` +\n ` PORT TCP port (default: 7600, set to 0 to disable TCP)\\n` +\n ` PAIRDRAW_MCP_SOCKET Override Unix socket path (recorded in the discovery file)\\n` +\n ` PAIRDRAW_MCP_DISCOVERY_PATH Override discovery file (mcp.json) location; defaults to the\\n` +\n ` platform path. Parent dir created 0o700. Mainly for test isolation.\\n` +\n ` PAIRDRAW_MCP_TCP Deprecated — TCP is controlled by PORT (>0 = on, 0 = off)\\n` +\n ` PAIRDRAW_MCP_AUTH_TOKEN Bearer token for MCP and RPC auth\\n` +\n ` PAIRDRAW_MCP_ROOT Allowed directory for file-scoped tools (default: home directory on Windows, current working directory elsewhere)\\n` +\n ` PAIRDRAW_MCP_EVAL Set to 1 to enable the eval tool\\n` +\n ` PAIRDRAW_MCP_SESSION_IDLE_TIMEOUT_MS\\n` +\n ` Close sessions idle this long, in ms (default: 900000;\\n` +\n ` 0 disables). An open GET/SSE stream is not activity.\\n` +\n ` PAIRDRAW_MCP_DISABLED_TOOLS Comma-separated tool names to omit\\n` +\n ` PAIRDRAW_MCP_SCOPE \"selection\" to let clients read only the selected layers\\n` +\n ` (default: \"document\")\\n` +\n ` PAIRDRAW_MCP_CORS_ORIGIN Allowed CORS origins, comma-separated.\\n` +\n ` Defaults to the desktop app origin, since the app\\n` +\n ` webview is the only view that calls this server.\\n` +\n ` PAIRDRAW_MCP_APP_TIMEOUT_MS If set, close the server and remove its discovery\\n` +\n ` file after no app is attached for this many ms. The\\n` +\n ` grace period starts at startup and after disconnects.\\n` +\n ` Unset/0 disables it (default) — do not set this for\\n` +\n ` manual/CLI use, since nothing may ever register.\\n` +\n ` PAIRDRAW_MCP_EXIT_ON_STDIN_CLOSE Set to 1 to shut down when stdin closes, so a\\n` +\n ` parent that starts the server through a shell wrapper\\n` +\n ` can stop it by closing the pipe. Unset for manual/CLI use.\\n` +\n ` PAIRDRAW_MCP_AGENTS Set to 1, with the two variables below, to start the agent\\n` +\n ` bridge for one browser tab that the parent process gave\\n` +\n ` the same tokens, as \\`bun run dev\\` does; no pairing link.\\n` +\n ` The tokens are never written to the discovery file,\\n` +\n ` and the eval tool stays off.\\n` +\n ` PAIRDRAW_MCP_AGENT_SESSION The tab's session token: 64 lowercase hex characters.\\n` +\n ` PAIRDRAW_MCP_AGENT_TOKEN The token the tab hands its agents, which reaches only\\n` +\n ` /mcp: 64 lowercase hex characters, not the session token.\\n`\n )\n process.exit(0)\n}\n\nconst rawPortText = (process.env.PORT ?? '7600').trim()\n// Reject non-digit strings (including hex like \"0x50\" and partially-numeric like\n// \"7600abc\") — Number.parseInt would silently parse these, masking misconfig.\nif (!/^\\d+$/.test(rawPortText)) {\n process.stderr.write(`Error: PORT must be an integer in 0–65535, got \"${process.env.PORT}\"\\n`)\n process.exit(1)\n}\nconst rawPort = Number.parseInt(rawPortText, 10)\n// Validate PORT: must be an integer in 0–65535. 0 means \"disable TCP\".\nif (rawPort < 0 || rawPort > 65535) {\n process.stderr.write(`Error: PORT must be an integer in 0–65535, got \"${process.env.PORT}\"\\n`)\n process.exit(1)\n}\nconst port = rawPort\n// PAIRDRAW_MCP_TCP is accepted for backward compat but has no effect —\n// the PORT value alone determines whether TCP is enabled (PORT=0 is the kill switch).\nconst withTcp = port > 0\n\nconst MAX_TIMEOUT_MS = 2_147_483_647\n\n/** Read a millisecond timeout from the environment, exiting on an invalid value. */\nfunction readTimeoutEnv(name: string): number | undefined {\n const text = process.env[name]?.trim()\n if (!text) return undefined\n const timeoutMs = Number(text)\n if (!/^\\d+$/.test(text) || timeoutMs > MAX_TIMEOUT_MS) {\n process.stderr.write(\n `Error: ${name} must be an integer in 0–${MAX_TIMEOUT_MS}, got \"${text}\"\\n`\n )\n process.exit(1)\n }\n return timeoutMs\n}\n\nconst appAttachTimeoutMs = readTimeoutEnv('PAIRDRAW_MCP_APP_TIMEOUT_MS')\nconst sessionIdleTimeoutMs = readTimeoutEnv('PAIRDRAW_MCP_SESSION_IDLE_TIMEOUT_MS')\n\nconst toolPolicy = readToolPolicyFromEnv()\n\n// The agent bridge starts programs, so a malformed session leaves it off rather than guessing.\nconst agents = devAgentBridgeFromEnv()\nif (process.env.PAIRDRAW_MCP_AGENTS === '1' && !agents) {\n process.stderr.write(\n 'Warning: PAIRDRAW_MCP_AGENTS=1 needs PAIRDRAW_MCP_AGENT_SESSION and ' +\n 'PAIRDRAW_MCP_AGENT_TOKEN as two different 64-character lowercase hex tokens. ' +\n 'Starting without the agent bridge.\\n'\n )\n}\n// As in `pairdraw-connect`: agents reach `/mcp`, where eval would run any script they send.\nif (agents && toolPolicy.allowEval) {\n process.stderr.write(\n 'Warning: PAIRDRAW_MCP_EVAL=1 is ignored while the agent bridge is on ' +\n '(PAIRDRAW_MCP_AGENTS=1). Starting without the eval tool.\\n'\n )\n}\n\nconst handle = await startServer({\n httpPort: withTcp ? port : 0,\n withTcp,\n socketPath: process.env.PAIRDRAW_MCP_SOCKET?.trim() || null,\n enableEval: toolPolicy.allowEval && !agents,\n disabledTools: toolPolicy.disabledTools,\n scope: toolPolicy.scope,\n mcpRoot: resolveMCPRoot(process.env.PAIRDRAW_MCP_ROOT),\n // Auth token: undefined → auto-generate, empty string → disable auth,\n // non-empty → use trimmed value. Whitespace-only is rejected to prevent a\n // silent fallback to an auto-generated token when the operator intended to\n // set an explicit one.\n authToken: (() => {\n const raw = process.env.PAIRDRAW_MCP_AUTH_TOKEN\n if (raw === undefined) return undefined\n if (raw === '') return null\n const trimmed = raw.trim()\n if (!trimmed) {\n process.stderr.write(\n 'Error: PAIRDRAW_MCP_AUTH_TOKEN is whitespace-only. Set a real token, or use an empty string to disable auth.\\n'\n )\n process.exit(1)\n }\n return trimmed\n })(),\n corsOrigin: resolveCORSOrigins(process.env.PAIRDRAW_MCP_CORS_ORIGIN),\n appAttachTimeoutMs,\n // This process exists for the server it started, and resumed stdin keeps the event loop alive,\n // so a watchdog shutdown must end it rather than leave a process with no listeners.\n onAppAttachTimeout: () => process.exit(0),\n sessionIdleTimeoutMs,\n agents: agents ?? undefined\n})\n\nconst readyMarker = process.env.PAIRDRAW_MCP_READY_MARKER\nif (readyMarker && /^pairdraw-ready:[a-f0-9-]{36}$/.test(readyMarker)) {\n process.stderr.write(`${readyMarker}\\n`)\n}\n\nprocess.stderr.write(`Pairdraw MCP server\\n`)\nif (handle.socketPath) process.stderr.write(` Socket: ${handle.socketPath}\\n`)\nif (handle.httpPort) process.stderr.write(` HTTP: http://127.0.0.1:${handle.httpPort}\\n`)\n\n// Graceful shutdown on signals\nconst shutdown = async () => {\n process.stderr.write('\\nShutting down MCP server...\\n')\n await handle.close()\n process.exit(0)\n}\n\nprocess.on('SIGINT', () => void shutdown().catch(() => process.exit(1)))\nprocess.on('SIGTERM', () => void shutdown().catch(() => process.exit(1)))\n\n// A parent that started this server through a shell wrapper cannot always kill it directly\n// (on Windows, ending `cmd /c` leaves the process it started running), but its end of the\n// stdin pipe closes with it.\nif (process.env.PAIRDRAW_MCP_EXIT_ON_STDIN_CLOSE === '1') {\n let stdinClosed = false\n const onStdinClosed = () => {\n if (stdinClosed) return\n stdinClosed = true\n void shutdown().catch(() => process.exit(1))\n }\n process.stdin.on('end', onStdinClosed)\n process.stdin.on('close', onStdinClosed)\n process.stdin.resume()\n}\n"],"mappings":";;;;;;;AAWA,MAAM,SAAS,QAAQ,KAAK,QAAQ,QAAQ;AAC5C,IAAI,WAAW,IAAI;CACjB,MAAM,MAAM,OAAO,QAAQ,KAAK,SAAS,EAAE;CAC3C,MAAM,UAAU,OAAO,cAAc,GAAG,KAAK,MAAM,IAAI,MAAM,qBAAqB,GAAG,IAAI;CACzF,QAAQ,KAAK,UAAU,IAAI,CAAC;AAC9B;AAEA,IAAI,QAAQ,KAAK,SAAS,WAAW,GAAG;CACtC,QAAQ,OAAO,MAAM,GAAG,YAAY,GAAG;CACvC,QAAQ,KAAK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KAAK,CAAC,CAAC;CAC7C;CACA,QAAQ,MAAM,GAAG,OAAO,aAAa;CACrC,QAAQ,MAAM,GAAG,SAAS,aAAa;CACvC,QAAQ,MAAM,OAAO;AACvB"}
@@ -2,7 +2,7 @@ import "./rolldown-runtime-ClRpJifh.mjs";
2
2
  import { a as getSocketPath, i as getSocketDir, o as platformHasUnixSockets, r as getDiscoveryPath, t as getAgentWorkspacePath } from "./paths-BpcXnrbP.mjs";
3
3
  import { n as isToolEnabled, o as createToolDescriptors, s as getMCPToolDefinitions, t as applyToolPolicy } from "./policy-CVfvvMB7.mjs";
4
4
  import { n as SELECTION_SCOPE_FILE_OUTPUT_ERROR, s as scopeRPC } from "./scope-2c_X9Kl3.mjs";
5
- import { a as writeDiscoveryFile, i as removeStaleSocket, r as removeDiscoveryFile, t as parseDiscoveryInfo } from "./discovery-BIJ7923d.mjs";
5
+ import { a as removeDiscoveryFile, c as writeDiscoveryFile, o as removeStaleSocket, r as parseDiscoveryInfo } from "./discovery-axCcZws7.mjs";
6
6
  import { bodyLimit } from "hono/body-limit";
7
7
  import * as v from "valibot";
8
8
  import { WebSocketServer } from "ws";
@@ -2890,7 +2890,7 @@ function createServerInstructions({ policy, filesystemEnabled, agentKind }) {
2890
2890
  }
2891
2891
  //#endregion
2892
2892
  //#region package.json
2893
- var version = "0.22.0";
2893
+ var version = "0.22.1";
2894
2894
  //#endregion
2895
2895
  //#region src/server/connections.ts
2896
2896
  const HEARTBEAT_INTERVAL_MS = 5e3;
@@ -3426,4 +3426,4 @@ function armAppAttachWatchdog(timeoutMs, browserRPC, handle, onTimeout, hasClien
3426
3426
  //#endregion
3427
3427
  export { resolveCORSOrigins as a, registerSkill as c, devAgentBridgeFromEnv as d, pairingFingerprint as f, DEFAULT_CONNECT_APP_URL as i, fail as l, startServer as n, MCP_AGENT_KINDS as o, createServerInstructions as r, registerTools as s, MCP_VERSION as t, ok as u };
3428
3428
 
3429
- //# sourceMappingURL=server-BHPENxBB.mjs.map
3429
+ //# sourceMappingURL=server-Df4-we5n.mjs.map