@pairdraw/mcp 0.0.0-stage → 0.16.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/LICENSE +21 -0
- package/README.md +19 -2
- package/dist/connect.d.mts +1 -0
- package/dist/connect.mjs +192 -0
- package/dist/connect.mjs.map +1 -0
- package/dist/discovery-CB2Bv5WA.mjs +167 -0
- package/dist/discovery-CB2Bv5WA.mjs.map +1 -0
- package/dist/discovery.d.mts +59 -0
- package/dist/discovery.mjs +2 -0
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +95 -0
- package/dist/index.mjs.map +1 -0
- package/dist/metadata-DVz00c8R.d.mts +26 -0
- package/dist/paths-BpcXnrbP.mjs +168 -0
- package/dist/paths-BpcXnrbP.mjs.map +1 -0
- package/dist/policy-B8Ka4WRH.mjs +206 -0
- package/dist/policy-B8Ka4WRH.mjs.map +1 -0
- package/dist/rolldown-runtime-ClRpJifh.mjs +3 -0
- package/dist/root-BzmoiT2g.mjs +9 -0
- package/dist/root-BzmoiT2g.mjs.map +1 -0
- package/dist/scope-D2LTTsDw.mjs +66 -0
- package/dist/scope-D2LTTsDw.mjs.map +1 -0
- package/dist/scope-DJ9hsBYV.d.mts +31 -0
- package/dist/server-BdiJUhSs.mjs +3261 -0
- package/dist/server-BdiJUhSs.mjs.map +1 -0
- package/dist/server.d.mts +265 -0
- package/dist/server.mjs +2 -0
- package/dist/stdio.d.mts +1 -0
- package/dist/stdio.mjs +411 -0
- package/dist/stdio.mjs.map +1 -0
- package/dist/tools.d.mts +17 -0
- package/dist/tools.mjs +33 -0
- package/dist/tools.mjs.map +1 -0
- package/dist/transport.d.mts +59 -0
- package/dist/transport.mjs +2 -0
- package/package.json +78 -4
- package/src/agents/acp.ts +110 -0
- package/src/agents/claude-cloud.ts +99 -0
- package/src/agents/filter.ts +85 -0
- package/src/agents/index.ts +299 -0
- package/src/agents/install.ts +44 -0
- package/src/agents/link.ts +79 -0
- package/src/agents/lookup.ts +136 -0
- package/src/agents/pairing.ts +182 -0
- package/src/agents/path.ts +85 -0
- package/src/agents/process.ts +88 -0
- package/src/agents/registry.ts +36 -0
- package/src/agents/schema.ts +77 -0
- package/src/agents/sign-in.ts +106 -0
- package/src/agents/socket.ts +79 -0
- package/src/auth.ts +21 -0
- package/src/browser-rpc.ts +440 -0
- package/src/connect.ts +170 -0
- package/src/global.d.ts +5 -0
- package/src/http-options.ts +14 -0
- package/src/index.ts +179 -0
- package/src/json.ts +1 -0
- package/src/result.ts +37 -0
- package/src/root.ts +5 -0
- package/src/rpc-types.ts +5 -0
- package/src/server/connections.ts +58 -0
- package/src/server/files.ts +49 -0
- package/src/server/install-command.ts +24 -0
- package/src/server/lifecycle.ts +389 -0
- package/src/server/origin.ts +53 -0
- package/src/server/pending-requests.ts +62 -0
- package/src/server/sessions.ts +335 -0
- package/src/server.ts +597 -0
- package/src/skill/content.ts +40 -0
- package/src/skill/instructions.ts +69 -0
- package/src/skill/register.ts +77 -0
- package/src/stdio/bridge.ts +460 -0
- package/src/stdio.ts +130 -0
- package/src/tool/browser.ts +183 -0
- package/src/tool/index.ts +12 -0
- package/src/tool/manifest.ts +221 -0
- package/src/tool/metadata.ts +44 -0
- package/src/tool/output.ts +336 -0
- package/src/tool/policy.ts +37 -0
- package/src/tool/registration.ts +523 -0
- package/src/tool/scope.ts +71 -0
- package/src/transport/discovery.ts +235 -0
- package/src/transport/origins.ts +85 -0
- package/src/transport/paths.ts +179 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Danila Poyarkov and OpenPencil contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,20 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pairdraw/mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Model Context Protocol server for [Pairdraw](https://github.com/BadryansahBangsawan/pairdraw). It lets MCP clients such as Claude Code, Cursor, and Windsurf inspect and edit designs through the running app, reusing the same tool definitions as the built-in AI chat.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install -g @pairdraw/mcp
|
|
7
|
+
pairdraw-mcp # stdio transport for MCP clients
|
|
8
|
+
pairdraw-mcp-http # Streamable HTTP transport for browser extensions and scripts
|
|
9
|
+
pairdraw-connect # companion that runs Claude Code, Codex, or Gemini CLI for the web app
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
On macOS and Linux, local clients prefer a private Unix domain socket; Windows and unavailable sockets fall back to localhost TCP. File access is limited to the effective MCP root.
|
|
13
|
+
|
|
14
|
+
Streamable HTTP clients initialize with a POST, then open GET/SSE with the returned `Mcp-Session-Id`; DELETE ends the session. The server keeps at most 10 sessions and closes those idle for 15 minutes (`PAIRDRAW_MCP_SESSION_IDLE_TIMEOUT_MS`, `0` disables). Running requests keep a session alive, an open SSE stream alone does not, and an expired session ID returns 404.
|
|
15
|
+
|
|
16
|
+
- Setup and client configuration: https://github.com/BadryansahBangsawan/pairdraw/blob/main/packages/docs/programmable/mcp-server.md
|
|
17
|
+
- Coding agents in the browser (`pairdraw-connect`): https://github.com/BadryansahBangsawan/pairdraw/blob/main/packages/docs/programmable/browser-agents.md
|
|
18
|
+
- Source and issues: https://github.com/BadryansahBangsawan/pairdraw
|
|
19
|
+
|
|
20
|
+
MIT License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import "./rolldown-runtime-ClRpJifh.mjs";
|
package/dist/connect.mjs
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import "./rolldown-runtime-ClRpJifh.mjs";
|
|
3
|
+
import { f as pairingFingerprint, i as resolveCORSOrigins, n as startServer, r as DEFAULT_CONNECT_APP_URL, t as MCP_VERSION } from "./server-BdiJUhSs.mjs";
|
|
4
|
+
import { n as getCompanionDir } from "./paths-BpcXnrbP.mjs";
|
|
5
|
+
import { t as resolveMCPRoot } from "./root-BzmoiT2g.mjs";
|
|
6
|
+
import { i as readToolPolicyFromEnv } from "./policy-B8Ka4WRH.mjs";
|
|
7
|
+
import { randomBytes } from "node:crypto";
|
|
8
|
+
import { rm, writeFile } from "node:fs/promises";
|
|
9
|
+
import { platform } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
import { uniq } from "es-toolkit";
|
|
13
|
+
//#region src/agents/link.ts
|
|
14
|
+
/** Hosts a development server may run the app on with plain HTTP. */
|
|
15
|
+
function isLocalHost(hostname) {
|
|
16
|
+
return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "127.0.0.1" || hostname === "[::1]";
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The web app the companion pairs with: the editor on this computer, or one the operator names,
|
|
20
|
+
* such as a Cloud server's. Plain HTTP is accepted only on this machine. Returns null for anything
|
|
21
|
+
* else.
|
|
22
|
+
*/
|
|
23
|
+
function resolveConnectAppURL(raw) {
|
|
24
|
+
const text = raw?.trim() || "http://localhost:1420";
|
|
25
|
+
let url;
|
|
26
|
+
try {
|
|
27
|
+
url = new URL(text);
|
|
28
|
+
} catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
if (url.username || url.password) return null;
|
|
32
|
+
if (url.protocol === "https:") return url;
|
|
33
|
+
return url.protocol === "http:" && isLocalHost(url.hostname) ? url : null;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The link that pairs a tab: the app with `#connect=<code>` in its fragment, which browsers never
|
|
37
|
+
* send to a server, and the port when it is not the default one.
|
|
38
|
+
*/
|
|
39
|
+
function connectLink(appURL, code, port, defaultPort) {
|
|
40
|
+
const link = new URL(appURL);
|
|
41
|
+
const params = new URLSearchParams({ connect: code });
|
|
42
|
+
if (port !== defaultPort) params.set("port", String(port));
|
|
43
|
+
link.hash = params.toString();
|
|
44
|
+
return link.toString();
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The origins the companion lets call it: the configured ones and the app it pairs with. `*`
|
|
48
|
+
* would let any site drive the agent bridge, so it is dropped here, whatever was configured.
|
|
49
|
+
*/
|
|
50
|
+
function connectCORSOrigins(raw, appURL) {
|
|
51
|
+
const configured = resolveCORSOrigins(raw).filter((origin) => origin !== "*");
|
|
52
|
+
return uniq([...configured, appURL.origin]);
|
|
53
|
+
}
|
|
54
|
+
function escapeAttribute(value) {
|
|
55
|
+
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Writes a page that forwards to the link, readable only by this user, so the browser is opened
|
|
59
|
+
* with the page's path rather than the link: a command line, which other users of the computer
|
|
60
|
+
* can list, then never holds the pairing code. Returns the path and a function that deletes it.
|
|
61
|
+
*/
|
|
62
|
+
async function writeConnectPage(dir, link) {
|
|
63
|
+
const path = join(dir, `connect-${randomBytes(8).toString("hex")}.html`);
|
|
64
|
+
const href = escapeAttribute(link);
|
|
65
|
+
const html = `<!doctype html><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${href}"><title>Pairdraw</title><a href="${href}">Open Pairdraw</a>\n`;
|
|
66
|
+
await writeFile(path, html, {
|
|
67
|
+
mode: 384,
|
|
68
|
+
flag: "wx"
|
|
69
|
+
});
|
|
70
|
+
return {
|
|
71
|
+
path,
|
|
72
|
+
remove: () => rm(path, { force: true })
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
//#region src/connect.ts
|
|
77
|
+
const DEFAULT_PORT = 7600;
|
|
78
|
+
if (process.argv.includes("--version")) {
|
|
79
|
+
process.stdout.write(`${MCP_VERSION}\n`);
|
|
80
|
+
process.exit(0);
|
|
81
|
+
}
|
|
82
|
+
if (process.argv.includes("--help") || process.argv.includes("-h")) {
|
|
83
|
+
process.stdout.write(`pairdraw-connect
|
|
84
|
+
|
|
85
|
+
Connect Pairdraw in the browser to this computer, so its chat can run
|
|
86
|
+
Claude Code, Codex, Gemini CLI, or omp here and use Pairdraw's tools.
|
|
87
|
+
|
|
88
|
+
Starts Pairdraw's MCP server with an agent bridge and opens a one-time link
|
|
89
|
+
that pairs the browser tab. Keep it running while you use agents.
|
|
90
|
+
|
|
91
|
+
Options:
|
|
92
|
+
--help, -h Show this help message
|
|
93
|
+
--version Print the version
|
|
94
|
+
--no-open Print the link without opening the browser
|
|
95
|
+
|
|
96
|
+
Environment variables:
|
|
97
|
+
PORT TCP port (default: ${DEFAULT_PORT})\n PAIRDRAW_CONNECT_APP_URL The Pairdraw web app to pair with (default:\n ${DEFAULT_CONNECT_APP_URL}, the editor \`bun run dev\` serves).\n Its origin may call this server.\n PAIRDRAW_MCP_CORS_ORIGIN Further origins allowed to call this server, comma-separated.\n PAIRDRAW_MCP_ROOT Allowed directory for file-scoped tools (default: home\n directory on Windows, current working directory elsewhere)\n PAIRDRAW_MCP_SOCKET Override the Unix socket path\n PAIRDRAW_MCP_DISABLED_TOOLS Comma-separated tool names to omit\n PAIRDRAW_MCP_SCOPE "selection" to let clients read only the selected layers\n\nThe eval tool is always off here, and authentication cannot be disabled.\n`);
|
|
98
|
+
process.exit(0);
|
|
99
|
+
}
|
|
100
|
+
function fail(message) {
|
|
101
|
+
process.stderr.write(`Error: ${message}\n`);
|
|
102
|
+
process.exit(1);
|
|
103
|
+
}
|
|
104
|
+
const portText = (process.env.PORT ?? String(DEFAULT_PORT)).trim();
|
|
105
|
+
if (!/^\d+$/.test(portText)) fail(`PORT must be an integer in 1–65535, got "${portText}"`);
|
|
106
|
+
const port = Number.parseInt(portText, 10);
|
|
107
|
+
if (port < 1 || port > 65535) fail(`PORT must be an integer in 1–65535, got "${portText}"`);
|
|
108
|
+
const appURL = resolveConnectAppURL(process.env.PAIRDRAW_CONNECT_APP_URL);
|
|
109
|
+
if (!appURL) fail("PAIRDRAW_CONNECT_APP_URL must be an https URL, or http on localhost");
|
|
110
|
+
const explicitToken = process.env.PAIRDRAW_MCP_AUTH_TOKEN?.trim();
|
|
111
|
+
const toolPolicy = readToolPolicyFromEnv();
|
|
112
|
+
let handle;
|
|
113
|
+
try {
|
|
114
|
+
handle = await startServer({
|
|
115
|
+
httpPort: port,
|
|
116
|
+
withTcp: true,
|
|
117
|
+
socketPath: process.env.PAIRDRAW_MCP_SOCKET?.trim() || null,
|
|
118
|
+
enableEval: false,
|
|
119
|
+
disabledTools: toolPolicy.disabledTools,
|
|
120
|
+
scope: toolPolicy.scope,
|
|
121
|
+
mcpRoot: resolveMCPRoot(process.env.PAIRDRAW_MCP_ROOT),
|
|
122
|
+
authToken: explicitToken || void 0,
|
|
123
|
+
corsOrigin: connectCORSOrigins(process.env.PAIRDRAW_MCP_CORS_ORIGIN, appURL),
|
|
124
|
+
agents: { onPaired: () => process.stdout.write("A browser tab connected. If you did not open the link, press Ctrl+C to stop.\n") }
|
|
125
|
+
});
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if ((error instanceof Error && "code" in error ? error.code : null) === "EADDRINUSE") fail(`port ${port} or the MCP socket is already in use. Quit the Pairdraw desktop app or another MCP server, or start this one with PORT=${port + 1}.`);
|
|
128
|
+
fail(error instanceof Error ? error.message : String(error));
|
|
129
|
+
}
|
|
130
|
+
const issueCode = handle.issuePairingCode;
|
|
131
|
+
if (!issueCode) fail("The agent bridge did not start.");
|
|
132
|
+
/** Opens a file or link in the default browser, without a shell. */
|
|
133
|
+
function openBrowser(url) {
|
|
134
|
+
const os = platform();
|
|
135
|
+
let command = "xdg-open";
|
|
136
|
+
let args = [url];
|
|
137
|
+
if (os === "darwin") command = "open";
|
|
138
|
+
if (os === "win32") {
|
|
139
|
+
command = "rundll32";
|
|
140
|
+
args = ["url.dll,FileProtocolHandler", url];
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
const child = spawn(command, args, {
|
|
144
|
+
stdio: "ignore",
|
|
145
|
+
detached: true
|
|
146
|
+
});
|
|
147
|
+
child.on("error", () => void 0);
|
|
148
|
+
child.unref();
|
|
149
|
+
} catch {
|
|
150
|
+
process.stdout.write("Could not open the browser; open the link above yourself.\n");
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const shouldOpen = !process.argv.includes("--no-open");
|
|
154
|
+
/** How long the page that forwards to a link stays on disk; the browser reads it at once. */
|
|
155
|
+
const PAGE_LIFETIME_MS = 3e4;
|
|
156
|
+
/**
|
|
157
|
+
* Opens the link through a private page, so no command line holds the code, and deletes the
|
|
158
|
+
* page soon after.
|
|
159
|
+
*/
|
|
160
|
+
async function openLink(link) {
|
|
161
|
+
try {
|
|
162
|
+
const page = await writeConnectPage(await getCompanionDir(), link);
|
|
163
|
+
openBrowser(page.path);
|
|
164
|
+
setTimeout(() => void page.remove(), PAGE_LIFETIME_MS).unref();
|
|
165
|
+
} catch {
|
|
166
|
+
process.stdout.write("Could not open the browser; open the link above yourself.\n");
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function announceLink(open) {
|
|
170
|
+
const code = issueCode();
|
|
171
|
+
const link = connectLink(appURL, code, handle.httpPort, DEFAULT_PORT);
|
|
172
|
+
process.stdout.write(`\nOpen this link to connect Pairdraw to this computer (works once, for 2 minutes):\n ${link}\nThe tab asks you to confirm; check that it shows ${pairingFingerprint(code)}.\n\nPress Enter for a new link. Press Ctrl+C to stop.\n`);
|
|
173
|
+
if (open) openLink(link);
|
|
174
|
+
}
|
|
175
|
+
process.stdout.write(`Pairdraw companion ${MCP_VERSION}\n`);
|
|
176
|
+
process.stdout.write(` HTTP: http://127.0.0.1:${handle.httpPort}\n`);
|
|
177
|
+
if (handle.socketPath) process.stdout.write(` Socket: ${handle.socketPath}\n`);
|
|
178
|
+
announceLink(shouldOpen);
|
|
179
|
+
process.stdin.on("data", () => announceLink(false));
|
|
180
|
+
process.stdin.on("error", () => void 0);
|
|
181
|
+
process.stdin.resume();
|
|
182
|
+
const shutdown = async () => {
|
|
183
|
+
process.stdout.write("\nStopping the Pairdraw companion...\n");
|
|
184
|
+
await handle.close();
|
|
185
|
+
process.exit(0);
|
|
186
|
+
};
|
|
187
|
+
process.on("SIGINT", () => void shutdown().catch(() => process.exit(1)));
|
|
188
|
+
process.on("SIGTERM", () => void shutdown().catch(() => process.exit(1)));
|
|
189
|
+
//#endregion
|
|
190
|
+
export {};
|
|
191
|
+
|
|
192
|
+
//# sourceMappingURL=connect.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect.mjs","names":[],"sources":["../src/agents/link.ts","../src/connect.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport { rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nimport { uniq } from 'es-toolkit'\n\nimport { DEFAULT_CONNECT_APP_URL, resolveCORSOrigins } from '#mcp/transport/origins'\n\n/** Hosts a development server may run the app on with plain HTTP. */\nfunction isLocalHost(hostname: string): boolean {\n return (\n hostname === 'localhost' ||\n hostname.endsWith('.localhost') ||\n hostname === '127.0.0.1' ||\n hostname === '[::1]'\n )\n}\n\n/**\n * The web app the companion pairs with: the editor on this computer, or one the operator names,\n * such as a Cloud server's. Plain HTTP is accepted only on this machine. Returns null for anything\n * else.\n */\nexport function resolveConnectAppURL(raw: string | undefined): URL | null {\n const text = raw?.trim() || DEFAULT_CONNECT_APP_URL\n let url: URL\n try {\n url = new URL(text)\n } catch {\n return null\n }\n if (url.username || url.password) return null\n if (url.protocol === 'https:') return url\n return url.protocol === 'http:' && isLocalHost(url.hostname) ? url : null\n}\n\n/**\n * The link that pairs a tab: the app with `#connect=<code>` in its fragment, which browsers never\n * send to a server, and the port when it is not the default one.\n */\nexport function connectLink(appURL: URL, code: string, port: number, defaultPort: number): string {\n const link = new URL(appURL)\n const params = new URLSearchParams({ connect: code })\n if (port !== defaultPort) params.set('port', String(port))\n link.hash = params.toString()\n return link.toString()\n}\n\n/**\n * The origins the companion lets call it: the configured ones and the app it pairs with. `*`\n * would let any site drive the agent bridge, so it is dropped here, whatever was configured.\n */\nexport function connectCORSOrigins(raw: string | undefined, appURL: URL): string[] {\n const configured = resolveCORSOrigins(raw).filter((origin) => origin !== '*')\n return uniq([...configured, appURL.origin])\n}\n\nfunction escapeAttribute(value: string): string {\n return value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<')\n}\n\n/**\n * Writes a page that forwards to the link, readable only by this user, so the browser is opened\n * with the page's path rather than the link: a command line, which other users of the computer\n * can list, then never holds the pairing code. Returns the path and a function that deletes it.\n */\nexport async function writeConnectPage(\n dir: string,\n link: string\n): Promise<{ path: string; remove: () => Promise<void> }> {\n const path = join(dir, `connect-${randomBytes(8).toString('hex')}.html`)\n const href = escapeAttribute(link)\n const html =\n `<!doctype html><meta charset=\"utf-8\"><meta name=\"referrer\" content=\"no-referrer\">` +\n `<meta http-equiv=\"refresh\" content=\"0;url=${href}\"><title>Pairdraw</title>` +\n `<a href=\"${href}\">Open Pairdraw</a>\\n`\n await writeFile(path, html, { mode: 0o600, flag: 'wx' })\n return { path, remove: () => rm(path, { force: true }) }\n}\n","#!/usr/bin/env node\nimport { spawn } from 'node:child_process'\nimport { platform } from 'node:os'\n\nimport {\n connectCORSOrigins,\n connectLink,\n resolveConnectAppURL,\n writeConnectPage\n} from '#mcp/agents/link'\nimport { pairingFingerprint } from '#mcp/agents/pairing'\nimport { resolveMCPRoot } from '#mcp/root'\nimport { MCP_VERSION, startServer } from '#mcp/server'\nimport { readToolPolicyFromEnv } from '#mcp/tool/policy'\nimport { DEFAULT_CONNECT_APP_URL } from '#mcp/transport/origins'\nimport { getCompanionDir } from '#mcp/transport/paths'\n\nconst DEFAULT_PORT = 7600\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-connect\\n\\n` +\n `Connect Pairdraw in the browser to this computer, so its chat can run\\n` +\n `Claude Code, Codex, Gemini CLI, or omp here and use Pairdraw's tools.\\n\\n` +\n `Starts Pairdraw's MCP server with an agent bridge and opens a one-time link\\n` +\n `that pairs the browser tab. Keep it running while you use agents.\\n\\n` +\n `Options:\\n` +\n ` --help, -h Show this help message\\n` +\n ` --version Print the version\\n` +\n ` --no-open Print the link without opening the browser\\n\\n` +\n `Environment variables:\\n` +\n ` PORT TCP port (default: ${DEFAULT_PORT})\\n` +\n ` PAIRDRAW_CONNECT_APP_URL The Pairdraw web app to pair with (default:\\n` +\n ` ${DEFAULT_CONNECT_APP_URL}, the editor \\`bun run dev\\` serves).\\n` +\n ` Its origin may call this server.\\n` +\n ` PAIRDRAW_MCP_CORS_ORIGIN Further origins allowed to call this server, comma-separated.\\n` +\n ` PAIRDRAW_MCP_ROOT Allowed directory for file-scoped tools (default: home\\n` +\n ` directory on Windows, current working directory elsewhere)\\n` +\n ` PAIRDRAW_MCP_SOCKET Override the Unix socket path\\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` +\n `The eval tool is always off here, and authentication cannot be disabled.\\n`\n )\n process.exit(0)\n}\n\nfunction fail(message: string): never {\n process.stderr.write(`Error: ${message}\\n`)\n process.exit(1)\n}\n\nconst portText = (process.env.PORT ?? String(DEFAULT_PORT)).trim()\nif (!/^\\d+$/.test(portText)) fail(`PORT must be an integer in 1–65535, got \"${portText}\"`)\nconst port = Number.parseInt(portText, 10)\nif (port < 1 || port > 65535) fail(`PORT must be an integer in 1–65535, got \"${portText}\"`)\n\nconst appURL = resolveConnectAppURL(process.env.PAIRDRAW_CONNECT_APP_URL)\nif (!appURL) {\n fail('PAIRDRAW_CONNECT_APP_URL must be an https URL, or http on localhost')\n}\n\nconst explicitToken = process.env.PAIRDRAW_MCP_AUTH_TOKEN?.trim()\nconst toolPolicy = readToolPolicyFromEnv()\n\nlet handle: Awaited<ReturnType<typeof startServer>>\ntry {\n handle = await startServer({\n httpPort: port,\n withTcp: true,\n socketPath: process.env.PAIRDRAW_MCP_SOCKET?.trim() || null,\n // The browser runs agents that can edit files; eval would let a page run code here too.\n enableEval: false,\n disabledTools: toolPolicy.disabledTools,\n scope: toolPolicy.scope,\n mcpRoot: resolveMCPRoot(process.env.PAIRDRAW_MCP_ROOT),\n // Auth always stays on: a paired tab and local MCP clients each bring their own token.\n authToken: explicitToken || undefined,\n corsOrigin: connectCORSOrigins(process.env.PAIRDRAW_MCP_CORS_ORIGIN, appURL),\n agents: {\n onPaired: () =>\n process.stdout.write(\n 'A browser tab connected. If you did not open the link, press Ctrl+C to stop.\\n'\n )\n }\n })\n} catch (error) {\n const code = error instanceof Error && 'code' in error ? error.code : null\n if (code === 'EADDRINUSE') {\n fail(\n `port ${port} or the MCP socket is already in use. Quit the Pairdraw desktop app or ` +\n `another MCP server, or start this one with PORT=${port + 1}.`\n )\n }\n fail(error instanceof Error ? error.message : String(error))\n}\n\nconst issueCode = handle.issuePairingCode\nif (!issueCode) fail('The agent bridge did not start.')\n\n/** Opens a file or link in the default browser, without a shell. */\nfunction openBrowser(url: string): void {\n const os = platform()\n let command = 'xdg-open'\n let args = [url]\n if (os === 'darwin') command = 'open'\n if (os === 'win32') {\n command = 'rundll32'\n args = ['url.dll,FileProtocolHandler', url]\n }\n try {\n const child = spawn(command, args, { stdio: 'ignore', detached: true })\n child.on('error', () => undefined)\n child.unref()\n } catch {\n process.stdout.write('Could not open the browser; open the link above yourself.\\n')\n }\n}\n\nconst shouldOpen = !process.argv.includes('--no-open')\n/** How long the page that forwards to a link stays on disk; the browser reads it at once. */\nconst PAGE_LIFETIME_MS = 30_000\n\n/**\n * Opens the link through a private page, so no command line holds the code, and deletes the\n * page soon after.\n */\nasync function openLink(link: string): Promise<void> {\n try {\n const page = await writeConnectPage(await getCompanionDir(), link)\n openBrowser(page.path)\n setTimeout(() => void page.remove(), PAGE_LIFETIME_MS).unref()\n } catch {\n process.stdout.write('Could not open the browser; open the link above yourself.\\n')\n }\n}\n\nfunction announceLink(open: boolean) {\n const code = issueCode()\n const link = connectLink(appURL, code, handle.httpPort, DEFAULT_PORT)\n process.stdout.write(\n `\\nOpen this link to connect Pairdraw to this computer (works once, for 2 minutes):\\n` +\n ` ${link}\\n` +\n `The tab asks you to confirm; check that it shows ${pairingFingerprint(code)}.\\n\\n` +\n `Press Enter for a new link. Press Ctrl+C to stop.\\n`\n )\n if (open) void openLink(link)\n}\n\nprocess.stdout.write(`Pairdraw companion ${MCP_VERSION}\\n`)\nprocess.stdout.write(` HTTP: http://127.0.0.1:${handle.httpPort}\\n`)\nif (handle.socketPath) process.stdout.write(` Socket: ${handle.socketPath}\\n`)\nannounceLink(shouldOpen)\n\nprocess.stdin.on('data', () => announceLink(false))\nprocess.stdin.on('error', () => undefined)\nprocess.stdin.resume()\n\nconst shutdown = async () => {\n process.stdout.write('\\nStopping the Pairdraw companion...\\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"],"mappings":";;;;;;;;;;;;;;AASA,SAAS,YAAY,UAA2B;CAC9C,OACE,aAAa,eACb,SAAS,SAAS,YAAY,KAC9B,aAAa,eACb,aAAa;AAEjB;;;;;;AAOA,SAAgB,qBAAqB,KAAqC;CACxE,MAAM,OAAO,KAAK,KAAK,KAAA;CACvB,IAAI;CACJ,IAAI;EACF,MAAM,IAAI,IAAI,IAAI;CACpB,QAAQ;EACN,OAAO;CACT;CACA,IAAI,IAAI,YAAY,IAAI,UAAU,OAAO;CACzC,IAAI,IAAI,aAAa,UAAU,OAAO;CACtC,OAAO,IAAI,aAAa,WAAW,YAAY,IAAI,QAAQ,IAAI,MAAM;AACvE;;;;;AAMA,SAAgB,YAAY,QAAa,MAAc,MAAc,aAA6B;CAChG,MAAM,OAAO,IAAI,IAAI,MAAM;CAC3B,MAAM,SAAS,IAAI,gBAAgB,EAAE,SAAS,KAAK,CAAC;CACpD,IAAI,SAAS,aAAa,OAAO,IAAI,QAAQ,OAAO,IAAI,CAAC;CACzD,KAAK,OAAO,OAAO,SAAS;CAC5B,OAAO,KAAK,SAAS;AACvB;;;;;AAMA,SAAgB,mBAAmB,KAAyB,QAAuB;CACjF,MAAM,aAAa,mBAAmB,GAAG,CAAC,CAAC,QAAQ,WAAW,WAAW,GAAG;CAC5E,OAAO,KAAK,CAAC,GAAG,YAAY,OAAO,MAAM,CAAC;AAC5C;AAEA,SAAS,gBAAgB,OAAuB;CAC9C,OAAO,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,QAAQ,CAAC,CAAC,QAAQ,MAAM,MAAM;AAClF;;;;;;AAOA,eAAsB,iBACpB,KACA,MACwD;C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ACnC,MAAM,OAAO,UAAU;CACvB,MAAM,OAAO,YAAY,QAAQ,MAAM,OAAO,UAAU,YAAY;CACpE,QAAQ,OAAO,MACb,yFACO,KAAK,qDAC0C,mBAAmB,IAAI,EAAE,yDAEjF;CACA,IAAI,MAAM,AAAK,SAAS,IAAI;AAC9B;AAEA,QAAQ,OAAO,MAAM,sBAAsB,YAAY,GAAG;AAC1D,QAAQ,OAAO,MAAM,8BAA8B,OAAO,SAAS,GAAG;AACtE,IAAI,OAAO,YAAY,QAAQ,OAAO,MAAM,aAAa,OAAO,WAAW,GAAG;AAC9E,aAAa,UAAU;AAEvB,QAAQ,MAAM,GAAG,cAAc,aAAa,KAAK,CAAC;AAClD,QAAQ,MAAM,GAAG,eAAe,MAAS;AACzC,QAAQ,MAAM,OAAO;AAErB,MAAM,WAAW,YAAY;CAC3B,QAAQ,OAAO,MAAM,wCAAwC;CAC7D,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"}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import "./rolldown-runtime-ClRpJifh.mjs";
|
|
2
|
+
import { a as getSocketPath, o as platformHasUnixSockets, r as getDiscoveryPath } from "./paths-BpcXnrbP.mjs";
|
|
3
|
+
import { t as MCP_TOOL_SCOPES } from "./scope-D2LTTsDw.mjs";
|
|
4
|
+
import * as v from "valibot";
|
|
5
|
+
import { access, constants, lstat, readFile, unlink } from "node:fs/promises";
|
|
6
|
+
import { Socket } from "node:net";
|
|
7
|
+
import { writeFileAtomic } from "@pairdraw/core/node/fs";
|
|
8
|
+
//#region src/transport/discovery.ts
|
|
9
|
+
const discoveryInfoSchema = v.pipe(v.string(), v.parseJson(), v.object({
|
|
10
|
+
pid: v.pipe(v.number(), v.integer(), v.minValue(1)),
|
|
11
|
+
version: v.string(),
|
|
12
|
+
httpPort: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(65535)),
|
|
13
|
+
authRequired: v.boolean(),
|
|
14
|
+
startedAt: v.string(),
|
|
15
|
+
socketPath: v.nullable(v.pipe(v.string(), v.nonEmpty())),
|
|
16
|
+
authToken: v.nullable(v.string()),
|
|
17
|
+
disabledTools: v.optional(v.array(v.string()), () => []),
|
|
18
|
+
scope: v.optional(v.picklist(MCP_TOOL_SCOPES), "document")
|
|
19
|
+
}));
|
|
20
|
+
/** Parse discovery file contents, or null when the file is not valid discovery JSON. */
|
|
21
|
+
function parseDiscoveryInfo(raw) {
|
|
22
|
+
const result = v.safeParse(discoveryInfoSchema, raw);
|
|
23
|
+
return result.success ? result.output : null;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Writes the discovery JSON file at the platform-appropriate location.
|
|
27
|
+
* Overwrites any existing file (from a previous server instance).
|
|
28
|
+
*
|
|
29
|
+
* The file is written all at once with `0o600` permissions, replacing a symlink at the path
|
|
30
|
+
* rather than writing through it, so readers never see half a file and concurrent writers never
|
|
31
|
+
* interleave.
|
|
32
|
+
*
|
|
33
|
+
* WARNING: The auth token is written in plaintext. Do not sync the discovery
|
|
34
|
+
* file to cloud storage or include it in backups without encryption.
|
|
35
|
+
*/
|
|
36
|
+
async function writeDiscoveryFile(info) {
|
|
37
|
+
const path = await getDiscoveryPath();
|
|
38
|
+
const json = JSON.stringify(info, null, 2);
|
|
39
|
+
await writeFileAtomic(path, json, { mode: 384 });
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Reads the discovery file. Returns null if:
|
|
43
|
+
* - The file does not exist
|
|
44
|
+
* - The file cannot be parsed
|
|
45
|
+
* - The recorded PID is no longer running (stale file)
|
|
46
|
+
*
|
|
47
|
+
* On success, returns the parsed DiscoveryInfo.
|
|
48
|
+
*/
|
|
49
|
+
async function readDiscoveryFile() {
|
|
50
|
+
const path = await getDiscoveryPath();
|
|
51
|
+
let raw;
|
|
52
|
+
try {
|
|
53
|
+
raw = await readFile(path, "utf-8");
|
|
54
|
+
} catch (e) {
|
|
55
|
+
if (!isEnoent(e)) process.stderr.write(` Discovery: read warning (${e instanceof Error ? e.message : String(e)})\n`);
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
const info = parseDiscoveryInfo(raw);
|
|
59
|
+
if (!info) return null;
|
|
60
|
+
if (!isProcessAlive(info.pid)) return null;
|
|
61
|
+
return info;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Removes the discovery file. Does not throw if the file does not exist.
|
|
65
|
+
*/
|
|
66
|
+
async function removeDiscoveryFile() {
|
|
67
|
+
const path = await getDiscoveryPath();
|
|
68
|
+
try {
|
|
69
|
+
await unlink(path);
|
|
70
|
+
} catch (e) {
|
|
71
|
+
if (!isEnoent(e)) throw e;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
async function isSocketLiveViaTcp(socketPath) {
|
|
75
|
+
let discoveryPath;
|
|
76
|
+
try {
|
|
77
|
+
discoveryPath = await getDiscoveryPath();
|
|
78
|
+
} catch {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
const raw = await readFile(discoveryPath, "utf-8").catch(() => null);
|
|
82
|
+
if (!raw) return false;
|
|
83
|
+
const info = parseDiscoveryInfo(raw);
|
|
84
|
+
if (!info || info.socketPath !== socketPath) return false;
|
|
85
|
+
if (info.httpPort <= 0) return isProcessAlive(info.pid);
|
|
86
|
+
return fetch(`http://127.0.0.1:${info.httpPort}/health`, { signal: AbortSignal.timeout(2e3) }).then(() => true).catch((e) => {
|
|
87
|
+
if (e instanceof Error && e.name === "TimeoutError") return true;
|
|
88
|
+
return false;
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Direct Unix-socket connection probe. A server binds the socket before
|
|
93
|
+
* writeDiscovery(), so isSocketLiveViaTcp() can return false during that
|
|
94
|
+
* window. This probe connects directly to the socket path — a successful
|
|
95
|
+
* connection or timeout means the socket is live; only ECONNREFUSED means
|
|
96
|
+
* no process is listening.
|
|
97
|
+
*/
|
|
98
|
+
function probeSocketLive(socketPath) {
|
|
99
|
+
return new Promise((resolve) => {
|
|
100
|
+
let settled = false;
|
|
101
|
+
const socket = new Socket();
|
|
102
|
+
const finish = (result) => {
|
|
103
|
+
if (settled) return;
|
|
104
|
+
settled = true;
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
socket.destroy();
|
|
107
|
+
resolve(result);
|
|
108
|
+
};
|
|
109
|
+
const timer = setTimeout(() => finish(true), 1e3);
|
|
110
|
+
socket.once("connect", () => finish(true));
|
|
111
|
+
socket.once("error", (err) => {
|
|
112
|
+
const code = err.code;
|
|
113
|
+
finish(code !== "ECONNREFUSED");
|
|
114
|
+
});
|
|
115
|
+
socket.connect(socketPath);
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Removes a stale Unix domain socket file if it exists and is not live.
|
|
120
|
+
* A socket is considered stale if no process is listening on it.
|
|
121
|
+
*/
|
|
122
|
+
async function removeStaleSocket(socketPathOverride) {
|
|
123
|
+
if (!platformHasUnixSockets()) return;
|
|
124
|
+
const socketPath = socketPathOverride ?? await getSocketPath();
|
|
125
|
+
let exists;
|
|
126
|
+
try {
|
|
127
|
+
await access(socketPath, constants.F_OK);
|
|
128
|
+
exists = true;
|
|
129
|
+
} catch {
|
|
130
|
+
exists = false;
|
|
131
|
+
}
|
|
132
|
+
if (!exists) return;
|
|
133
|
+
const stat = await lstat(socketPath).catch((e) => {
|
|
134
|
+
if (isEnoent(e)) return null;
|
|
135
|
+
throw e;
|
|
136
|
+
});
|
|
137
|
+
if (!stat) return;
|
|
138
|
+
if (!stat.isSocket()) throw new Error(`Refusing to remove non-socket path: ${socketPath}`);
|
|
139
|
+
if (await probeSocketLive(socketPath)) return;
|
|
140
|
+
if (await isSocketLiveViaTcp(socketPath)) return;
|
|
141
|
+
try {
|
|
142
|
+
await unlink(socketPath);
|
|
143
|
+
} catch (e) {
|
|
144
|
+
if (e instanceof Error && "code" in e && e.code !== "ENOENT") process.stderr.write(`Failed to remove stale socket: ${e.message}\n`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Checks if a process with the given PID is still running.
|
|
149
|
+
* Uses process.kill(pid, 0) which doesn't send a signal, just checks existence.
|
|
150
|
+
* Works on both Unix and Windows.
|
|
151
|
+
*/
|
|
152
|
+
function isProcessAlive(pid) {
|
|
153
|
+
try {
|
|
154
|
+
process.kill(pid, 0);
|
|
155
|
+
return true;
|
|
156
|
+
} catch (e) {
|
|
157
|
+
if (e instanceof Error && "code" in e && e.code === "ESRCH") return false;
|
|
158
|
+
return true;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function isEnoent(e) {
|
|
162
|
+
return e instanceof Error && "code" in e && e.code === "ENOENT";
|
|
163
|
+
}
|
|
164
|
+
//#endregion
|
|
165
|
+
export { writeDiscoveryFile as a, removeStaleSocket as i, readDiscoveryFile as n, removeDiscoveryFile as r, parseDiscoveryInfo as t };
|
|
166
|
+
|
|
167
|
+
//# sourceMappingURL=discovery-CB2Bv5WA.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"discovery-CB2Bv5WA.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,E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;;;;;AAMA,eAAsB,kBAAkB,oBAA4C;CAClF,IAAI,CAAC,uBAAuB,GAAG;CAE/B,MAAM,aAAa,sBAAuB,MAAM,cAAc;CAC9D,IAAI;CACJ,IAAI;EACF,MAAM,OAAO,YAAY,UAAU,IAAI;EACvC,SAAS;CACX,QAAQ;EACN,SAAS;CACX;CAEA,IAAI,CAAC,QAAQ;CAKb,MAAM,OAAO,MAAM,MAAM,UAAU,CAAC,CAAC,OAAO,MAAM;EAChD,IAAI,SAAS,CAAC,GAAG,OAAO;EACxB,MAAM;CACR,CAAC;CACD,IAAI,CAAC,MAAM;CACX,IAAI,CAAC,KAAK,SAAS,GACjB,MAAM,IAAI,MAAM,uCAAuC,YAAY;CAGrE,IAAI,MAAM,gBAAgB,UAAU,GAAG;CACvC,IAAI,MAAM,mBAAmB,UAAU,GAAG;CAG1C,IAAI;EACF,MAAM,OAAO,UAAU;CACzB,SAAS,GAAG;EACV,IAAI,aAAa,SAAS,UAAU,KAAM,EAA4B,SAAS,UAC7E,QAAQ,OAAO,MAAM,kCAAkC,EAAE,QAAQ,GAAG;CAExE;AACF;;;;;;AAOA,SAAS,eAAe,KAAsB;CAC5C,IAAI;EACF,QAAQ,KAAK,KAAK,CAAC;EACnB,OAAO;CACT,SAAS,GAAG;EACV,IAAI,aAAa,SAAS,UAAU,KAAM,EAA4B,SAAS,SAC7E,OAAO;EAET,OAAO;CACT;AACF;AAEA,SAAS,SAAS,GAAqB;CACrC,OAAO,aAAa,SAAS,UAAU,KAAM,EAA4B,SAAS;AACpF"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import "./rolldown-runtime-ClRpJifh.mjs";
|
|
2
|
+
import { t as MCPToolScope } from "./scope-DJ9hsBYV.mjs";
|
|
3
|
+
//#region src/transport/discovery.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Metadata written to the discovery file so clients can auto-locate
|
|
6
|
+
* the running MCP server without knowing the socket path or TCP port.
|
|
7
|
+
*
|
|
8
|
+
* WARNING: The discovery file contains a plaintext auth token. Do not sync
|
|
9
|
+
* this file to cloud storage or include it in backups without encryption.
|
|
10
|
+
* Any process running as the same user can read this file.
|
|
11
|
+
*/
|
|
12
|
+
interface DiscoveryInfo {
|
|
13
|
+
pid: number;
|
|
14
|
+
/** Unix domain socket path, or null on platforms that don't support them (Windows). */
|
|
15
|
+
socketPath: string | null;
|
|
16
|
+
httpPort: number;
|
|
17
|
+
authRequired: boolean;
|
|
18
|
+
authToken: string | null;
|
|
19
|
+
version: string;
|
|
20
|
+
startedAt: string;
|
|
21
|
+
disabledTools?: string[];
|
|
22
|
+
/** What MCP clients can reach; stdio clients started outside the app follow it. */
|
|
23
|
+
scope?: MCPToolScope;
|
|
24
|
+
}
|
|
25
|
+
/** Parse discovery file contents, or null when the file is not valid discovery JSON. */
|
|
26
|
+
declare function parseDiscoveryInfo(raw: string): DiscoveryInfo | null;
|
|
27
|
+
/**
|
|
28
|
+
* Writes the discovery JSON file at the platform-appropriate location.
|
|
29
|
+
* Overwrites any existing file (from a previous server instance).
|
|
30
|
+
*
|
|
31
|
+
* The file is written all at once with `0o600` permissions, replacing a symlink at the path
|
|
32
|
+
* rather than writing through it, so readers never see half a file and concurrent writers never
|
|
33
|
+
* interleave.
|
|
34
|
+
*
|
|
35
|
+
* WARNING: The auth token is written in plaintext. Do not sync the discovery
|
|
36
|
+
* file to cloud storage or include it in backups without encryption.
|
|
37
|
+
*/
|
|
38
|
+
declare function writeDiscoveryFile(info: DiscoveryInfo): Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Reads the discovery file. Returns null if:
|
|
41
|
+
* - The file does not exist
|
|
42
|
+
* - The file cannot be parsed
|
|
43
|
+
* - The recorded PID is no longer running (stale file)
|
|
44
|
+
*
|
|
45
|
+
* On success, returns the parsed DiscoveryInfo.
|
|
46
|
+
*/
|
|
47
|
+
declare function readDiscoveryFile(): Promise<DiscoveryInfo | null>;
|
|
48
|
+
/**
|
|
49
|
+
* Removes the discovery file. Does not throw if the file does not exist.
|
|
50
|
+
*/
|
|
51
|
+
declare function removeDiscoveryFile(): Promise<void>;
|
|
52
|
+
/**
|
|
53
|
+
* Removes a stale Unix domain socket file if it exists and is not live.
|
|
54
|
+
* A socket is considered stale if no process is listening on it.
|
|
55
|
+
*/
|
|
56
|
+
declare function removeStaleSocket(socketPathOverride?: string): Promise<void>;
|
|
57
|
+
//#endregion
|
|
58
|
+
export { DiscoveryInfo, parseDiscoveryInfo, readDiscoveryFile, removeDiscoveryFile, removeStaleSocket, writeDiscoveryFile };
|
|
59
|
+
//# sourceMappingURL=discovery.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as writeDiscoveryFile, i as removeStaleSocket, n as readDiscoveryFile, r as removeDiscoveryFile, t as parseDiscoveryInfo } from "./discovery-CB2Bv5WA.mjs";
|
|
2
|
+
export { parseDiscoveryInfo, readDiscoveryFile, removeDiscoveryFile, removeStaleSocket, writeDiscoveryFile };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import "./rolldown-runtime-ClRpJifh.mjs";
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import "./rolldown-runtime-ClRpJifh.mjs";
|
|
3
|
+
import { d as devAgentBridgeFromEnv, i as resolveCORSOrigins, n as startServer, t as MCP_VERSION } from "./server-BdiJUhSs.mjs";
|
|
4
|
+
import { t as resolveMCPRoot } from "./root-BzmoiT2g.mjs";
|
|
5
|
+
import { i as readToolPolicyFromEnv } from "./policy-B8Ka4WRH.mjs";
|
|
6
|
+
//#region src/index.ts
|
|
7
|
+
if (process.argv.includes("--version")) {
|
|
8
|
+
process.stdout.write(`${MCP_VERSION}\n`);
|
|
9
|
+
process.exit(0);
|
|
10
|
+
}
|
|
11
|
+
if (process.argv.includes("--help") || process.argv.includes("-h")) {
|
|
12
|
+
process.stdout.write("pairdraw-mcp-http\n\nStart the Pairdraw MCP server.\n\nOn macOS/Linux, the server listens on a Unix domain socket by default\nwith optional TCP for browser clients. On Windows, only TCP is available.\n\nOptions:\n --help, -h Show this help message\n --version Print the version\n\nEnvironment variables:\n PORT TCP port (default: 7600, set to 0 to disable TCP)\n PAIRDRAW_MCP_SOCKET Override Unix socket path (recorded in the discovery file)\n PAIRDRAW_MCP_DISCOVERY_PATH Override discovery file (mcp.json) location; defaults to the\n platform path. Parent dir created 0o700. Mainly for test isolation.\n PAIRDRAW_MCP_TCP Deprecated — TCP is controlled by PORT (>0 = on, 0 = off)\n PAIRDRAW_MCP_AUTH_TOKEN Bearer token for MCP and RPC auth\n PAIRDRAW_MCP_ROOT Allowed directory for file-scoped tools (default: home directory on Windows, current working directory elsewhere)\n PAIRDRAW_MCP_EVAL Set to 1 to enable the eval tool\n PAIRDRAW_MCP_SESSION_IDLE_TIMEOUT_MS\n Close sessions idle this long, in ms (default: 900000;\n 0 disables). An open GET/SSE stream is not activity.\n PAIRDRAW_MCP_DISABLED_TOOLS Comma-separated tool names to omit\n PAIRDRAW_MCP_SCOPE \"selection\" to let clients read only the selected layers\n (default: \"document\")\n PAIRDRAW_MCP_CORS_ORIGIN Allowed CORS origins, comma-separated.\n Defaults to the desktop app origin, since the app\n webview is the only view that calls this server.\n PAIRDRAW_MCP_APP_TIMEOUT_MS If set, close the server and remove its discovery\n file after no app is attached for this many ms. The\n grace period starts at startup and after disconnects.\n Unset/0 disables it (default) — do not set this for\n manual/CLI use, since nothing may ever register.\n PAIRDRAW_MCP_EXIT_ON_STDIN_CLOSE Set to 1 to shut down when stdin closes, so a\n parent that starts the server through a shell wrapper\n can stop it by closing the pipe. Unset for manual/CLI use.\n PAIRDRAW_MCP_AGENTS Set to 1, with the two variables below, to start the agent\n bridge for one browser tab that the parent process gave\n the same tokens, as `bun run dev` does; no pairing link.\n The tokens are never written to the discovery file,\n and the eval tool stays off.\n PAIRDRAW_MCP_AGENT_SESSION The tab's session token: 64 lowercase hex characters.\n PAIRDRAW_MCP_AGENT_TOKEN The token the tab hands its agents, which reaches only\n /mcp: 64 lowercase hex characters, not the session token.\n");
|
|
13
|
+
process.exit(0);
|
|
14
|
+
}
|
|
15
|
+
const rawPortText = (process.env.PORT ?? "7600").trim();
|
|
16
|
+
if (!/^\d+$/.test(rawPortText)) {
|
|
17
|
+
process.stderr.write(`Error: PORT must be an integer in 0–65535, got "${process.env.PORT}"\n`);
|
|
18
|
+
process.exit(1);
|
|
19
|
+
}
|
|
20
|
+
const rawPort = Number.parseInt(rawPortText, 10);
|
|
21
|
+
if (rawPort < 0 || rawPort > 65535) {
|
|
22
|
+
process.stderr.write(`Error: PORT must be an integer in 0–65535, got "${process.env.PORT}"\n`);
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
const port = rawPort;
|
|
26
|
+
const withTcp = port > 0;
|
|
27
|
+
const MAX_TIMEOUT_MS = 2147483647;
|
|
28
|
+
/** Read a millisecond timeout from the environment, exiting on an invalid value. */
|
|
29
|
+
function readTimeoutEnv(name) {
|
|
30
|
+
const text = process.env[name]?.trim();
|
|
31
|
+
if (!text) return void 0;
|
|
32
|
+
const timeoutMs = Number(text);
|
|
33
|
+
if (!/^\d+$/.test(text) || timeoutMs > MAX_TIMEOUT_MS) {
|
|
34
|
+
process.stderr.write(`Error: ${name} must be an integer in 0–${MAX_TIMEOUT_MS}, got "${text}"\n`);
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
return timeoutMs;
|
|
38
|
+
}
|
|
39
|
+
const appAttachTimeoutMs = readTimeoutEnv("PAIRDRAW_MCP_APP_TIMEOUT_MS");
|
|
40
|
+
const sessionIdleTimeoutMs = readTimeoutEnv("PAIRDRAW_MCP_SESSION_IDLE_TIMEOUT_MS");
|
|
41
|
+
const toolPolicy = readToolPolicyFromEnv();
|
|
42
|
+
const agents = devAgentBridgeFromEnv();
|
|
43
|
+
if (process.env.PAIRDRAW_MCP_AGENTS === "1" && !agents) process.stderr.write("Warning: PAIRDRAW_MCP_AGENTS=1 needs PAIRDRAW_MCP_AGENT_SESSION and PAIRDRAW_MCP_AGENT_TOKEN as two different 64-character lowercase hex tokens. Starting without the agent bridge.\n");
|
|
44
|
+
if (agents && toolPolicy.allowEval) process.stderr.write("Warning: PAIRDRAW_MCP_EVAL=1 is ignored while the agent bridge is on (PAIRDRAW_MCP_AGENTS=1). Starting without the eval tool.\n");
|
|
45
|
+
const handle = await startServer({
|
|
46
|
+
httpPort: withTcp ? port : 0,
|
|
47
|
+
withTcp,
|
|
48
|
+
socketPath: process.env.PAIRDRAW_MCP_SOCKET?.trim() || null,
|
|
49
|
+
enableEval: toolPolicy.allowEval && !agents,
|
|
50
|
+
disabledTools: toolPolicy.disabledTools,
|
|
51
|
+
scope: toolPolicy.scope,
|
|
52
|
+
mcpRoot: resolveMCPRoot(process.env.PAIRDRAW_MCP_ROOT),
|
|
53
|
+
authToken: (() => {
|
|
54
|
+
const raw = process.env.PAIRDRAW_MCP_AUTH_TOKEN;
|
|
55
|
+
if (raw === void 0) return void 0;
|
|
56
|
+
if (raw === "") return null;
|
|
57
|
+
const trimmed = raw.trim();
|
|
58
|
+
if (!trimmed) {
|
|
59
|
+
process.stderr.write("Error: PAIRDRAW_MCP_AUTH_TOKEN is whitespace-only. Set a real token, or use an empty string to disable auth.\n");
|
|
60
|
+
process.exit(1);
|
|
61
|
+
}
|
|
62
|
+
return trimmed;
|
|
63
|
+
})(),
|
|
64
|
+
corsOrigin: resolveCORSOrigins(process.env.PAIRDRAW_MCP_CORS_ORIGIN),
|
|
65
|
+
appAttachTimeoutMs,
|
|
66
|
+
sessionIdleTimeoutMs,
|
|
67
|
+
agents: agents ?? void 0
|
|
68
|
+
});
|
|
69
|
+
const readyMarker = process.env.PAIRDRAW_MCP_READY_MARKER;
|
|
70
|
+
if (readyMarker && /^pairdraw-ready:[a-f0-9-]{36}$/.test(readyMarker)) process.stderr.write(`${readyMarker}\n`);
|
|
71
|
+
process.stderr.write(`Pairdraw MCP server\n`);
|
|
72
|
+
if (handle.socketPath) process.stderr.write(` Socket: ${handle.socketPath}\n`);
|
|
73
|
+
if (handle.httpPort) process.stderr.write(` HTTP: http://127.0.0.1:${handle.httpPort}\n`);
|
|
74
|
+
const shutdown = async () => {
|
|
75
|
+
process.stderr.write("\nShutting down MCP server...\n");
|
|
76
|
+
await handle.close();
|
|
77
|
+
process.exit(0);
|
|
78
|
+
};
|
|
79
|
+
process.on("SIGINT", () => void shutdown().catch(() => process.exit(1)));
|
|
80
|
+
process.on("SIGTERM", () => void shutdown().catch(() => process.exit(1)));
|
|
81
|
+
if (process.env.PAIRDRAW_MCP_EXIT_ON_STDIN_CLOSE === "1") {
|
|
82
|
+
let stdinClosed = false;
|
|
83
|
+
const onStdinClosed = () => {
|
|
84
|
+
if (stdinClosed) return;
|
|
85
|
+
stdinClosed = true;
|
|
86
|
+
shutdown().catch(() => process.exit(1));
|
|
87
|
+
};
|
|
88
|
+
process.stdin.on("end", onStdinClosed);
|
|
89
|
+
process.stdin.on("close", onStdinClosed);
|
|
90
|
+
process.stdin.resume();
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
export {};
|
|
94
|
+
|
|
95
|
+
//# sourceMappingURL=index.mjs.map
|