@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/server.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { l as fail, n as startServer, o as MCP_AGENT_KINDS, s as registerTools, t as MCP_VERSION, u as ok } from "./server-BHPENxBB.mjs";
1
+ import { l as fail, n as startServer, o as MCP_AGENT_KINDS, s as registerTools, t as MCP_VERSION, u as ok } from "./server-Df4-we5n.mjs";
2
2
  export { MCP_AGENT_KINDS, MCP_VERSION, fail, ok, registerTools, startServer };
package/dist/stdio.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import "./rolldown-runtime-ClRpJifh.mjs";
3
- import { c as registerSkill, r as createServerInstructions, s as registerTools, t as MCP_VERSION } from "./server-BHPENxBB.mjs";
3
+ import { c as registerSkill, r as createServerInstructions, s as registerTools, t as MCP_VERSION } from "./server-Df4-we5n.mjs";
4
4
  import { a as getSocketPath, o as platformHasUnixSockets } from "./paths-BpcXnrbP.mjs";
5
5
  import { t as resolveMCPRoot } from "./root-BzmoiT2g.mjs";
6
6
  import { r as parseDisabledTools } from "./policy-CVfvvMB7.mjs";
7
7
  import { a as narrowestScope, o as parseToolScope } from "./scope-2c_X9Kl3.mjs";
8
- import { n as readDiscoveryFile } from "./discovery-BIJ7923d.mjs";
8
+ import { i as readDiscoveryFile } from "./discovery-axCcZws7.mjs";
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { McpServer } from "@modelcontextprotocol/server";
11
11
  import { request } from "node:http";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pairdraw/mcp",
3
- "version": "0.22.0",
3
+ "version": "0.22.1",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -15,7 +15,7 @@
15
15
  "dependencies": {
16
16
  "@hono/node-server": "^1.19.17",
17
17
  "@modelcontextprotocol/server": "^2.0.0",
18
- "@pairdraw/core": "^0.22.0",
18
+ "@pairdraw/core": "^0.22.1",
19
19
  "@valibot/to-json-schema": "^1.8.0",
20
20
  "es-toolkit": "^1.52.0",
21
21
  "hono": "^4.13.13",
package/src/index.ts CHANGED
@@ -3,8 +3,19 @@ import { devAgentBridgeFromEnv } from '#mcp/agents/index'
3
3
  import { resolveMCPRoot } from '#mcp/root'
4
4
  import { MCP_VERSION, startServer } from '#mcp/server'
5
5
  import { readToolPolicyFromEnv } from '#mcp/tool/policy'
6
+ import { stopDiscoveredServer } from '#mcp/transport/discovery'
6
7
  import { resolveCORSOrigins } from '#mcp/transport/origins'
7
8
 
9
+ // Replaces a server a previous app version left running: the app starts the installed entry with
10
+ // the PID its own discovery file names, and this process stops it only when the file and the
11
+ // answering server agree (see stopDiscoveredServer).
12
+ const stopAt = process.argv.indexOf('--stop')
13
+ if (stopAt !== -1) {
14
+ const pid = Number(process.argv[stopAt + 1])
15
+ const stopped = Number.isSafeInteger(pid) && pid > 0 ? await stopDiscoveredServer(pid) : false
16
+ process.exit(stopped ? 0 : 2)
17
+ }
18
+
8
19
  if (process.argv.includes('--version')) {
9
20
  process.stdout.write(`${MCP_VERSION}\n`)
10
21
  process.exit(0)
@@ -218,7 +218,7 @@ export async function removeStaleSocket(socketPathOverride?: string): Promise<vo
218
218
  * Uses process.kill(pid, 0) which doesn't send a signal, just checks existence.
219
219
  * Works on both Unix and Windows.
220
220
  */
221
- function isProcessAlive(pid: number): boolean {
221
+ export function isProcessAlive(pid: number): boolean {
222
222
  try {
223
223
  process.kill(pid, 0)
224
224
  return true
@@ -230,6 +230,79 @@ function isProcessAlive(pid: number): boolean {
230
230
  }
231
231
  }
232
232
 
233
+ /** Resolves after `ms`, for polling a process that is shutting down. */
234
+ function sleep(ms: number): Promise<void> {
235
+ const { promise, resolve } = Promise.withResolvers<undefined>()
236
+ setTimeout(() => resolve(undefined), ms)
237
+ return promise
238
+ }
239
+
240
+ /**
241
+ * The fields that prove a `/health` answer comes from Pairdraw's own MCP server. `tools` is
242
+ * present only when the request carried the token, so a tokenless probe leaves it out.
243
+ */
244
+ const discoveredServerHealthSchema = v.object({
245
+ status: v.picklist(['ok', 'no_app']),
246
+ version: v.string(),
247
+ authRequired: v.boolean(),
248
+ agentSessionEvents: v.literal(true),
249
+ tools: v.optional(v.array(v.unknown()))
250
+ })
251
+
252
+ /**
253
+ * Whether the process to stop is the server Pairdraw's discovery file names. A stale file can
254
+ * outlive its server and a reused PID would then name another process, so the server at the
255
+ * recorded port must still answer health with the version the file recorded.
256
+ *
257
+ * A socket-only entry (no TCP port) is refused: the desktop app talks HTTP, and a socket
258
+ * connection cannot authenticate the version the way `/health` does.
259
+ */
260
+ export async function isDiscoveredServer(pid: number, info: DiscoveryInfo): Promise<boolean> {
261
+ if (info.pid !== pid) return false
262
+ if (info.httpPort <= 0) return false
263
+ const token = info.authToken?.trim() || null
264
+ // A server that needs auth cannot be identified without the token, so never probe it blind.
265
+ if (info.authRequired && !token) return false
266
+ try {
267
+ const response = await fetch(`http://127.0.0.1:${info.httpPort}/health`, {
268
+ headers: token ? { Authorization: `Bearer ${token}` } : undefined,
269
+ signal: AbortSignal.timeout(2000)
270
+ })
271
+ if (!response.ok) return false
272
+ const parsed = v.safeParse(discoveredServerHealthSchema, await response.json())
273
+ if (!parsed.success) return false
274
+ const health = parsed.output
275
+ if (health.version !== info.version) return false
276
+ if (health.authRequired !== info.authRequired) return false
277
+ if (token && health.tools === undefined) return false
278
+ return true
279
+ } catch {
280
+ return false
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Stops the server recorded in Pairdraw's discovery file, after checking it is the process the
286
+ * file names. Used by `pairdraw-mcp-http --stop <pid>` so the app can replace a server a previous
287
+ * app version left running without killing an unrelated process. Returns false when the file and
288
+ * the answering server do not agree, or the process is still running after `waitMs`.
289
+ */
290
+ export async function stopDiscoveredServer(pid: number, waitMs = 5000): Promise<boolean> {
291
+ const info = await readDiscoveryFile()
292
+ if (!info || !(await isDiscoveredServer(pid, info))) return false
293
+ try {
294
+ process.kill(pid, 'SIGTERM')
295
+ } catch {
296
+ return false
297
+ }
298
+ const deadline = Date.now() + waitMs
299
+ while (isProcessAlive(pid)) {
300
+ if (Date.now() >= deadline) return false
301
+ await sleep(50)
302
+ }
303
+ return true
304
+ }
305
+
233
306
  function isEnoent(e: unknown): boolean {
234
307
  return e instanceof Error && 'code' in e && (e as NodeJS.ErrnoException).code === 'ENOENT'
235
308
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"discovery-BIJ7923d.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 */\nfunction 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\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,SAA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