@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.
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-BdiJUhSs.mjs +3261 -0
  25. package/dist/server-BdiJUhSs.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 +78 -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,69 @@
1
+ import { compact } from 'es-toolkit/array'
2
+
3
+ import { SKILL_NAME, skillResourceURI } from '#mcp/skill/content'
4
+ import { createToolDescriptors } from '#mcp/tool/manifest'
5
+ import type { ToolPolicy } from '#mcp/tool/metadata'
6
+ import { isToolEnabled } from '#mcp/tool/policy'
7
+ import type { MCPAgentKind } from '#mcp/tool/registration'
8
+
9
+ export interface ServerInstructionsOptions {
10
+ policy: ToolPolicy
11
+ /** Whether an MCP root exposes the file tools, as `registerTools` decides. */
12
+ filesystemEnabled: boolean
13
+ /** Who the session serves: an external client, or an app chat whose prompt already has the reference. */
14
+ agentKind: MCPAgentKind
15
+ }
16
+
17
+ const SKILL_FILE_URI = skillResourceURI('SKILL.md')
18
+ const REFERENCE_PATH = 'references/design-authoring.md'
19
+ const REFERENCE_URI = skillResourceURI(REFERENCE_PATH)
20
+
21
+ function skillParagraph(enabled: (name: string) => boolean): string {
22
+ const designs = enabled('render')
23
+ const lead = designs ? 'Before you design' : 'Before you use these tools'
24
+ if (!enabled('read_skill')) {
25
+ return `${lead}, read the ${SKILL_NAME} skill from the resources ${SKILL_FILE_URI} and ${REFERENCE_URI}.`
26
+ }
27
+ const reference = designs ? ' before you use render' : ''
28
+ return `${lead}, read the ${SKILL_NAME} skill: call read_skill for SKILL.md, then read_skill with path "${REFERENCE_PATH}"${reference}. Clients without that tool can read the same files as the resources ${SKILL_FILE_URI} and ${REFERENCE_URI}.`
29
+ }
30
+
31
+ function usageParagraph(enabled: (name: string) => boolean, policy: ToolPolicy): string {
32
+ const undo = enabled('undo')
33
+ return compact([
34
+ enabled('list_documents') &&
35
+ 'When several documents may be open, call list_documents first and pass its document_id and page_id to later calls.',
36
+ policy.scope === 'document' &&
37
+ enabled('export_image') &&
38
+ 'Check visual changes with export_image.',
39
+ undo && `${enabled('redo') ? 'undo and redo step' : 'undo steps'} back only your own changes.`,
40
+ enabled('get_codegen_prompt') &&
41
+ 'Call get_codegen_prompt before turning a design into frontend code.'
42
+ ]).join(' ')
43
+ }
44
+
45
+ /**
46
+ * What the server tells a client when it connects, naming only the tools its policy and scope
47
+ * expose. Clients such as Codex show only the start of it, so the first paragraphs stand on their
48
+ * own and stay under 512 characters. App chats get no skill paragraph: their system prompt already
49
+ * carries the design authoring reference.
50
+ */
51
+ export function createServerInstructions({
52
+ policy,
53
+ filesystemEnabled,
54
+ agentKind
55
+ }: ServerInstructionsOptions): string {
56
+ const exposed = new Set(
57
+ createToolDescriptors(filesystemEnabled)
58
+ .filter((descriptor) => isToolEnabled(descriptor, policy))
59
+ .map((descriptor) => descriptor.name)
60
+ )
61
+ const enabled = (name: string) => exposed.has(name)
62
+ return compact([
63
+ policy.scope === 'selection'
64
+ ? 'Pairdraw is a design editor. These tools read only the layers selected in its running app and cannot change the document.'
65
+ : 'Pairdraw is a design editor. These tools read and edit the documents open in its running app.',
66
+ agentKind === 'mcp' && skillParagraph(enabled),
67
+ usageParagraph(enabled, policy)
68
+ ]).join('\n\n')
69
+ }
@@ -0,0 +1,77 @@
1
+ import type { McpServer, PromptMessage } from '@modelcontextprotocol/server'
2
+ // eslint-disable-next-line pairdraw/no-mixed-case-acronym-identifiers -- Upstream export spelling.
3
+ import { toStandardJsonSchema as toStandardJSONSchema } from '@valibot/to-json-schema'
4
+ import * as v from 'valibot'
5
+
6
+ import {
7
+ SKILL_FILE_PATHS,
8
+ SKILL_FILES,
9
+ SKILL_NAME,
10
+ skillResourceURI,
11
+ type SkillFile
12
+ } from '#mcp/skill/content'
13
+
14
+ const SKILL_MIME_TYPE = 'text/markdown'
15
+
16
+ /** The prompt that loads the skill into a conversation, as a slash command in most clients. */
17
+ export const SKILL_PROMPT_NAME = 'design'
18
+
19
+ const skillPromptArgsSchema = v.object({
20
+ task: v.optional(
21
+ v.pipe(v.string(), v.description('What to design or change, such as "a pricing page"'))
22
+ )
23
+ })
24
+
25
+ function fileMessage(file: SkillFile): PromptMessage {
26
+ return {
27
+ role: 'user',
28
+ content: { type: 'text', text: `<!-- ${SKILL_NAME}/${file.path} -->\n\n${file.text}` }
29
+ }
30
+ }
31
+
32
+ function taskMessage(task: string | undefined): PromptMessage {
33
+ const request = task?.trim()
34
+ return {
35
+ role: 'user',
36
+ content: {
37
+ type: 'text',
38
+ text: request
39
+ ? `Follow the Pairdraw skill above and use the pairdraw tools for this task: ${request}`
40
+ : 'Follow the Pairdraw skill above whenever you use the pairdraw tools in this conversation.'
41
+ }
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Serves the agent skill to clients that cannot install skills: each file as a resource, and all
47
+ * of them as the `design` prompt. These carry no document data, so tool policy and selection
48
+ * scope leave them on; `read_skill` is the tool form for clients without resources or prompts.
49
+ */
50
+ export function registerSkill(mcpServer: McpServer): void {
51
+ for (const path of SKILL_FILE_PATHS) {
52
+ const file = SKILL_FILES[path]
53
+ mcpServer.registerResource(
54
+ `${SKILL_NAME}/${path}`,
55
+ skillResourceURI(path),
56
+ { title: file.title, description: file.description, mimeType: SKILL_MIME_TYPE },
57
+ (uri) => ({ contents: [{ uri: uri.href, mimeType: SKILL_MIME_TYPE, text: file.text }] })
58
+ )
59
+ }
60
+
61
+ mcpServer.registerPrompt(
62
+ SKILL_PROMPT_NAME,
63
+ {
64
+ title: 'Design with Pairdraw',
65
+ description:
66
+ 'Load the Pairdraw skill and design authoring reference, optionally with a design task.',
67
+ argsSchema: toStandardJSONSchema(skillPromptArgsSchema)
68
+ },
69
+ ({ task }) => ({
70
+ description: SKILL_FILES['SKILL.md'].description,
71
+ messages: [
72
+ ...SKILL_FILE_PATHS.map((path) => fileMessage(SKILL_FILES[path])),
73
+ taskMessage(task)
74
+ ]
75
+ })
76
+ )
77
+ }
@@ -0,0 +1,460 @@
1
+ import { request } from 'node:http'
2
+ import type { ClientRequest, RequestOptions } from 'node:http'
3
+
4
+ import { readDiscoveryFile } from '#mcp/transport/discovery'
5
+ import { getSocketPath, platformHasUnixSockets } from '#mcp/transport/paths'
6
+
7
+ type StdioRPCBridgeOptions = {
8
+ /** Override socket path (if known). Auto-discovered if omitted. */
9
+ socketPath?: string | null
10
+ /** Auth token for /rpc Bearer header. */
11
+ authToken?: string | null
12
+ reconnectDelayMs?: number
13
+ onReady?: () => void
14
+ onReconnect?: () => void
15
+ }
16
+
17
+ // 35s gives a 5s margin over the worst case (10s app wait + 20s RPC timeout = 30s)
18
+ const RPC_TIMEOUT = 35_000
19
+ const DISCONNECTED_MESSAGE =
20
+ 'Pairdraw app is not connected. ' +
21
+ 'STOP and tell the user: "The Pairdraw desktop app is not running or no document is open. ' +
22
+ 'Please start the app and open a document, then try again." ' +
23
+ 'Do NOT attempt to start the app yourself or retry automatically.'
24
+
25
+ type TransportMode = 'socket' | 'tcp'
26
+
27
+ /**
28
+ * Creates an RPC bridge that connects to the MCP server via HTTP
29
+ * over a Unix domain socket.
30
+ *
31
+ * This replaces the previous WebSocket-based bridge with a simpler
32
+ * HTTP approach that natively supports Unix domain sockets.
33
+ */
34
+ export function createStdioRPCBridge({
35
+ socketPath: socketPathOverride,
36
+ authToken,
37
+ reconnectDelayMs = 2000,
38
+ onReady,
39
+ onReconnect
40
+ }: StdioRPCBridgeOptions) {
41
+ let resolvedSocketPath: string | null = socketPathOverride ?? null
42
+ let resolvedHttpPort: number | null = null
43
+ let transportMode: TransportMode | null = null
44
+ let ready = false
45
+ let wasConnected = false
46
+ let reconnectTimer: ReturnType<typeof setTimeout> | undefined
47
+ let connectPromise: Promise<void> | null = null
48
+ let closed = false
49
+ let authFailure = false
50
+ let socketFailed = false
51
+
52
+ // Socket path resolution has two tiers:
53
+ // Explicit: socketPathOverride parameter — authoritative pin, never
54
+ // overwritten by discovery during reconnect.
55
+ // Hint: PAIRDRAW_MCP_SOCKET env var — resolved through
56
+ // getSocketPath() and readDiscoveryFile(); NOT treated as
57
+ // explicit, so the bridge can pick up a changed path from the
58
+ // discovery file after a server restart.
59
+ const hasExplicitSocketPath = socketPathOverride !== undefined && socketPathOverride !== null
60
+ // Track whether authToken was explicitly provided by the caller.
61
+ // When false, the token is auto-discovered from the discovery file and
62
+ // can be refreshed transparently on 401 without surfacing the error.
63
+ const hasExplicitAuth = authToken !== undefined
64
+ let resolvedAuthToken: string | null = authToken ?? null
65
+
66
+ async function resolveAuthToken(): Promise<string | null> {
67
+ if (hasExplicitAuth) return resolvedAuthToken
68
+ if (resolvedAuthToken) return resolvedAuthToken
69
+ const info = await readDiscoveryFile()
70
+ if (info?.authToken) {
71
+ resolvedAuthToken = info.authToken
72
+ }
73
+ return resolvedAuthToken
74
+ }
75
+
76
+ async function resolveTransport(): Promise<void> {
77
+ // Already resolved
78
+ if (transportMode) return
79
+
80
+ // Try reading the discovery file
81
+ const info = await readDiscoveryFile()
82
+
83
+ // When the auth token was not explicitly provided, pick it up from the
84
+ // discovery file whenever we re-read transport info. This ensures the
85
+ // bridge picks up a new server-generated token after a restart without
86
+ // waiting for a 401 response.
87
+ if (!hasExplicitAuth && info?.authToken) {
88
+ resolvedAuthToken = info.authToken
89
+ }
90
+
91
+ // When no Unix socket is available, prefer TCP via httpPort
92
+ if (!platformHasUnixSockets()) {
93
+ if (info?.httpPort) {
94
+ resolvedHttpPort = info.httpPort
95
+ transportMode = 'tcp'
96
+ return
97
+ }
98
+ throw new Error('No MCP server discovery info found')
99
+ }
100
+
101
+ // Unix: prefer socket path from discovery file, fall back to default.
102
+ // If no socket is available (TCP-only server), use TCP via httpPort.
103
+ // The socketPath option (when provided directly by the caller) takes
104
+ // precedence and is never overwritten by discovery.
105
+ if (hasExplicitSocketPath && resolvedSocketPath) {
106
+ // Caller explicitly provided a socket path — keep it, never overwrite
107
+ } else if (info?.socketPath) {
108
+ resolvedSocketPath = info.socketPath
109
+ } else if (info?.httpPort) {
110
+ // Server is TCP-only (no socket listener) — use TCP
111
+ resolvedHttpPort = info.httpPort
112
+ transportMode = 'tcp'
113
+ return
114
+ } else {
115
+ resolvedSocketPath = await getSocketPath()
116
+ }
117
+
118
+ // Also capture httpPort as fallback
119
+ if (info?.httpPort) {
120
+ resolvedHttpPort = info.httpPort
121
+ }
122
+
123
+ // If the socket previously failed and TCP is available, use TCP
124
+ // instead of retrying the same stale socket indefinitely.
125
+ if (!hasExplicitSocketPath && socketFailed && resolvedHttpPort) {
126
+ transportMode = 'tcp'
127
+ return
128
+ }
129
+
130
+ transportMode = 'socket'
131
+ }
132
+
133
+ /**
134
+ * Makes an HTTP request to the MCP server via socket or TCP.
135
+ */
136
+ function httpRequest(
137
+ method: string,
138
+ path: string,
139
+ body?: Record<string, unknown>
140
+ ): Promise<{ status: number; data: unknown; req: ClientRequest }> {
141
+ return new Promise((resolve, reject) => {
142
+ const bodyJSON = body ? JSON.stringify(body) : undefined
143
+ const headers: Record<string, string> = {}
144
+ if (bodyJSON) headers['Content-Type'] = 'application/json'
145
+ if (resolvedAuthToken) headers.Authorization = `Bearer ${resolvedAuthToken}`
146
+
147
+ let reqOpts: RequestOptions | null = null
148
+ if (transportMode === 'socket' && resolvedSocketPath) {
149
+ reqOpts = { socketPath: resolvedSocketPath, path, method, headers }
150
+ } else if (transportMode === 'tcp' && resolvedHttpPort) {
151
+ reqOpts = { hostname: '127.0.0.1', port: resolvedHttpPort, path, method, headers }
152
+ }
153
+
154
+ if (!reqOpts) {
155
+ reject(new Error(DISCONNECTED_MESSAGE))
156
+ return
157
+ }
158
+
159
+ const req = request(reqOpts, (res) => {
160
+ const chunks: Buffer[] = []
161
+ res.on('data', (chunk: Buffer) => chunks.push(chunk))
162
+ res.on('end', () => {
163
+ const raw = Buffer.concat(chunks).toString('utf-8')
164
+ let data: unknown
165
+ try {
166
+ data = JSON.parse(raw)
167
+ } catch {
168
+ data = raw
169
+ }
170
+ resolve({ status: res.statusCode ?? 200, data, req })
171
+ })
172
+ res.on('error', reject)
173
+ })
174
+
175
+ req.on('error', reject)
176
+ // Socket-level idle timeout to prevent indefinite hangs on
177
+ // unresponsive connections. Set 5s shorter than the outer RPC_TIMEOUT
178
+ // so this fires deterministically first, producing a clear "server
179
+ // unreachable" signal rather than racing with the outer timer.
180
+ // If the outer sendRPC timer already rejected, the error handler
181
+ // is a no-op (settled guard in attempt()).
182
+ req.setTimeout(RPC_TIMEOUT - 5_000, () => {
183
+ req.destroy(new Error('Socket timeout'))
184
+ })
185
+ if (bodyJSON) req.write(bodyJSON)
186
+ req.end()
187
+ })
188
+ }
189
+
190
+ /**
191
+ * Checks if the server is healthy and the browser is connected.
192
+ */
193
+ async function checkHealth(): Promise<{
194
+ reachable: boolean
195
+ appConnected: boolean
196
+ authFailed: boolean
197
+ }> {
198
+ try {
199
+ const { status, data } = await httpRequest('GET', '/health')
200
+ if (status === 401) return { reachable: true, appConnected: false, authFailed: true }
201
+ if (status !== 200) return { reachable: false, appConnected: false, authFailed: false }
202
+ const health = data as { status?: string }
203
+ return {
204
+ reachable: health.status === 'ok' || health.status === 'no_app',
205
+ appConnected: health.status === 'ok',
206
+ authFailed: false
207
+ }
208
+ } catch {
209
+ if (!hasExplicitSocketPath && transportMode === 'socket') socketFailed = true
210
+ return { reachable: false, appConnected: false, authFailed: false }
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Attempts to connect to the server. Retries with a fixed delay.
216
+ */
217
+ async function connect(): Promise<void> {
218
+ if (closed) return
219
+ try {
220
+ await resolveTransport()
221
+ if (!resolvedAuthToken) await resolveAuthToken()
222
+ } catch {
223
+ connectPromise = null
224
+ scheduleReconnect()
225
+ return
226
+ }
227
+
228
+ // close() may have been called while we were resolving transport.
229
+ // oxlint-disable-next-line no-unnecessary-condition
230
+ if (closed) return
231
+
232
+ const { reachable, appConnected, authFailed } = await checkHealth()
233
+ // oxlint-disable-next-line no-unnecessary-condition
234
+ if (closed) return
235
+ if (authFailed) {
236
+ // Auth token is wrong — surface as an auth error rather than a generic
237
+ // disconnect so the caller can prompt for a new token or re-read discovery.
238
+ authFailure = true
239
+ ready = false
240
+ connectPromise = null
241
+ // When using an auto-discovered token, clear it and transportMode so
242
+ // the next reconnect re-reads the discovery file for a fresh token
243
+ // instead of reusing the stale one (which would cause another 401 loop).
244
+ if (!hasExplicitAuth) {
245
+ resolvedAuthToken = null
246
+ transportMode = null
247
+ }
248
+ scheduleReconnect()
249
+ return
250
+ }
251
+ authFailure = false
252
+ if (appConnected) {
253
+ ready = true
254
+ socketFailed = false
255
+ connectPromise = null
256
+ if (wasConnected) {
257
+ onReconnect?.()
258
+ } else {
259
+ wasConnected = true
260
+ onReady?.()
261
+ }
262
+ return
263
+ }
264
+
265
+ if (reachable) {
266
+ // Server is up — we can send RPC requests and let the server
267
+ // wait for the desktop app to connect.
268
+ ready = true
269
+ socketFailed = false
270
+ connectPromise = null
271
+ if (!wasConnected) {
272
+ wasConnected = true
273
+ onReady?.()
274
+ }
275
+ return
276
+ }
277
+
278
+ transportMode = null
279
+ if (!hasExplicitSocketPath) resolvedSocketPath = null
280
+ resolvedHttpPort = null
281
+ connectPromise = null
282
+ scheduleReconnect()
283
+ }
284
+
285
+ function scheduleReconnect() {
286
+ if (closed) return
287
+ clearTimeout(reconnectTimer)
288
+ reconnectTimer = setTimeout(() => {
289
+ connectPromise = connect()
290
+ }, reconnectDelayMs)
291
+ reconnectTimer.unref()
292
+ }
293
+
294
+ /**
295
+ * Sends an RPC request to the MCP server.
296
+ *
297
+ * Routes through the /rpc HTTP endpoint, which proxies
298
+ * the call to the connected browser.
299
+ *
300
+ * When using an auto-discovered auth token (hasExplicitAuth === false),
301
+ * a 401 response triggers a transparent retry: the cached token is cleared,
302
+ * the discovery file is re-read for a fresh token, and the request is
303
+ * retried once. Only if the retry also fails is the error surfaced to the
304
+ * caller. This makes server restarts with a new auto-generated token
305
+ * seamless to the AI agent.
306
+ */
307
+ function sendRPC(body: Record<string, unknown>): Promise<unknown> {
308
+ // If not ready, await the in-flight connect() promise first — the
309
+ // bridge may still be resolving transport. Only reject after that
310
+ // completes and we're still not ready.
311
+ const awaitReady = async (): Promise<void> => {
312
+ if (!ready && connectPromise) await connectPromise
313
+ if (authFailure) throw new Error('Unauthorized: check PAIRDRAW_MCP_AUTH_TOKEN')
314
+ if (!ready) throw new Error(DISCONNECTED_MESSAGE)
315
+ }
316
+
317
+ return awaitReady().then(
318
+ () =>
319
+ new Promise((resolve, reject) => {
320
+ let settled = false
321
+ const timer = setTimeout(() => {
322
+ if (settled) return
323
+ settled = true
324
+ reject(new Error(`RPC timeout (${Math.round(RPC_TIMEOUT / 1000)}s)`))
325
+ }, RPC_TIMEOUT)
326
+
327
+ /**
328
+ * Performs one HTTP request attempt. `allowAuthRetry` controls whether
329
+ * a 401 with an auto-discovered token triggers a re-read and retry.
330
+ * It is set to `false` for the second attempt to prevent infinite loops.
331
+ */
332
+ function attempt(allowAuthRetry: boolean) {
333
+ httpRequest('POST', '/rpc', body)
334
+ .then(({ status, data, req }) => {
335
+ // If the overall RPC timeout fired while the request was in-flight,
336
+ // the server may have already executed the tool. Destroying the
337
+ // request only closes the TCP socket — it does not roll back any
338
+ // server-side mutation. Callers must not assume that a timeout
339
+ // means the operation was not executed.
340
+ if (settled) {
341
+ req.destroy()
342
+ return undefined
343
+ }
344
+
345
+ if (status === 401) {
346
+ if (allowAuthRetry && !hasExplicitAuth) {
347
+ // Auto-discovered token may have rotated — re-read the
348
+ // discovery file for a fresh token and retry transparently.
349
+ // IMPORTANT: Do NOT clear the timer here — the retry must
350
+ // still be protected by the overall 35-second timeout.
351
+ resolvedAuthToken = null
352
+ void readDiscoveryFile()
353
+ .then((info) => {
354
+ if (settled) return undefined
355
+ if (info?.authToken) {
356
+ resolvedAuthToken = info.authToken
357
+ // Keep existing transport mode (socket path / port
358
+ // doesn't change on server restart — only the token
359
+ // does). Retry exactly once with the new token.
360
+ attempt(false)
361
+ return undefined
362
+ }
363
+ clearTimeout(timer)
364
+ authFailure = true
365
+ transportMode = null
366
+ if (!hasExplicitSocketPath) resolvedSocketPath = null
367
+ resolvedHttpPort = null
368
+ ready = false
369
+ settled = true
370
+ scheduleReconnect()
371
+ reject(new Error('Unauthorized'))
372
+ return undefined
373
+ })
374
+ .catch(() => {
375
+ if (settled) return
376
+ clearTimeout(timer)
377
+ // Discovery read failed — stale transport state must be
378
+ // discarded so the bridge re-resolves on reconnect.
379
+ transportMode = null
380
+ if (!hasExplicitSocketPath) resolvedSocketPath = null
381
+ resolvedHttpPort = null
382
+ ready = false
383
+ settled = true
384
+ scheduleReconnect()
385
+ reject(new Error(DISCONNECTED_MESSAGE))
386
+ })
387
+ return undefined
388
+ }
389
+
390
+ // Explicit token was rejected (config error), or auto-retry
391
+ // already failed — surface the error immediately.
392
+ clearTimeout(timer)
393
+ authFailure = true
394
+ if (!hasExplicitAuth) {
395
+ resolvedAuthToken = null
396
+ }
397
+ transportMode = null
398
+ // Clear auto-discovered transport params so resolveTransport()
399
+ // picks up fresh values from the discovery file on reconnect.
400
+ if (!hasExplicitSocketPath) resolvedSocketPath = null
401
+ resolvedHttpPort = null
402
+ ready = false
403
+ settled = true
404
+ scheduleReconnect()
405
+ reject(new Error('Unauthorized: check PAIRDRAW_MCP_AUTH_TOKEN'))
406
+ return undefined
407
+ }
408
+
409
+ clearTimeout(timer)
410
+
411
+ if (status >= 400) {
412
+ const errData = data as { error?: string }
413
+ settled = true
414
+ reject(new Error(errData.error ?? `RPC failed with status ${status}`))
415
+ return undefined
416
+ }
417
+ settled = true
418
+ resolve(data)
419
+ return undefined
420
+ })
421
+ .catch(() => {
422
+ if (settled) return
423
+ clearTimeout(timer)
424
+ if (!hasExplicitSocketPath && transportMode === 'socket') {
425
+ socketFailed = true
426
+ }
427
+ transportMode = null
428
+ // Clear auto-discovered transport params so resolveTransport()
429
+ // picks up fresh values from the discovery file on reconnect.
430
+ if (!hasExplicitSocketPath) resolvedSocketPath = null
431
+ resolvedHttpPort = null
432
+ ready = false
433
+ settled = true
434
+ scheduleReconnect()
435
+ reject(new Error(DISCONNECTED_MESSAGE))
436
+ })
437
+ }
438
+
439
+ attempt(true)
440
+ })
441
+ )
442
+ }
443
+
444
+ /**
445
+ * Stops the reconnect timer and marks the bridge as not ready.
446
+ * Call this to cleanly shut down the bridge and prevent timer leaks.
447
+ */
448
+ function close(): void {
449
+ closed = true
450
+ clearTimeout(reconnectTimer)
451
+ reconnectTimer = undefined
452
+ ready = false
453
+ connectPromise = null
454
+ }
455
+
456
+ // Start connection
457
+ connectPromise = connect()
458
+
459
+ return { sendRPC, close }
460
+ }