@pairdraw/mcp 0.0.0-stage → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -2
  3. package/dist/connect.d.mts +1 -0
  4. package/dist/connect.mjs +192 -0
  5. package/dist/connect.mjs.map +1 -0
  6. package/dist/discovery-CB2Bv5WA.mjs +167 -0
  7. package/dist/discovery-CB2Bv5WA.mjs.map +1 -0
  8. package/dist/discovery.d.mts +59 -0
  9. package/dist/discovery.mjs +2 -0
  10. package/dist/index.d.mts +1 -0
  11. package/dist/index.mjs +95 -0
  12. package/dist/index.mjs.map +1 -0
  13. package/dist/metadata-DVz00c8R.d.mts +26 -0
  14. package/dist/paths-BpcXnrbP.mjs +168 -0
  15. package/dist/paths-BpcXnrbP.mjs.map +1 -0
  16. package/dist/policy-B8Ka4WRH.mjs +206 -0
  17. package/dist/policy-B8Ka4WRH.mjs.map +1 -0
  18. package/dist/rolldown-runtime-ClRpJifh.mjs +3 -0
  19. package/dist/root-BzmoiT2g.mjs +9 -0
  20. package/dist/root-BzmoiT2g.mjs.map +1 -0
  21. package/dist/scope-D2LTTsDw.mjs +66 -0
  22. package/dist/scope-D2LTTsDw.mjs.map +1 -0
  23. package/dist/scope-DJ9hsBYV.d.mts +31 -0
  24. package/dist/server--T-KD99G.mjs +3261 -0
  25. package/dist/server--T-KD99G.mjs.map +1 -0
  26. package/dist/server.d.mts +265 -0
  27. package/dist/server.mjs +2 -0
  28. package/dist/stdio.d.mts +1 -0
  29. package/dist/stdio.mjs +411 -0
  30. package/dist/stdio.mjs.map +1 -0
  31. package/dist/tools.d.mts +17 -0
  32. package/dist/tools.mjs +33 -0
  33. package/dist/tools.mjs.map +1 -0
  34. package/dist/transport.d.mts +59 -0
  35. package/dist/transport.mjs +2 -0
  36. package/package.json +64 -4
  37. package/src/agents/acp.ts +110 -0
  38. package/src/agents/claude-cloud.ts +99 -0
  39. package/src/agents/filter.ts +85 -0
  40. package/src/agents/index.ts +299 -0
  41. package/src/agents/install.ts +44 -0
  42. package/src/agents/link.ts +79 -0
  43. package/src/agents/lookup.ts +136 -0
  44. package/src/agents/pairing.ts +182 -0
  45. package/src/agents/path.ts +85 -0
  46. package/src/agents/process.ts +88 -0
  47. package/src/agents/registry.ts +36 -0
  48. package/src/agents/schema.ts +77 -0
  49. package/src/agents/sign-in.ts +106 -0
  50. package/src/agents/socket.ts +79 -0
  51. package/src/auth.ts +21 -0
  52. package/src/browser-rpc.ts +440 -0
  53. package/src/connect.ts +170 -0
  54. package/src/global.d.ts +5 -0
  55. package/src/http-options.ts +14 -0
  56. package/src/index.ts +179 -0
  57. package/src/json.ts +1 -0
  58. package/src/result.ts +37 -0
  59. package/src/root.ts +5 -0
  60. package/src/rpc-types.ts +5 -0
  61. package/src/server/connections.ts +58 -0
  62. package/src/server/files.ts +49 -0
  63. package/src/server/install-command.ts +24 -0
  64. package/src/server/lifecycle.ts +389 -0
  65. package/src/server/origin.ts +53 -0
  66. package/src/server/pending-requests.ts +62 -0
  67. package/src/server/sessions.ts +335 -0
  68. package/src/server.ts +597 -0
  69. package/src/skill/content.ts +40 -0
  70. package/src/skill/instructions.ts +69 -0
  71. package/src/skill/register.ts +77 -0
  72. package/src/stdio/bridge.ts +460 -0
  73. package/src/stdio.ts +130 -0
  74. package/src/tool/browser.ts +183 -0
  75. package/src/tool/index.ts +12 -0
  76. package/src/tool/manifest.ts +221 -0
  77. package/src/tool/metadata.ts +44 -0
  78. package/src/tool/output.ts +336 -0
  79. package/src/tool/policy.ts +37 -0
  80. package/src/tool/registration.ts +523 -0
  81. package/src/tool/scope.ts +71 -0
  82. package/src/transport/discovery.ts +235 -0
  83. package/src/transport/origins.ts +85 -0
  84. package/src/transport/paths.ts +179 -0
