@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.
- 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--T-KD99G.mjs +3261 -0
- package/dist/server--T-KD99G.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 +64 -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
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
import * as v from 'valibot'
|
|
4
|
+
import type { WebSocket } from 'ws'
|
|
5
|
+
|
|
6
|
+
import { isAuthorized } from '#mcp/auth'
|
|
7
|
+
import type { RPCJSONObject } from '#mcp/json'
|
|
8
|
+
import type { PendingRequest } from '#mcp/rpc-types'
|
|
9
|
+
|
|
10
|
+
const RPC_TIMEOUT = 20_000
|
|
11
|
+
const APP_WAIT_TIMEOUT = 10_000
|
|
12
|
+
|
|
13
|
+
const APP_NOT_CONNECTED_MESSAGE =
|
|
14
|
+
'Pairdraw app is not connected. STOP and tell the user: "The Pairdraw desktop app is not running, no document is open, or the desktop app is connected to a different MCP server. Please start Pairdraw, open a document, and try again." Do NOT attempt to start the app yourself or retry automatically.'
|
|
15
|
+
|
|
16
|
+
type BrowserRPCBridgeOptions = {
|
|
17
|
+
authToken: string | null
|
|
18
|
+
/** Decides which tokens may register or authenticate; defaults to `authToken` alone. */
|
|
19
|
+
authorize?: (token: string | null) => boolean
|
|
20
|
+
onConnectionChange: () => void
|
|
21
|
+
/** How long an RPC waits for the app to register before failing with APP_NOT_CONNECTED. Defaults to 10 s. */
|
|
22
|
+
appWaitTimeoutMs?: number
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type ConnectionListener = (connected: boolean) => void
|
|
26
|
+
|
|
27
|
+
/** Any JSON object; the per-type schemas below run only once its `type` is known. */
|
|
28
|
+
const browserEnvelopeSchema = v.pipe(
|
|
29
|
+
v.string(),
|
|
30
|
+
v.parseJson(),
|
|
31
|
+
v.custom<Record<string, unknown>>(
|
|
32
|
+
(value) => typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
33
|
+
)
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
const handshakeMessageSchema = v.looseObject({
|
|
37
|
+
token: v.optional(v.nullable(v.string())),
|
|
38
|
+
/** The editor window's label; a register without one is the legacy single-window app. */
|
|
39
|
+
window: v.optional(v.nullable(v.string()))
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
const focusMessageSchema = v.looseObject({ type: v.literal('focus') })
|
|
43
|
+
|
|
44
|
+
const requestMessageSchema = v.looseObject({
|
|
45
|
+
type: v.literal('request'),
|
|
46
|
+
id: v.pipe(v.string(), v.nonEmpty())
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
const responseMessageSchema = v.looseObject({
|
|
50
|
+
type: v.literal('response'),
|
|
51
|
+
id: v.pipe(v.string(), v.nonEmpty()),
|
|
52
|
+
ok: v.optional(v.boolean()),
|
|
53
|
+
error: v.optional(v.string())
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
type BrowserMessage =
|
|
57
|
+
| v.InferOutput<typeof requestMessageSchema>
|
|
58
|
+
| v.InferOutput<typeof responseMessageSchema>
|
|
59
|
+
|
|
60
|
+
function stripEnvelope(msg: BrowserMessage): Record<string, unknown> {
|
|
61
|
+
const { type: _type, id: _id, ...body } = msg
|
|
62
|
+
return body
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function responsePayload(result: unknown): RPCJSONObject {
|
|
66
|
+
if (result && typeof result === 'object' && !Array.isArray(result)) {
|
|
67
|
+
return result as RPCJSONObject
|
|
68
|
+
}
|
|
69
|
+
return { result }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function sendJSON(ws: WebSocket, body: Record<string, unknown>) {
|
|
73
|
+
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(body))
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function createSettler<T>(resolve: (value: T) => void, reject: (error: Error) => void) {
|
|
77
|
+
let settled = false
|
|
78
|
+
return {
|
|
79
|
+
resolve: (value: T) => {
|
|
80
|
+
if (settled) return
|
|
81
|
+
settled = true
|
|
82
|
+
resolve(value)
|
|
83
|
+
},
|
|
84
|
+
reject: (error: Error) => {
|
|
85
|
+
if (settled) return
|
|
86
|
+
settled = true
|
|
87
|
+
reject(error)
|
|
88
|
+
},
|
|
89
|
+
isSettled: () => settled
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function createBrowserRPCBridge({
|
|
94
|
+
authToken,
|
|
95
|
+
authorize = (token) => isAuthorized(token, authToken),
|
|
96
|
+
onConnectionChange,
|
|
97
|
+
appWaitTimeoutMs = APP_WAIT_TIMEOUT
|
|
98
|
+
}: BrowserRPCBridgeOptions) {
|
|
99
|
+
const pending = new Map<string, PendingRequest & { ws: WebSocket }>()
|
|
100
|
+
const clients = new Set<WebSocket>()
|
|
101
|
+
const connectionWaiters = new Set<PendingRequest>()
|
|
102
|
+
// Track which WebSocket clients have authenticated via a valid
|
|
103
|
+
// register message. Unauthenticated clients can only send register;
|
|
104
|
+
// all other message types (request, response) are rejected.
|
|
105
|
+
const authenticatedClients = new Set<WebSocket>()
|
|
106
|
+
const connectionListeners = new Set<ConnectionListener>()
|
|
107
|
+
/**
|
|
108
|
+
* The editor windows, by socket, in registration order. Every window registers its own
|
|
109
|
+
* connection, so a second window must not displace the first; a reconnect of the same window
|
|
110
|
+
* does replace its old socket.
|
|
111
|
+
*/
|
|
112
|
+
const browsers = new Map<WebSocket, string>()
|
|
113
|
+
/** The window that last gained focus; tool calls go there until another window takes focus. */
|
|
114
|
+
let focusedBrowser: WebSocket | null = null
|
|
115
|
+
let bridgeClosed = false
|
|
116
|
+
|
|
117
|
+
function isOpen(ws: WebSocket): boolean {
|
|
118
|
+
return ws.readyState === ws.OPEN
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function isConnected(): boolean {
|
|
122
|
+
return [...browsers.keys()].some(isOpen)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* The window a tool call goes to: the last focused one. Before any window reports focus, the
|
|
127
|
+
* only connected window answers; with several, the most recently registered does, so a call
|
|
128
|
+
* never waits for a focus event that may not come.
|
|
129
|
+
*/
|
|
130
|
+
function targetBrowser(): WebSocket | null {
|
|
131
|
+
if (focusedBrowser && browsers.has(focusedBrowser) && isOpen(focusedBrowser)) {
|
|
132
|
+
return focusedBrowser
|
|
133
|
+
}
|
|
134
|
+
if (browsers.size === 1) {
|
|
135
|
+
const [only] = browsers.keys()
|
|
136
|
+
return isOpen(only) ? only : null
|
|
137
|
+
}
|
|
138
|
+
let latest: WebSocket | null = null
|
|
139
|
+
for (const ws of browsers.keys()) if (isOpen(ws)) latest = ws
|
|
140
|
+
return latest
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function notifyConnectionChange() {
|
|
144
|
+
onConnectionChange()
|
|
145
|
+
const connected = isConnected()
|
|
146
|
+
for (const listener of connectionListeners) listener(connected)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function subscribeConnectionChange(listener: ConnectionListener): () => void {
|
|
150
|
+
connectionListeners.add(listener)
|
|
151
|
+
listener(isConnected())
|
|
152
|
+
return () => connectionListeners.delete(listener)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function notifyConnectionWaiters() {
|
|
156
|
+
for (const waiter of connectionWaiters) {
|
|
157
|
+
clearTimeout(waiter.timer)
|
|
158
|
+
waiter.resolve(undefined)
|
|
159
|
+
}
|
|
160
|
+
connectionWaiters.clear()
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function rejectConnectionWaiters(reason: string) {
|
|
164
|
+
for (const waiter of connectionWaiters) {
|
|
165
|
+
clearTimeout(waiter.timer)
|
|
166
|
+
waiter.reject(new Error(reason))
|
|
167
|
+
}
|
|
168
|
+
connectionWaiters.clear()
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function waitForConnection(): Promise<void> {
|
|
172
|
+
return new Promise<void>((resolve, reject) => {
|
|
173
|
+
let waiter: PendingRequest | null = null
|
|
174
|
+
|
|
175
|
+
const timer = setTimeout(() => {
|
|
176
|
+
if (waiter) connectionWaiters.delete(waiter)
|
|
177
|
+
reject(new Error(APP_NOT_CONNECTED_MESSAGE))
|
|
178
|
+
}, appWaitTimeoutMs)
|
|
179
|
+
|
|
180
|
+
waiter = {
|
|
181
|
+
resolve: () => {
|
|
182
|
+
clearTimeout(timer)
|
|
183
|
+
resolve()
|
|
184
|
+
},
|
|
185
|
+
reject: (error: Error) => {
|
|
186
|
+
clearTimeout(timer)
|
|
187
|
+
reject(error)
|
|
188
|
+
},
|
|
189
|
+
timer
|
|
190
|
+
}
|
|
191
|
+
// Add the waiter BEFORE checking browser state to avoid a lost-wakeup
|
|
192
|
+
// race: if the browser registers between sendRPC's initial check and
|
|
193
|
+
// this point, notifyConnectionWaiters() will have already fired and
|
|
194
|
+
// cleared the set. Without this re-check, the waiter would stall for
|
|
195
|
+
// appWaitTimeoutMs even though the browser is connected.
|
|
196
|
+
connectionWaiters.add(waiter)
|
|
197
|
+
if (isConnected()) {
|
|
198
|
+
waiter.resolve(undefined)
|
|
199
|
+
connectionWaiters.delete(waiter)
|
|
200
|
+
}
|
|
201
|
+
})
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function rejectAllPending(reason: string) {
|
|
205
|
+
for (const [, req] of pending) {
|
|
206
|
+
clearTimeout(req.timer)
|
|
207
|
+
req.reject(new Error(reason))
|
|
208
|
+
}
|
|
209
|
+
pending.clear()
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** A closed window's requests cannot answer any more; other windows' calls keep waiting. */
|
|
213
|
+
function rejectPendingFor(ws: WebSocket, reason: string) {
|
|
214
|
+
for (const [id, req] of pending) {
|
|
215
|
+
if (req.ws !== ws) continue
|
|
216
|
+
clearTimeout(req.timer)
|
|
217
|
+
req.reject(new Error(reason))
|
|
218
|
+
pending.delete(id)
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function sendRegisterPrompt(ws: WebSocket) {
|
|
223
|
+
// Send a prompt inviting the client to register as the browser.
|
|
224
|
+
// IMPORTANT: Do NOT include the auth token here. On TCP, any local
|
|
225
|
+
// process can connect via WebSocket — sending the secret token would
|
|
226
|
+
// leak credentials to unauthenticated clients. The legitimate browser
|
|
227
|
+
// app already knows the token (from the discovery file or Vite env)
|
|
228
|
+
// and sends it proactively in its ws.onopen handler. The token field
|
|
229
|
+
// is set to null to signal that auth is required without revealing
|
|
230
|
+
// the secret. When auth is disabled (authToken === null), null is
|
|
231
|
+
// still correct — it means "no token needed."
|
|
232
|
+
sendJSON(ws, { type: 'register', token: null })
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function broadcastRegisterPrompt() {
|
|
236
|
+
for (const client of clients) sendRegisterPrompt(client)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function sendRPC(body: Record<string, unknown>): Promise<unknown> {
|
|
240
|
+
if (bridgeClosed) return Promise.reject(new Error('Server shutting down'))
|
|
241
|
+
return new Promise((resolve, reject) => {
|
|
242
|
+
const doSend = () => {
|
|
243
|
+
const ws = targetBrowser()
|
|
244
|
+
if (!ws) {
|
|
245
|
+
reject(new Error(APP_NOT_CONNECTED_MESSAGE))
|
|
246
|
+
return
|
|
247
|
+
}
|
|
248
|
+
const id = randomUUID()
|
|
249
|
+
const settle = createSettler(resolve, reject)
|
|
250
|
+
const timer = setTimeout(() => {
|
|
251
|
+
pending.delete(id)
|
|
252
|
+
settle.reject(new Error(`RPC timeout (${Math.round(RPC_TIMEOUT / 1000)}s)`))
|
|
253
|
+
}, RPC_TIMEOUT)
|
|
254
|
+
pending.set(id, { resolve: settle.resolve, reject: settle.reject, timer, ws })
|
|
255
|
+
try {
|
|
256
|
+
ws.send(JSON.stringify({ ...body, type: 'request', id }))
|
|
257
|
+
} catch (e) {
|
|
258
|
+
clearTimeout(timer)
|
|
259
|
+
pending.delete(id)
|
|
260
|
+
if (!settle.isSettled()) {
|
|
261
|
+
settle.reject(e instanceof Error ? e : new Error(String(e)))
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (targetBrowser()) {
|
|
267
|
+
doSend()
|
|
268
|
+
} else {
|
|
269
|
+
void waitForConnection().then(doSend).catch(reject)
|
|
270
|
+
}
|
|
271
|
+
})
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async function handleClientRequest(
|
|
275
|
+
ws: WebSocket,
|
|
276
|
+
msg: v.InferOutput<typeof requestMessageSchema>
|
|
277
|
+
) {
|
|
278
|
+
try {
|
|
279
|
+
const result = await sendRPC(stripEnvelope(msg))
|
|
280
|
+
sendJSON(ws, { ...responsePayload(result), type: 'response', id: msg.id, ok: true })
|
|
281
|
+
} catch (e) {
|
|
282
|
+
sendJSON(ws, {
|
|
283
|
+
type: 'response',
|
|
284
|
+
id: msg.id,
|
|
285
|
+
ok: false,
|
|
286
|
+
error: e instanceof Error ? e.message : String(e)
|
|
287
|
+
})
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Registers an editor window. A window is identified by its label: the same window reconnecting
|
|
293
|
+
* replaces its old socket and rejects only its own in-flight calls, while a second window keeps
|
|
294
|
+
* the first connected.
|
|
295
|
+
*/
|
|
296
|
+
function registerBrowser(ws: WebSocket, token: string | null, window: string) {
|
|
297
|
+
if (bridgeClosed) return
|
|
298
|
+
if (!authorize(token)) {
|
|
299
|
+
ws.close()
|
|
300
|
+
return
|
|
301
|
+
}
|
|
302
|
+
// Mark this client as authenticated — it can now send requests.
|
|
303
|
+
authenticatedClients.add(ws)
|
|
304
|
+
for (const [previous, label] of browsers) {
|
|
305
|
+
if (label !== window || previous === ws) continue
|
|
306
|
+
// Reject in-flight requests to this window's old socket. Without this, pending requests
|
|
307
|
+
// sit in the pending map until RPC_TIMEOUT (20s), because handleClose for the old socket
|
|
308
|
+
// no longer finds its label once this connection takes it.
|
|
309
|
+
rejectPendingFor(previous, 'Browser reconnected')
|
|
310
|
+
browsers.delete(previous)
|
|
311
|
+
authenticatedClients.delete(previous)
|
|
312
|
+
if (focusedBrowser === previous) focusedBrowser = ws
|
|
313
|
+
if (isOpen(previous)) previous.close()
|
|
314
|
+
}
|
|
315
|
+
browsers.set(ws, window)
|
|
316
|
+
notifyConnectionWaiters()
|
|
317
|
+
notifyConnectionChange()
|
|
318
|
+
broadcastRegisterPrompt()
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function handleBrowserResponse(msg: v.InferOutput<typeof responseMessageSchema>, ws: WebSocket) {
|
|
322
|
+
const req = pending.get(msg.id)
|
|
323
|
+
// Only the window a call was sent to may answer it.
|
|
324
|
+
if (!req || req.ws !== ws) return
|
|
325
|
+
pending.delete(msg.id)
|
|
326
|
+
clearTimeout(req.timer)
|
|
327
|
+
if (msg.ok === false) {
|
|
328
|
+
req.reject(new Error(msg.error ?? 'RPC failed'))
|
|
329
|
+
} else {
|
|
330
|
+
req.resolve(stripEnvelope(msg))
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function handleMessage(data: string, ws: WebSocket) {
|
|
335
|
+
if (bridgeClosed) return
|
|
336
|
+
const envelope = v.safeParse(browserEnvelopeSchema, data)
|
|
337
|
+
if (!envelope.success) {
|
|
338
|
+
if (envelope.issues.some((issue) => issue.type === 'parse_json')) {
|
|
339
|
+
console.warn('Malformed automation message:', v.summarize(envelope.issues))
|
|
340
|
+
} else {
|
|
341
|
+
ws.close()
|
|
342
|
+
}
|
|
343
|
+
return
|
|
344
|
+
}
|
|
345
|
+
const msg = envelope.output
|
|
346
|
+
|
|
347
|
+
if (msg.type === 'auth' || msg.type === 'register') {
|
|
348
|
+
// `auth` authenticates a stdio bridge client without registering it as
|
|
349
|
+
// the browser app, so it can send request/response messages without
|
|
350
|
+
// becoming the RPC target. The token is validated the same way as
|
|
351
|
+
// registerBrowser — when auth is disabled (authToken === null), any
|
|
352
|
+
// token is accepted. A message without a token is ignored; a token of
|
|
353
|
+
// any other type closes the socket.
|
|
354
|
+
const handshake = v.safeParse(handshakeMessageSchema, msg)
|
|
355
|
+
if (!handshake.success) {
|
|
356
|
+
ws.close()
|
|
357
|
+
return
|
|
358
|
+
}
|
|
359
|
+
const { token, window } = handshake.output
|
|
360
|
+
if (token === undefined) return
|
|
361
|
+
if (msg.type === 'register') {
|
|
362
|
+
registerBrowser(ws, token, window ?? '')
|
|
363
|
+
} else if (authorize(token)) {
|
|
364
|
+
authenticatedClients.add(ws)
|
|
365
|
+
} else {
|
|
366
|
+
ws.close()
|
|
367
|
+
}
|
|
368
|
+
return
|
|
369
|
+
}
|
|
370
|
+
// All non-register messages require authentication. Without this
|
|
371
|
+
// check, an unauthenticated WebSocket client (that hasn't sent a
|
|
372
|
+
// valid register message) could bypass the HTTP auth on /rpc by
|
|
373
|
+
// sending request messages over the WebSocket directly.
|
|
374
|
+
if (!authenticatedClients.has(ws)) {
|
|
375
|
+
ws.close()
|
|
376
|
+
return
|
|
377
|
+
}
|
|
378
|
+
if (msg.type === 'focus') {
|
|
379
|
+
// Focus is the routing signal: a tool call goes to the window that last had it, and a
|
|
380
|
+
// report from anything but a registered editor window cannot move that.
|
|
381
|
+
if (v.safeParse(focusMessageSchema, msg).success && browsers.has(ws)) focusedBrowser = ws
|
|
382
|
+
return
|
|
383
|
+
}
|
|
384
|
+
const request = v.safeParse(requestMessageSchema, msg)
|
|
385
|
+
if (request.success) {
|
|
386
|
+
void handleClientRequest(ws, request.output)
|
|
387
|
+
return
|
|
388
|
+
}
|
|
389
|
+
const response = v.safeParse(responseMessageSchema, msg)
|
|
390
|
+
if (response.success) handleBrowserResponse(response.output, ws)
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function handleClose(ws: WebSocket) {
|
|
394
|
+
clients.delete(ws)
|
|
395
|
+
authenticatedClients.delete(ws)
|
|
396
|
+
if (!browsers.delete(ws)) return
|
|
397
|
+
if (focusedBrowser === ws) focusedBrowser = null
|
|
398
|
+
rejectPendingFor(ws, 'Browser disconnected')
|
|
399
|
+
// Intentionally NOT rejecting connectionWaiters here. If a request
|
|
400
|
+
// entered waitForConnection() before the close event (e.g. during a
|
|
401
|
+
// CLOSING→CLOSED transition), the waiter should keep waiting the full
|
|
402
|
+
// APP_WAIT_TIMEOUT for a reconnect. registerBrowser will resolve it
|
|
403
|
+
// via notifyConnectionWaiters if the browser reconnects in time.
|
|
404
|
+
notifyConnectionChange()
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function handleConnection(ws: WebSocket) {
|
|
408
|
+
if (bridgeClosed) return
|
|
409
|
+
clients.add(ws)
|
|
410
|
+
// Transport security restricts WHO can connect: Unix socket with
|
|
411
|
+
// 0o600 permissions (same-user only) or TCP localhost (any local
|
|
412
|
+
// process). The authenticatedClients set gates WHAT connected clients
|
|
413
|
+
// can do: only those that sent a valid register message may forward
|
|
414
|
+
// requests. The register prompt does NOT include the auth token —
|
|
415
|
+
// the browser app sends the token proactively (from the discovery
|
|
416
|
+
// file or Vite env).
|
|
417
|
+
sendRegisterPrompt(ws)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function close() {
|
|
421
|
+
bridgeClosed = true
|
|
422
|
+
rejectAllPending('Server shutting down')
|
|
423
|
+
rejectConnectionWaiters('Server shutting down')
|
|
424
|
+
browsers.clear()
|
|
425
|
+
focusedBrowser = null
|
|
426
|
+
clients.clear()
|
|
427
|
+
authenticatedClients.clear()
|
|
428
|
+
connectionListeners.clear()
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
return {
|
|
432
|
+
close,
|
|
433
|
+
isConnected,
|
|
434
|
+
subscribeConnectionChange,
|
|
435
|
+
sendRPC,
|
|
436
|
+
handleConnection,
|
|
437
|
+
handleMessage,
|
|
438
|
+
handleClose
|
|
439
|
+
}
|
|
440
|
+
}
|
package/src/connect.ts
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from 'node:child_process'
|
|
3
|
+
import { platform } from 'node:os'
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
connectCORSOrigins,
|
|
7
|
+
connectLink,
|
|
8
|
+
resolveConnectAppURL,
|
|
9
|
+
writeConnectPage
|
|
10
|
+
} from '#mcp/agents/link'
|
|
11
|
+
import { pairingFingerprint } from '#mcp/agents/pairing'
|
|
12
|
+
import { resolveMCPRoot } from '#mcp/root'
|
|
13
|
+
import { MCP_VERSION, startServer } from '#mcp/server'
|
|
14
|
+
import { readToolPolicyFromEnv } from '#mcp/tool/policy'
|
|
15
|
+
import { DEFAULT_CONNECT_APP_URL } from '#mcp/transport/origins'
|
|
16
|
+
import { getCompanionDir } from '#mcp/transport/paths'
|
|
17
|
+
|
|
18
|
+
const DEFAULT_PORT = 7600
|
|
19
|
+
|
|
20
|
+
if (process.argv.includes('--version')) {
|
|
21
|
+
process.stdout.write(`${MCP_VERSION}\n`)
|
|
22
|
+
process.exit(0)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (process.argv.includes('--help') || process.argv.includes('-h')) {
|
|
26
|
+
process.stdout.write(
|
|
27
|
+
`pairdraw-connect\n\n` +
|
|
28
|
+
`Connect Pairdraw in the browser to this computer, so its chat can run\n` +
|
|
29
|
+
`Claude Code, Codex, or Gemini CLI here and use Pairdraw's tools.\n\n` +
|
|
30
|
+
`Starts Pairdraw's MCP server with an agent bridge and opens a one-time link\n` +
|
|
31
|
+
`that pairs the browser tab. Keep it running while you use agents.\n\n` +
|
|
32
|
+
`Options:\n` +
|
|
33
|
+
` --help, -h Show this help message\n` +
|
|
34
|
+
` --version Print the version\n` +
|
|
35
|
+
` --no-open Print the link without opening the browser\n\n` +
|
|
36
|
+
`Environment variables:\n` +
|
|
37
|
+
` PORT TCP port (default: ${DEFAULT_PORT})\n` +
|
|
38
|
+
` PAIRDRAW_CONNECT_APP_URL The Pairdraw web app to pair with (default:\n` +
|
|
39
|
+
` ${DEFAULT_CONNECT_APP_URL}, the editor \`bun run dev\` serves).\n` +
|
|
40
|
+
` Its origin may call this server.\n` +
|
|
41
|
+
` PAIRDRAW_MCP_CORS_ORIGIN Further origins allowed to call this server, comma-separated.\n` +
|
|
42
|
+
` PAIRDRAW_MCP_ROOT Allowed directory for file-scoped tools (default: home\n` +
|
|
43
|
+
` directory on Windows, current working directory elsewhere)\n` +
|
|
44
|
+
` PAIRDRAW_MCP_SOCKET Override the Unix socket path\n` +
|
|
45
|
+
` PAIRDRAW_MCP_DISABLED_TOOLS Comma-separated tool names to omit\n` +
|
|
46
|
+
` PAIRDRAW_MCP_SCOPE "selection" to let clients read only the selected layers\n\n` +
|
|
47
|
+
`The eval tool is always off here, and authentication cannot be disabled.\n`
|
|
48
|
+
)
|
|
49
|
+
process.exit(0)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function fail(message: string): never {
|
|
53
|
+
process.stderr.write(`Error: ${message}\n`)
|
|
54
|
+
process.exit(1)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const portText = (process.env.PORT ?? String(DEFAULT_PORT)).trim()
|
|
58
|
+
if (!/^\d+$/.test(portText)) fail(`PORT must be an integer in 1–65535, got "${portText}"`)
|
|
59
|
+
const port = Number.parseInt(portText, 10)
|
|
60
|
+
if (port < 1 || port > 65535) fail(`PORT must be an integer in 1–65535, got "${portText}"`)
|
|
61
|
+
|
|
62
|
+
const appURL = resolveConnectAppURL(process.env.PAIRDRAW_CONNECT_APP_URL)
|
|
63
|
+
if (!appURL) {
|
|
64
|
+
fail('PAIRDRAW_CONNECT_APP_URL must be an https URL, or http on localhost')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const explicitToken = process.env.PAIRDRAW_MCP_AUTH_TOKEN?.trim()
|
|
68
|
+
const toolPolicy = readToolPolicyFromEnv()
|
|
69
|
+
|
|
70
|
+
let handle: Awaited<ReturnType<typeof startServer>>
|
|
71
|
+
try {
|
|
72
|
+
handle = await startServer({
|
|
73
|
+
httpPort: port,
|
|
74
|
+
withTcp: true,
|
|
75
|
+
socketPath: process.env.PAIRDRAW_MCP_SOCKET?.trim() || null,
|
|
76
|
+
// The browser runs agents that can edit files; eval would let a page run code here too.
|
|
77
|
+
enableEval: false,
|
|
78
|
+
disabledTools: toolPolicy.disabledTools,
|
|
79
|
+
scope: toolPolicy.scope,
|
|
80
|
+
mcpRoot: resolveMCPRoot(process.env.PAIRDRAW_MCP_ROOT),
|
|
81
|
+
// Auth always stays on: a paired tab and local MCP clients each bring their own token.
|
|
82
|
+
authToken: explicitToken || undefined,
|
|
83
|
+
corsOrigin: connectCORSOrigins(process.env.PAIRDRAW_MCP_CORS_ORIGIN, appURL),
|
|
84
|
+
agents: {
|
|
85
|
+
onPaired: () =>
|
|
86
|
+
process.stdout.write(
|
|
87
|
+
'A browser tab connected. If you did not open the link, press Ctrl+C to stop.\n'
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
})
|
|
91
|
+
} catch (error) {
|
|
92
|
+
const code = error instanceof Error && 'code' in error ? error.code : null
|
|
93
|
+
if (code === 'EADDRINUSE') {
|
|
94
|
+
fail(
|
|
95
|
+
`port ${port} or the MCP socket is already in use. Quit the Pairdraw desktop app or ` +
|
|
96
|
+
`another MCP server, or start this one with PORT=${port + 1}.`
|
|
97
|
+
)
|
|
98
|
+
}
|
|
99
|
+
fail(error instanceof Error ? error.message : String(error))
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const issueCode = handle.issuePairingCode
|
|
103
|
+
if (!issueCode) fail('The agent bridge did not start.')
|
|
104
|
+
|
|
105
|
+
/** Opens a file or link in the default browser, without a shell. */
|
|
106
|
+
function openBrowser(url: string): void {
|
|
107
|
+
const os = platform()
|
|
108
|
+
let command = 'xdg-open'
|
|
109
|
+
let args = [url]
|
|
110
|
+
if (os === 'darwin') command = 'open'
|
|
111
|
+
if (os === 'win32') {
|
|
112
|
+
command = 'rundll32'
|
|
113
|
+
args = ['url.dll,FileProtocolHandler', url]
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
const child = spawn(command, args, { stdio: 'ignore', detached: true })
|
|
117
|
+
child.on('error', () => undefined)
|
|
118
|
+
child.unref()
|
|
119
|
+
} catch {
|
|
120
|
+
process.stdout.write('Could not open the browser; open the link above yourself.\n')
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const shouldOpen = !process.argv.includes('--no-open')
|
|
125
|
+
/** How long the page that forwards to a link stays on disk; the browser reads it at once. */
|
|
126
|
+
const PAGE_LIFETIME_MS = 30_000
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Opens the link through a private page, so no command line holds the code, and deletes the
|
|
130
|
+
* page soon after.
|
|
131
|
+
*/
|
|
132
|
+
async function openLink(link: string): Promise<void> {
|
|
133
|
+
try {
|
|
134
|
+
const page = await writeConnectPage(await getCompanionDir(), link)
|
|
135
|
+
openBrowser(page.path)
|
|
136
|
+
setTimeout(() => void page.remove(), PAGE_LIFETIME_MS).unref()
|
|
137
|
+
} catch {
|
|
138
|
+
process.stdout.write('Could not open the browser; open the link above yourself.\n')
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function announceLink(open: boolean) {
|
|
143
|
+
const code = issueCode()
|
|
144
|
+
const link = connectLink(appURL, code, handle.httpPort, DEFAULT_PORT)
|
|
145
|
+
process.stdout.write(
|
|
146
|
+
`\nOpen this link to connect Pairdraw to this computer (works once, for 2 minutes):\n` +
|
|
147
|
+
` ${link}\n` +
|
|
148
|
+
`The tab asks you to confirm; check that it shows ${pairingFingerprint(code)}.\n\n` +
|
|
149
|
+
`Press Enter for a new link. Press Ctrl+C to stop.\n`
|
|
150
|
+
)
|
|
151
|
+
if (open) void openLink(link)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
process.stdout.write(`Pairdraw companion ${MCP_VERSION}\n`)
|
|
155
|
+
process.stdout.write(` HTTP: http://127.0.0.1:${handle.httpPort}\n`)
|
|
156
|
+
if (handle.socketPath) process.stdout.write(` Socket: ${handle.socketPath}\n`)
|
|
157
|
+
announceLink(shouldOpen)
|
|
158
|
+
|
|
159
|
+
process.stdin.on('data', () => announceLink(false))
|
|
160
|
+
process.stdin.on('error', () => undefined)
|
|
161
|
+
process.stdin.resume()
|
|
162
|
+
|
|
163
|
+
const shutdown = async () => {
|
|
164
|
+
process.stdout.write('\nStopping the Pairdraw companion...\n')
|
|
165
|
+
await handle.close()
|
|
166
|
+
process.exit(0)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
process.on('SIGINT', () => void shutdown().catch(() => process.exit(1)))
|
|
170
|
+
process.on('SIGTERM', () => void shutdown().catch(() => process.exit(1)))
|
package/src/global.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export const MCP_CORS_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
|
|
2
|
+
|
|
3
|
+
// x-mcp-token: Pairdraw extension for MCP clients that cannot set the
|
|
4
|
+
// Authorization header (e.g. some IDE plugins). Not part of the MCP spec.
|
|
5
|
+
export const MCP_CORS_HEADERS = [
|
|
6
|
+
'Content-Type',
|
|
7
|
+
'Authorization',
|
|
8
|
+
'x-mcp-token',
|
|
9
|
+
'mcp-session-id',
|
|
10
|
+
'Last-Event-ID',
|
|
11
|
+
'mcp-protocol-version'
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
export const MCP_EXPOSED_HEADERS = ['mcp-session-id', 'mcp-protocol-version']
|