@@ -0,0 +1,265 @@
1
+ import "./rolldown-runtime-ClRpJifh.mjs";
2
+ import { t as MCPToolScope } from "./scope-DJ9hsBYV.mjs";
3
+ import { i as ToolPolicy } from "./metadata-DVz00c8R.mjs";
4
+ import * as v from "valibot";
5
+ import { Hono } from "hono";
6
+ import { McpServer, ServerContext } from "@modelcontextprotocol/server";
7
+ import { IncomingMessage, Server } from "node:http";
8
+ import { Duplex } from "node:stream";
9
+ //#region src/agents/install.d.ts
10
+ /**
11
+ * Installs an agent's adapter package globally with npm; rejects when npm did not finish. It
12
+ * runs in the companion's workspace, so an `.npmrc` in the folder the companion started in
13
+ * cannot point npm elsewhere.
14
+ */
15
+ type PackageInstaller = (packageName: string, searchPath: string, cwd: string) => Promise<void>;
16
+ declare const installWithNpm: PackageInstaller;
17
+ //#endregion
18
+ //#region src/agents/pairing.d.ts
19
+ /** How long a printed link may be opened. */
20
+ declare const PAIRING_CODE_TTL_MS: number;
21
+ /** A paired tab that sends nothing this long is signed out; an open tab checks in every 10 s. */
22
+ declare const SESSION_IDLE_TIMEOUT_MS: number;
23
+ type PairingResult = {
24
+ ok: true;
25
+ token: string;
26
+ agentToken: string;
27
+ } | {
28
+ ok: false;
29
+ reason: 'rejected' | 'rate-limited';
30
+ };
31
+ /** The two tokens of a session that exists without `/pair`. */
32
+ interface TrustedSession {
33
+ token: string;
34
+ agentToken: string;
35
+ }
36
+ interface PairingOptions {
37
+ ttlMs?: number;
38
+ idleTimeoutMs?: number;
39
+ now?: () => number;
40
+ /**
41
+ * Sessions the process that started the server set up for its own tab, as `bun run dev` does
42
+ * through the environment. They never sit idle too long, are never forgotten for newer tabs,
43
+ * and cannot be revoked; they end with the server.
44
+ */
45
+ trusted?: readonly TrustedSession[];
46
+ }
47
+ /**
48
+ * Six characters derived from a pairing code, shown by the companion and by the tab that opens
49
+ * its link, so the person can tell the link is the one their terminal printed. The app derives
50
+ * the same characters (`companionFingerprint` in `src/app/automation/companion/`).
51
+ */
52
+ declare function pairingFingerprint(code: string): string;
53
+ /**
54
+ * One-time codes and the tokens they buy. A code is printed in the link the companion opens,
55
+ * works once, and expires. Pairing returns two tokens: the tab's session token, which reaches
56
+ * the agent routes, and an agent token, which reaches only the MCP server and is what the tab
57
+ * hands the agents it starts. Both live only in this process and the tab's memory, so
58
+ * restarting the companion signs every tab out. Trusted sessions skip the code: the process that
59
+ * started the server made their tokens and gave them to its own tab.
60
+ */
61
+ declare function createPairing({ ttlMs, idleTimeoutMs, now, trusted }?: PairingOptions): {
62
+ issueCode: () => string;
63
+ exchange: (candidate: string) => PairingResult;
64
+ isSession: (token: string | null | undefined) => boolean;
65
+ isAgentToken: (token: string | null | undefined) => boolean;
66
+ revoke: (token: string) => void;
67
+ };
68
+ //#endregion
69
+ //#region src/agents/registry.d.ts
70
+ /**
71
+ * An agent the companion may start. Every command line is fixed here: a client names an agent
72
+ * by its id and never sends a program, arguments, or environment.
73
+ */
74
+ interface CompanionAgent {
75
+ id: string;
76
+ /** The ACP program the bridge starts. */
77
+ command: string;
78
+ args: readonly string[];
79
+ /** The agent's own CLI, when the ACP program is a separate adapter for it. */
80
+ cliCommand?: string;
81
+ /** The npm package `install` puts on the computer, when the ACP program is an adapter. */
82
+ adapterPackage?: string;
83
+ /** Arguments of a sign-in the agent runs in a terminal, such as Claude's browser login. */
84
+ terminalSignIn?: readonly string[];
85
+ }
86
+ /** The agents the app offers, as `ACP_AGENTS` in Core defines them. */
87
+ declare const COMPANION_AGENTS: readonly CompanionAgent[];
88
+ /** The agent a route names, or undefined for an id the companion does not know. */
89
+ declare function findCompanionAgent(registry: readonly CompanionAgent[], id: string): CompanionAgent | undefined;
90
+ //#endregion
91
+ //#region src/agents/index.d.ts
92
+ interface AgentBridgeOptions {
93
+ /** Where agents start, created on first use; defaults to a folder beside the discovery file. */
94
+ workspace?: string;
95
+ /** The agents the bridge may start. Defaults to `ACP_AGENTS`; tests pass stand-ins. */
96
+ registry?: readonly CompanionAgent[];
97
+ /** The PATH agents are found on and started with; defaults to an augmented `PATH`. */
98
+ searchPath?: string;
99
+ /** Installs adapter packages; defaults to `npm install --global`. */
100
+ installer?: PackageInstaller;
101
+ /** Code and session lifetimes; trusted sessions come from `trustedSessions`. */
102
+ pairing?: Omit<PairingOptions, 'trusted'>;
103
+ /**
104
+ * Sessions that need no `/pair`, for the tab of the process that started the server
105
+ * (`devAgentBridgeFromEnv`). They never expire and cannot be revoked.
106
+ */
107
+ trustedSessions?: readonly TrustedSession[];
108
+ /** The TCP port the server listens on, which is where the companion's own MCP endpoint is. */
109
+ port?: () => number;
110
+ /** Told each time a tab pairs, so the companion can say so in its terminal. */
111
+ onPaired?: () => void;
112
+ }
113
+ /**
114
+ * The bridge `bun run dev` asks the MCP server it starts for: `PAIRDRAW_MCP_AGENTS=1`, with its
115
+ * tab's session in `PAIRDRAW_MCP_AGENT_SESSION` and `PAIRDRAW_MCP_AGENT_TOKEN`. Null without
116
+ * them or when they are malformed, and the server then has no bridge. The tokens stay in this
117
+ * process: the discovery file never holds them.
118
+ */
119
+ declare function devAgentBridgeFromEnv(env?: NodeJS.ProcessEnv): AgentBridgeOptions | null;
120
+ /**
121
+ * The companion's agent bridge: pairing, finding and installing agents, and starting them for a
122
+ * paired tab. Every route and socket here needs a session token from `/pair`; the MCP server's
123
+ * own token, which local MCP clients read from the discovery file, does not start programs.
124
+ */
125
+ declare function createAgentBridge(options: AgentBridgeOptions & {
126
+ version: string;
127
+ entry: string;
128
+ }): {
129
+ routes: (app: Hono) => void;
130
+ handleUpgrade: (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
131
+ close: () => Promise<void>;
132
+ issuePairingCode: () => string;
133
+ isSession: (token: string | null | undefined) => boolean;
134
+ isAgentToken: (token: string | null | undefined) => boolean;
135
+ };
136
+ type AgentBridge = ReturnType<typeof createAgentBridge>;
137
+ //#endregion
138
+ //#region src/result.d.ts
139
+ type MCPContent = {
140
+ type: 'text';
141
+ text: string;
142
+ } | {
143
+ type: 'image';
144
+ data: string;
145
+ mimeType: string;
146
+ };
147
+ type MCPResult = {
148
+ content: MCPContent[];
149
+ isError?: boolean;
150
+ };
151
+ declare const MAX_RESULT_BYTES = 900000;
152
+ declare function resultTooLargeMessage(kind: string, bytes: number, hint: string): string;
153
+ declare function ok(data: unknown, toolName?: string): MCPResult;
154
+ declare function fail(e: unknown): MCPResult;
155
+ //#endregion
156
+ //#region src/tool/registration.d.ts
157
+ type RPCSender = (body: Record<string, unknown>) => Promise<unknown>;
158
+ type MCPToolSettled = (context: ServerContext) => Promise<void>;
159
+ declare const automationTargetSchema: {
160
+ document_id: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.DescriptionAction<string, "Optional Pairdraw document/tab ID to target">]>, undefined>;
161
+ page_id: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.DescriptionAction<string, "Optional page ID to target within the document">]>, undefined>;
162
+ };
163
+ declare function splitAutomationTarget(args: Record<string, unknown>): {
164
+ target: {
165
+ document_id?: string;
166
+ page_id?: string;
167
+ };
168
+ args: Record<string, unknown>;
169
+ };
170
+ type RPCResponse = {
171
+ ok?: boolean;
172
+ result?: unknown;
173
+ target?: unknown;
174
+ error?: string;
175
+ };
176
+ declare function sendCommand(sendRPC: RPCSender, command: string, args: Record<string, unknown>): Promise<RPCResponse>;
177
+ declare function withTarget<T extends object>(body: T, res: RPCResponse): T & {
178
+ target?: unknown;
179
+ };
180
+ /** Who sends a session's tool calls: any MCP client, or an ACP or Pi harness chat in the app. */
181
+ declare const MCP_AGENT_KINDS: readonly ["mcp", "acp", "harness"];
182
+ type MCPAgentKind = (typeof MCP_AGENT_KINDS)[number];
183
+ /** The session tool calls come from, so the app can show the client as an agent at work. */
184
+ interface MCPAgentSession {
185
+ id: string;
186
+ kind: MCPAgentKind;
187
+ /** The app chat the session belongs to, from its `x-pairdraw-chat` header. */
188
+ chat?: string;
189
+ }
190
+ interface RegisterToolsOptions {
191
+ policy: ToolPolicy;
192
+ mcpRoot?: string | null;
193
+ sendRPC: RPCSender;
194
+ agentSession?: MCPAgentSession;
195
+ /** Transport lifecycle cleanup after tool execution, including cancellation. */
196
+ onToolSettled?: MCPToolSettled;
197
+ }
198
+ declare function registerTools(mcpServer: McpServer, options: RegisterToolsOptions): void;
199
+ //#endregion
200
+ //#region src/server.d.ts
201
+ declare const MCP_VERSION: string;
202
+ interface ServerOptions {
203
+ /** TCP port for the HTTP + WebSocket server. Ignored when `withTcp` is false. When set to 0 with `withTcp: true`, binds to an ephemeral port. Defaults to 7600. */
204
+ httpPort?: number;
205
+ /** Path to the Unix domain socket. Auto-resolved if omitted. */
206
+ socketPath?: string | null;
207
+ /** Whether to also listen on TCP (in addition to the socket). API default is `false`; the CLI passes `true` by default (derived from PORT, default 7600). */
208
+ withTcp?: boolean;
209
+ enableEval?: boolean;
210
+ /** Tool names omitted from every MCP session. */
211
+ disabledTools?: Iterable<string>;
212
+ /** What clients can reach: the whole document (default) or only the user's selection. */
213
+ scope?: MCPToolScope;
214
+ mcpRoot?: string | null;
215
+ /** Auth token for /mcp and /rpc endpoints. Auto-generated (32-hex) when omitted. Pass null explicitly to disable auth. */
216
+ authToken?: string | null;
217
+ corsOrigin?: string | readonly string[] | null;
218
+ /**
219
+ * If set, the server starts a grace-period timer while no app is attached.
220
+ * The timer closes the server and removes its discovery file unless an app
221
+ * registers before it expires. A later app disconnect starts a new grace
222
+ * period, which lets app-spawned servers survive brief reloads while still
223
+ * cleaning up after renderer or process crashes. Undefined/0 disables the
224
+ * watchdog — the default, since a bare CLI invocation for manual testing
225
+ * should not self-terminate just because nobody connected yet. The desktop
226
+ * app opts in when it spawns the server.
227
+ */
228
+ appAttachTimeoutMs?: number;
229
+ /**
230
+ * How long an MCP session may sit without requests before it is closed.
231
+ * Defaults to 15 minutes; 0 disables expiration. An open GET/SSE stream
232
+ * does not count as activity.
233
+ */
234
+ sessionIdleTimeoutMs?: number;
235
+ /**
236
+ * How long a tool call waits for the app to register before it fails with
237
+ * APP_NOT_CONNECTED. Defaults to 10 s so a stdio bridge started slightly
238
+ * before the desktop app still succeeds; tests shorten it.
239
+ */
240
+ appWaitTimeoutMs?: number;
241
+ /**
242
+ * Turns on the companion's agent bridge (`pairdraw-connect`): pairing with the web app, and
243
+ * finding, installing, signing in to, and starting the coding agents in `ACP_AGENTS` for a
244
+ * paired tab. Off unless set.
245
+ */
246
+ agents?: AgentBridgeOptions;
247
+ }
248
+ interface ServerHandle {
249
+ /** The Hono app (routes) */
250
+ app: Hono;
251
+ /** The primary Node.js HTTP server (socket listener if present, otherwise TCP) */
252
+ server: Server;
253
+ /** Resolved socket path (null if not listening on socket) */
254
+ socketPath: string | null;
255
+ /** TCP port the server is listening on (0 if TCP is disabled) */
256
+ httpPort: number;
257
+ /** Shut down the server: close listeners, remove socket and discovery files */
258
+ close: () => Promise<void>;
259
+ /** Issues a one-time pairing code, when the agent bridge is on; otherwise null. */
260
+ issuePairingCode: (() => string) | null;
261
+ }
262
+ declare function startServer(options?: ServerOptions): Promise<ServerHandle>;
263
+ //#endregion
264
+ export { type MCPAgentKind, type MCPAgentSession, type MCPContent, type MCPResult, MCP_AGENT_KINDS, MCP_VERSION, type RPCSender, type RegisterToolsOptions, ServerHandle, ServerOptions, fail, ok, registerTools, startServer };
265
+ //# sourceMappingURL=server.d.mts.map
@@ -0,0 +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--T-KD99G.mjs";
2
+ export { MCP_AGENT_KINDS, MCP_VERSION, fail, ok, registerTools, startServer };
@@ -0,0 +1 @@
1
+ import "./rolldown-runtime-ClRpJifh.mjs";
package/dist/stdio.mjs ADDED
@@ -0,0 +1,411 @@
1
+ #!/usr/bin/env node
2
+ import "./rolldown-runtime-ClRpJifh.mjs";
3
+ import { a as createServerInstructions, c as registerSkill, s as registerTools, t as MCP_VERSION } from "./server--T-KD99G.mjs";
4
+ import { a as getSocketPath, o as platformHasUnixSockets } from "./paths-BpcXnrbP.mjs";
5
+ import { t as resolveMCPRoot } from "./root-BzmoiT2g.mjs";
6
+ import { r as parseDisabledTools } from "./policy-B8Ka4WRH.mjs";
7
+ import { a as narrowestScope, o as parseToolScope } from "./scope-D2LTTsDw.mjs";
8
+ import { n as readDiscoveryFile } from "./discovery-CB2Bv5WA.mjs";
9
+ import { randomUUID } from "node:crypto";
10
+ import { McpServer } from "@modelcontextprotocol/server";
11
+ import { request } from "node:http";
12
+ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
13
+ //#region src/stdio/bridge.ts
14
+ const RPC_TIMEOUT = 35e3;
15
+ const DISCONNECTED_MESSAGE = "Pairdraw app is not connected. STOP and tell the user: \"The Pairdraw desktop app is not running or no document is open. Please start the app and open a document, then try again.\" Do NOT attempt to start the app yourself or retry automatically.";
16
+ /**
17
+ * Creates an RPC bridge that connects to the MCP server via HTTP
18
+ * over a Unix domain socket.
19
+ *
20
+ * This replaces the previous WebSocket-based bridge with a simpler
21
+ * HTTP approach that natively supports Unix domain sockets.
22
+ */
23
+ function createStdioRPCBridge({ socketPath: socketPathOverride, authToken, reconnectDelayMs = 2e3, onReady, onReconnect }) {
24
+ let resolvedSocketPath = socketPathOverride ?? null;
25
+ let resolvedHttpPort = null;
26
+ let transportMode = null;
27
+ let ready = false;
28
+ let wasConnected = false;
29
+ let reconnectTimer;
30
+ let connectPromise = null;
31
+ let closed = false;
32
+ let authFailure = false;
33
+ let socketFailed = false;
34
+ const hasExplicitSocketPath = socketPathOverride !== void 0 && socketPathOverride !== null;
35
+ const hasExplicitAuth = authToken !== void 0;
36
+ let resolvedAuthToken = authToken ?? null;
37
+ async function resolveAuthToken() {
38
+ if (hasExplicitAuth) return resolvedAuthToken;
39
+ if (resolvedAuthToken) return resolvedAuthToken;
40
+ const info = await readDiscoveryFile();
41
+ if (info?.authToken) resolvedAuthToken = info.authToken;
42
+ return resolvedAuthToken;
43
+ }
44
+ async function resolveTransport() {
45
+ if (transportMode) return;
46
+ const info = await readDiscoveryFile();
47
+ if (!hasExplicitAuth && info?.authToken) resolvedAuthToken = info.authToken;
48
+ if (!platformHasUnixSockets()) {
49
+ if (info?.httpPort) {
50
+ resolvedHttpPort = info.httpPort;
51
+ transportMode = "tcp";
52
+ return;
53
+ }
54
+ throw new Error("No MCP server discovery info found");
55
+ }
56
+ if (hasExplicitSocketPath && resolvedSocketPath) {} else if (info?.socketPath) resolvedSocketPath = info.socketPath;
57
+ else if (info?.httpPort) {
58
+ resolvedHttpPort = info.httpPort;
59
+ transportMode = "tcp";
60
+ return;
61
+ } else resolvedSocketPath = await getSocketPath();
62
+ if (info?.httpPort) resolvedHttpPort = info.httpPort;
63
+ if (!hasExplicitSocketPath && socketFailed && resolvedHttpPort) {
64
+ transportMode = "tcp";
65
+ return;
66
+ }
67
+ transportMode = "socket";
68
+ }
69
+ /**
70
+ * Makes an HTTP request to the MCP server via socket or TCP.
71
+ */
72
+ function httpRequest(method, path, body) {
73
+ return new Promise((resolve, reject) => {
74
+ const bodyJSON = body ? JSON.stringify(body) : void 0;
75
+ const headers = {};
76
+ if (bodyJSON) headers["Content-Type"] = "application/json";
77
+ if (resolvedAuthToken) headers.Authorization = `Bearer ${resolvedAuthToken}`;
78
+ let reqOpts = null;
79
+ if (transportMode === "socket" && resolvedSocketPath) reqOpts = {
80
+ socketPath: resolvedSocketPath,
81
+ path,
82
+ method,
83
+ headers
84
+ };
85
+ else if (transportMode === "tcp" && resolvedHttpPort) reqOpts = {
86
+ hostname: "127.0.0.1",
87
+ port: resolvedHttpPort,
88
+ path,
89
+ method,
90
+ headers
91
+ };
92
+ if (!reqOpts) {
93
+ reject(/* @__PURE__ */ new Error(DISCONNECTED_MESSAGE));
94
+ return;
95
+ }
96
+ const req = request(reqOpts, (res) => {
97
+ const chunks = [];
98
+ res.on("data", (chunk) => chunks.push(chunk));
99
+ res.on("end", () => {
100
+ const raw = Buffer.concat(chunks).toString("utf-8");
101
+ let data;
102
+ try {
103
+ data = JSON.parse(raw);
104
+ } catch {
105
+ data = raw;
106
+ }
107
+ resolve({
108
+ status: res.statusCode ?? 200,
109
+ data,
110
+ req
111
+ });
112
+ });
113
+ res.on("error", reject);
114
+ });
115
+ req.on("error", reject);
116
+ req.setTimeout(3e4, () => {
117
+ req.destroy(/* @__PURE__ */ new Error("Socket timeout"));
118
+ });
119
+ if (bodyJSON) req.write(bodyJSON);
120
+ req.end();
121
+ });
122
+ }
123
+ /**
124
+ * Checks if the server is healthy and the browser is connected.
125
+ */
126
+ async function checkHealth() {
127
+ try {
128
+ const { status, data } = await httpRequest("GET", "/health");
129
+ if (status === 401) return {
130
+ reachable: true,
131
+ appConnected: false,
132
+ authFailed: true
133
+ };
134
+ if (status !== 200) return {
135
+ reachable: false,
136
+ appConnected: false,
137
+ authFailed: false
138
+ };
139
+ const health = data;
140
+ return {
141
+ reachable: health.status === "ok" || health.status === "no_app",
142
+ appConnected: health.status === "ok",
143
+ authFailed: false
144
+ };
145
+ } catch {
146
+ if (!hasExplicitSocketPath && transportMode === "socket") socketFailed = true;
147
+ return {
148
+ reachable: false,
149
+ appConnected: false,
150
+ authFailed: false
151
+ };
152
+ }
153
+ }
154
+ /**
155
+ * Attempts to connect to the server. Retries with a fixed delay.
156
+ */
157
+ async function connect() {
158
+ if (closed) return;
159
+ try {
160
+ await resolveTransport();
161
+ if (!resolvedAuthToken) await resolveAuthToken();
162
+ } catch {
163
+ connectPromise = null;
164
+ scheduleReconnect();
165
+ return;
166
+ }
167
+ if (closed) return;
168
+ const { reachable, appConnected, authFailed } = await checkHealth();
169
+ if (closed) return;
170
+ if (authFailed) {
171
+ authFailure = true;
172
+ ready = false;
173
+ connectPromise = null;
174
+ if (!hasExplicitAuth) {
175
+ resolvedAuthToken = null;
176
+ transportMode = null;
177
+ }
178
+ scheduleReconnect();
179
+ return;
180
+ }
181
+ authFailure = false;
182
+ if (appConnected) {
183
+ ready = true;
184
+ socketFailed = false;
185
+ connectPromise = null;
186
+ if (wasConnected) onReconnect?.();
187
+ else {
188
+ wasConnected = true;
189
+ onReady?.();
190
+ }
191
+ return;
192
+ }
193
+ if (reachable) {
194
+ ready = true;
195
+ socketFailed = false;
196
+ connectPromise = null;
197
+ if (!wasConnected) {
198
+ wasConnected = true;
199
+ onReady?.();
200
+ }
201
+ return;
202
+ }
203
+ transportMode = null;
204
+ if (!hasExplicitSocketPath) resolvedSocketPath = null;
205
+ resolvedHttpPort = null;
206
+ connectPromise = null;
207
+ scheduleReconnect();
208
+ }
209
+ function scheduleReconnect() {
210
+ if (closed) return;
211
+ clearTimeout(reconnectTimer);
212
+ reconnectTimer = setTimeout(() => {
213
+ connectPromise = connect();
214
+ }, reconnectDelayMs);
215
+ reconnectTimer.unref();
216
+ }
217
+ /**
218
+ * Sends an RPC request to the MCP server.
219
+ *
220
+ * Routes through the /rpc HTTP endpoint, which proxies
221
+ * the call to the connected browser.
222
+ *
223
+ * When using an auto-discovered auth token (hasExplicitAuth === false),
224
+ * a 401 response triggers a transparent retry: the cached token is cleared,
225
+ * the discovery file is re-read for a fresh token, and the request is
226
+ * retried once. Only if the retry also fails is the error surfaced to the
227
+ * caller. This makes server restarts with a new auto-generated token
228
+ * seamless to the AI agent.
229
+ */
230
+ function sendRPC(body) {
231
+ const awaitReady = async () => {
232
+ if (!ready && connectPromise) await connectPromise;
233
+ if (authFailure) throw new Error("Unauthorized: check PAIRDRAW_MCP_AUTH_TOKEN");
234
+ if (!ready) throw new Error(DISCONNECTED_MESSAGE);
235
+ };
236
+ return awaitReady().then(() => new Promise((resolve, reject) => {
237
+ let settled = false;
238
+ const timer = setTimeout(() => {
239
+ if (settled) return;
240
+ settled = true;
241
+ reject(/* @__PURE__ */ new Error(`RPC timeout (${Math.round(RPC_TIMEOUT / 1e3)}s)`));
242
+ }, RPC_TIMEOUT);
243
+ /**
244
+ * Performs one HTTP request attempt. `allowAuthRetry` controls whether
245
+ * a 401 with an auto-discovered token triggers a re-read and retry.
246
+ * It is set to `false` for the second attempt to prevent infinite loops.
247
+ */
248
+ function attempt(allowAuthRetry) {
249
+ httpRequest("POST", "/rpc", body).then(({ status, data, req }) => {
250
+ if (settled) {
251
+ req.destroy();
252
+ return;
253
+ }
254
+ if (status === 401) {
255
+ if (allowAuthRetry && !hasExplicitAuth) {
256
+ resolvedAuthToken = null;
257
+ readDiscoveryFile().then((info) => {
258
+ if (settled) return void 0;
259
+ if (info?.authToken) {
260
+ resolvedAuthToken = info.authToken;
261
+ attempt(false);
262
+ return;
263
+ }
264
+ clearTimeout(timer);
265
+ authFailure = true;
266
+ transportMode = null;
267
+ if (!hasExplicitSocketPath) resolvedSocketPath = null;
268
+ resolvedHttpPort = null;
269
+ ready = false;
270
+ settled = true;
271
+ scheduleReconnect();
272
+ reject(/* @__PURE__ */ new Error("Unauthorized"));
273
+ }).catch(() => {
274
+ if (settled) return;
275
+ clearTimeout(timer);
276
+ transportMode = null;
277
+ if (!hasExplicitSocketPath) resolvedSocketPath = null;
278
+ resolvedHttpPort = null;
279
+ ready = false;
280
+ settled = true;
281
+ scheduleReconnect();
282
+ reject(/* @__PURE__ */ new Error(DISCONNECTED_MESSAGE));
283
+ });
284
+ return;
285
+ }
286
+ clearTimeout(timer);
287
+ authFailure = true;
288
+ if (!hasExplicitAuth) resolvedAuthToken = null;
289
+ transportMode = null;
290
+ if (!hasExplicitSocketPath) resolvedSocketPath = null;
291
+ resolvedHttpPort = null;
292
+ ready = false;
293
+ settled = true;
294
+ scheduleReconnect();
295
+ reject(/* @__PURE__ */ new Error("Unauthorized: check PAIRDRAW_MCP_AUTH_TOKEN"));
296
+ return;
297
+ }
298
+ clearTimeout(timer);
299
+ if (status >= 400) {
300
+ const errData = data;
301
+ settled = true;
302
+ reject(new Error(errData.error ?? `RPC failed with status ${status}`));
303
+ return;
304
+ }
305
+ settled = true;
306
+ resolve(data);
307
+ }).catch(() => {
308
+ if (settled) return;
309
+ clearTimeout(timer);
310
+ if (!hasExplicitSocketPath && transportMode === "socket") socketFailed = true;
311
+ transportMode = null;
312
+ if (!hasExplicitSocketPath) resolvedSocketPath = null;
313
+ resolvedHttpPort = null;
314
+ ready = false;
315
+ settled = true;
316
+ scheduleReconnect();
317
+ reject(/* @__PURE__ */ new Error(DISCONNECTED_MESSAGE));
318
+ });
319
+ }
320
+ attempt(true);
321
+ }));
322
+ }
323
+ /**
324
+ * Stops the reconnect timer and marks the bridge as not ready.
325
+ * Call this to cleanly shut down the bridge and prevent timer leaks.
326
+ */
327
+ function close() {
328
+ closed = true;
329
+ clearTimeout(reconnectTimer);
330
+ reconnectTimer = void 0;
331
+ ready = false;
332
+ connectPromise = null;
333
+ }
334
+ connectPromise = connect();
335
+ return {
336
+ sendRPC,
337
+ close
338
+ };
339
+ }
340
+ //#endregion
341
+ //#region src/stdio.ts
342
+ if (process.argv.includes("--version")) {
343
+ process.stdout.write(`${MCP_VERSION}\n`);
344
+ process.exit(0);
345
+ }
346
+ if (process.argv.includes("--help") || process.argv.includes("-h")) {
347
+ process.stdout.write("pairdraw-mcp\n\nStart the Pairdraw MCP stdio bridge.\n\nConnects to the MCP server via Unix domain socket on macOS/Linux (with TCP fallback) or via TCP on Windows.\nThe MCP server is started by the Pairdraw\ndesktop app; this bridge only forwards stdio JSON-RPC to it.\n\nOptions:\n --help, -h Show this help message\n --version Print the version\n\nEnvironment variables:\n PAIRDRAW_MCP_SOCKET Override socket path (auto-discovered from discovery file when unset)\n PAIRDRAW_MCP_AUTH_TOKEN Bearer token for RPC auth\n PAIRDRAW_MCP_ROOT Allowed directory for file-scoped tools\n (default: home directory on Windows, cwd elsewhere)\n PAIRDRAW_MCP_EVAL Set to 1 to enable the eval tool\n PAIRDRAW_MCP_DISABLED_TOOLS Comma-separated tool names to omit; defaults to the app setting\n PAIRDRAW_MCP_SCOPE \"selection\" to read only the selected layers; defaults to the app setting\n");
348
+ process.exit(0);
349
+ }
350
+ const discovery = await readDiscoveryFile();
351
+ const toolPolicy = {
352
+ allowEval: process.env.PAIRDRAW_MCP_EVAL === "1",
353
+ disabledTools: process.env.PAIRDRAW_MCP_DISABLED_TOOLS === void 0 ? discovery?.disabledTools ?? [] : parseDisabledTools(process.env.PAIRDRAW_MCP_DISABLED_TOOLS),
354
+ scope: narrowestScope(discovery?.scope ?? "document", parseToolScope(process.env.PAIRDRAW_MCP_SCOPE))
355
+ };
356
+ const mcpRoot = resolveMCPRoot(process.env.PAIRDRAW_MCP_ROOT);
357
+ const rawAuthToken = process.env.PAIRDRAW_MCP_AUTH_TOKEN;
358
+ if (rawAuthToken !== void 0 && rawAuthToken !== "" && rawAuthToken.trim() === "") {
359
+ process.stderr.write("Error: PAIRDRAW_MCP_AUTH_TOKEN is whitespace-only. Set a real token, or use an empty string to disable auth.\n");
360
+ process.exit(1);
361
+ }
362
+ function resolveAuthToken(raw) {
363
+ if (raw === void 0) return void 0;
364
+ if (raw === "") return null;
365
+ return raw.trim();
366
+ }
367
+ const bridge = createStdioRPCBridge({
368
+ authToken: resolveAuthToken(rawAuthToken),
369
+ onReady: () => {
370
+ process.stderr.write("Connected to Pairdraw MCP server; document availability is checked per tool call\n");
371
+ },
372
+ onReconnect: () => {
373
+ process.stderr.write("Reconnected to Pairdraw MCP server; document availability is checked per tool call\n");
374
+ }
375
+ });
376
+ const mcpServer = new McpServer({
377
+ name: "pairdraw",
378
+ version: MCP_VERSION
379
+ }, { instructions: createServerInstructions({
380
+ policy: toolPolicy,
381
+ filesystemEnabled: Boolean(mcpRoot),
382
+ agentKind: "mcp"
383
+ }) });
384
+ registerTools(mcpServer, {
385
+ policy: toolPolicy,
386
+ mcpRoot,
387
+ sendRPC: bridge.sendRPC,
388
+ agentSession: {
389
+ id: randomUUID(),
390
+ kind: "mcp"
391
+ }
392
+ });
393
+ registerSkill(mcpServer);
394
+ const transport = new StdioServerTransport();
395
+ mcpServer.connect(transport).catch((err) => {
396
+ process.stderr.write(`Fatal: MCP connect failed — ${err instanceof Error ? err.message : err}\n`);
397
+ process.exit(1);
398
+ });
399
+ process.on("uncaughtException", (err) => {
400
+ process.stderr.write(`Fatal: ${err instanceof Error ? err.message : err}\n`);
401
+ process.exit(1);
402
+ });
403
+ process.on("unhandledRejection", (reason) => {
404
+ const message = reason instanceof Error ? reason.message : String(reason);
405
+ process.stderr.write(`Fatal: unhandled rejection — ${message}\n`);
406
+ process.exit(1);
407
+ });
408
+ //#endregion
409
+ export {};
410
+
411
+ //# sourceMappingURL=stdio.mjs.map