@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
package/src/index.ts ADDED
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env node
2
+ import { devAgentBridgeFromEnv } from '#mcp/agents/index'
3
+ import { resolveMCPRoot } from '#mcp/root'
4
+ import { MCP_VERSION, startServer } from '#mcp/server'
5
+ import { readToolPolicyFromEnv } from '#mcp/tool/policy'
6
+ import { resolveCORSOrigins } from '#mcp/transport/origins'
7
+
8
+ if (process.argv.includes('--version')) {
9
+ process.stdout.write(`${MCP_VERSION}\n`)
10
+ process.exit(0)
11
+ }
12
+
13
+ if (process.argv.includes('--help') || process.argv.includes('-h')) {
14
+ process.stdout.write(
15
+ `pairdraw-mcp-http\n\n` +
16
+ `Start the Pairdraw MCP server.\n\n` +
17
+ `On macOS/Linux, the server listens on a Unix domain socket by default\n` +
18
+ `with optional TCP for browser clients. On Windows, only TCP is available.\n\n` +
19
+ `Options:\n` +
20
+ ` --help, -h Show this help message\n` +
21
+ ` --version Print the version\n\n` +
22
+ `Environment variables:\n` +
23
+ ` PORT TCP port (default: 7600, set to 0 to disable TCP)\n` +
24
+ ` PAIRDRAW_MCP_SOCKET Override Unix socket path (recorded in the discovery file)\n` +
25
+ ` PAIRDRAW_MCP_DISCOVERY_PATH Override discovery file (mcp.json) location; defaults to the\n` +
26
+ ` platform path. Parent dir created 0o700. Mainly for test isolation.\n` +
27
+ ` PAIRDRAW_MCP_TCP Deprecated — TCP is controlled by PORT (>0 = on, 0 = off)\n` +
28
+ ` PAIRDRAW_MCP_AUTH_TOKEN Bearer token for MCP and RPC auth\n` +
29
+ ` PAIRDRAW_MCP_ROOT Allowed directory for file-scoped tools (default: home directory on Windows, current working directory elsewhere)\n` +
30
+ ` PAIRDRAW_MCP_EVAL Set to 1 to enable the eval tool\n` +
31
+ ` PAIRDRAW_MCP_SESSION_IDLE_TIMEOUT_MS\n` +
32
+ ` Close sessions idle this long, in ms (default: 900000;\n` +
33
+ ` 0 disables). An open GET/SSE stream is not activity.\n` +
34
+ ` PAIRDRAW_MCP_DISABLED_TOOLS Comma-separated tool names to omit\n` +
35
+ ` PAIRDRAW_MCP_SCOPE "selection" to let clients read only the selected layers\n` +
36
+ ` (default: "document")\n` +
37
+ ` PAIRDRAW_MCP_CORS_ORIGIN Allowed CORS origins, comma-separated.\n` +
38
+ ` Defaults to the desktop app origin, since the app\n` +
39
+ ` webview is the only view that calls this server.\n` +
40
+ ` PAIRDRAW_MCP_APP_TIMEOUT_MS If set, close the server and remove its discovery\n` +
41
+ ` file after no app is attached for this many ms. The\n` +
42
+ ` grace period starts at startup and after disconnects.\n` +
43
+ ` Unset/0 disables it (default) — do not set this for\n` +
44
+ ` manual/CLI use, since nothing may ever register.\n` +
45
+ ` PAIRDRAW_MCP_EXIT_ON_STDIN_CLOSE Set to 1 to shut down when stdin closes, so a\n` +
46
+ ` parent that starts the server through a shell wrapper\n` +
47
+ ` can stop it by closing the pipe. Unset for manual/CLI use.\n` +
48
+ ` PAIRDRAW_MCP_AGENTS Set to 1, with the two variables below, to start the agent\n` +
49
+ ` bridge for one browser tab that the parent process gave\n` +
50
+ ` the same tokens, as \`bun run dev\` does; no pairing link.\n` +
51
+ ` The tokens are never written to the discovery file,\n` +
52
+ ` and the eval tool stays off.\n` +
53
+ ` PAIRDRAW_MCP_AGENT_SESSION The tab's session token: 64 lowercase hex characters.\n` +
54
+ ` PAIRDRAW_MCP_AGENT_TOKEN The token the tab hands its agents, which reaches only\n` +
55
+ ` /mcp: 64 lowercase hex characters, not the session token.\n`
56
+ )
57
+ process.exit(0)
58
+ }
59
+
60
+ const rawPortText = (process.env.PORT ?? '7600').trim()
61
+ // Reject non-digit strings (including hex like "0x50" and partially-numeric like
62
+ // "7600abc") — Number.parseInt would silently parse these, masking misconfig.
63
+ if (!/^\d+$/.test(rawPortText)) {
64
+ process.stderr.write(`Error: PORT must be an integer in 0–65535, got "${process.env.PORT}"\n`)
65
+ process.exit(1)
66
+ }
67
+ const rawPort = Number.parseInt(rawPortText, 10)
68
+ // Validate PORT: must be an integer in 0–65535. 0 means "disable TCP".
69
+ if (rawPort < 0 || rawPort > 65535) {
70
+ process.stderr.write(`Error: PORT must be an integer in 0–65535, got "${process.env.PORT}"\n`)
71
+ process.exit(1)
72
+ }
73
+ const port = rawPort
74
+ // PAIRDRAW_MCP_TCP is accepted for backward compat but has no effect —
75
+ // the PORT value alone determines whether TCP is enabled (PORT=0 is the kill switch).
76
+ const withTcp = port > 0
77
+
78
+ const MAX_TIMEOUT_MS = 2_147_483_647
79
+
80
+ /** Read a millisecond timeout from the environment, exiting on an invalid value. */
81
+ function readTimeoutEnv(name: string): number | undefined {
82
+ const text = process.env[name]?.trim()
83
+ if (!text) return undefined
84
+ const timeoutMs = Number(text)
85
+ if (!/^\d+$/.test(text) || timeoutMs > MAX_TIMEOUT_MS) {
86
+ process.stderr.write(
87
+ `Error: ${name} must be an integer in 0–${MAX_TIMEOUT_MS}, got "${text}"\n`
88
+ )
89
+ process.exit(1)
90
+ }
91
+ return timeoutMs
92
+ }
93
+
94
+ const appAttachTimeoutMs = readTimeoutEnv('PAIRDRAW_MCP_APP_TIMEOUT_MS')
95
+ const sessionIdleTimeoutMs = readTimeoutEnv('PAIRDRAW_MCP_SESSION_IDLE_TIMEOUT_MS')
96
+
97
+ const toolPolicy = readToolPolicyFromEnv()
98
+
99
+ // The agent bridge starts programs, so a malformed session leaves it off rather than guessing.
100
+ const agents = devAgentBridgeFromEnv()
101
+ if (process.env.PAIRDRAW_MCP_AGENTS === '1' && !agents) {
102
+ process.stderr.write(
103
+ 'Warning: PAIRDRAW_MCP_AGENTS=1 needs PAIRDRAW_MCP_AGENT_SESSION and ' +
104
+ 'PAIRDRAW_MCP_AGENT_TOKEN as two different 64-character lowercase hex tokens. ' +
105
+ 'Starting without the agent bridge.\n'
106
+ )
107
+ }
108
+ // As in `pairdraw-connect`: agents reach `/mcp`, where eval would run any script they send.
109
+ if (agents && toolPolicy.allowEval) {
110
+ process.stderr.write(
111
+ 'Warning: PAIRDRAW_MCP_EVAL=1 is ignored while the agent bridge is on ' +
112
+ '(PAIRDRAW_MCP_AGENTS=1). Starting without the eval tool.\n'
113
+ )
114
+ }
115
+
116
+ const handle = await startServer({
117
+ httpPort: withTcp ? port : 0,
118
+ withTcp,
119
+ socketPath: process.env.PAIRDRAW_MCP_SOCKET?.trim() || null,
120
+ enableEval: toolPolicy.allowEval && !agents,
121
+ disabledTools: toolPolicy.disabledTools,
122
+ scope: toolPolicy.scope,
123
+ mcpRoot: resolveMCPRoot(process.env.PAIRDRAW_MCP_ROOT),
124
+ // Auth token: undefined → auto-generate, empty string → disable auth,
125
+ // non-empty → use trimmed value. Whitespace-only is rejected to prevent a
126
+ // silent fallback to an auto-generated token when the operator intended to
127
+ // set an explicit one.
128
+ authToken: (() => {
129
+ const raw = process.env.PAIRDRAW_MCP_AUTH_TOKEN
130
+ if (raw === undefined) return undefined
131
+ if (raw === '') return null
132
+ const trimmed = raw.trim()
133
+ if (!trimmed) {
134
+ process.stderr.write(
135
+ 'Error: PAIRDRAW_MCP_AUTH_TOKEN is whitespace-only. Set a real token, or use an empty string to disable auth.\n'
136
+ )
137
+ process.exit(1)
138
+ }
139
+ return trimmed
140
+ })(),
141
+ corsOrigin: resolveCORSOrigins(process.env.PAIRDRAW_MCP_CORS_ORIGIN),
142
+ appAttachTimeoutMs,
143
+ sessionIdleTimeoutMs,
144
+ agents: agents ?? undefined
145
+ })
146
+
147
+ const readyMarker = process.env.PAIRDRAW_MCP_READY_MARKER
148
+ if (readyMarker && /^pairdraw-ready:[a-f0-9-]{36}$/.test(readyMarker)) {
149
+ process.stderr.write(`${readyMarker}\n`)
150
+ }
151
+
152
+ process.stderr.write(`Pairdraw MCP server\n`)
153
+ if (handle.socketPath) process.stderr.write(` Socket: ${handle.socketPath}\n`)
154
+ if (handle.httpPort) process.stderr.write(` HTTP: http://127.0.0.1:${handle.httpPort}\n`)
155
+
156
+ // Graceful shutdown on signals
157
+ const shutdown = async () => {
158
+ process.stderr.write('\nShutting down MCP server...\n')
159
+ await handle.close()
160
+ process.exit(0)
161
+ }
162
+
163
+ process.on('SIGINT', () => void shutdown().catch(() => process.exit(1)))
164
+ process.on('SIGTERM', () => void shutdown().catch(() => process.exit(1)))
165
+
166
+ // A parent that started this server through a shell wrapper cannot always kill it directly
167
+ // (on Windows, ending `cmd /c` leaves the process it started running), but its end of the
168
+ // stdin pipe closes with it.
169
+ if (process.env.PAIRDRAW_MCP_EXIT_ON_STDIN_CLOSE === '1') {
170
+ let stdinClosed = false
171
+ const onStdinClosed = () => {
172
+ if (stdinClosed) return
173
+ stdinClosed = true
174
+ void shutdown().catch(() => process.exit(1))
175
+ }
176
+ process.stdin.on('end', onStdinClosed)
177
+ process.stdin.on('close', onStdinClosed)
178
+ process.stdin.resume()
179
+ }
package/src/json.ts ADDED
@@ -0,0 +1 @@
1
+ export type RPCJSONObject = { [key: string]: unknown }
package/src/result.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { Buffer } from 'node:buffer'
2
+
3
+ export type MCPContent =
4
+ | { type: 'text'; text: string }
5
+ | { type: 'image'; data: string; mimeType: string }
6
+
7
+ export type MCPResult = { content: MCPContent[]; isError?: boolean }
8
+
9
+ export const MAX_RESULT_BYTES = 900_000
10
+
11
+ export function resultTooLargeMessage(kind: string, bytes: number, hint: string): string {
12
+ return `${kind} is too large (${Math.round(bytes / 1024)}KB, limit ${Math.round(
13
+ MAX_RESULT_BYTES / 1024
14
+ )}KB). ${hint}`
15
+ }
16
+
17
+ export function ok(data: unknown, toolName?: string): MCPResult {
18
+ const text = JSON.stringify(data, null, 2)
19
+ const bytes = Buffer.byteLength(text, 'utf8')
20
+ if (bytes > MAX_RESULT_BYTES) {
21
+ return fail(
22
+ new Error(
23
+ resultTooLargeMessage(
24
+ toolName ? `Result from "${toolName}"` : 'Result',
25
+ bytes,
26
+ 'Narrow the request with depth/root_id/node_types, get_node, or find_nodes.'
27
+ )
28
+ )
29
+ )
30
+ }
31
+ return { content: [{ type: 'text', text }] }
32
+ }
33
+
34
+ export function fail(e: unknown): MCPResult {
35
+ const msg = e instanceof Error ? e.message : String(e)
36
+ return { content: [{ type: 'text', text: JSON.stringify({ error: msg }) }], isError: true }
37
+ }
package/src/root.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { homedir, platform } from 'node:os'
2
+
3
+ export function resolveMCPRoot(value: string | undefined, runtimePlatform = platform()): string {
4
+ return value?.trim() || (runtimePlatform === 'win32' ? homedir() : process.cwd())
5
+ }
@@ -0,0 +1,5 @@
1
+ export type PendingRequest = {
2
+ resolve: (value: unknown) => void
3
+ reject: (error: Error) => void
4
+ timer: ReturnType<typeof setTimeout>
5
+ }
@@ -0,0 +1,58 @@
1
+ import type { WebSocket, WebSocketServer } from 'ws'
2
+
3
+ import type { createBrowserRPCBridge } from '#mcp/browser-rpc'
4
+
5
+ const HEARTBEAT_INTERVAL_MS = 5_000
6
+
7
+ /** Set up shared WebSocket connection handling and heartbeat. Call once. */
8
+ export function wireConnectionHandling(
9
+ wss: WebSocketServer,
10
+ browserRPC: ReturnType<typeof createBrowserRPCBridge>
11
+ ) {
12
+ const alive = new WeakMap<WebSocket, boolean>()
13
+
14
+ wss.on('connection', (ws: WebSocket) => {
15
+ alive.set(ws, true)
16
+ browserRPC.handleConnection(ws)
17
+
18
+ ws.on('pong', () => alive.set(ws, true))
19
+ ws.on('message', (raw) => {
20
+ alive.set(ws, true)
21
+ const data = typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf-8')
22
+ browserRPC.handleMessage(data, ws)
23
+ })
24
+
25
+ ws.on('close', () => {
26
+ browserRPC.handleClose(ws)
27
+ })
28
+
29
+ ws.on('error', () => {
30
+ try {
31
+ ws.terminate()
32
+ } catch {
33
+ alive.delete(ws)
34
+ }
35
+ })
36
+ })
37
+
38
+ const heartbeat = setInterval(() => {
39
+ for (const ws of wss.clients) {
40
+ if (alive.get(ws) === false) {
41
+ try {
42
+ ws.terminate()
43
+ } catch {
44
+ continue
45
+ }
46
+ continue
47
+ }
48
+ alive.set(ws, false)
49
+ try {
50
+ ws.ping()
51
+ } catch {
52
+ continue
53
+ }
54
+ }
55
+ }, HEARTBEAT_INTERVAL_MS)
56
+ heartbeat.unref()
57
+ wss.on('close', () => clearInterval(heartbeat))
58
+ }
@@ -0,0 +1,49 @@
1
+ import type { Context, Hono } from 'hono'
2
+ import { bodyLimit } from 'hono/body-limit'
3
+
4
+ import { MAX_FILE_TRANSFER_BYTES, readInsideRoot, writeInsideRoot } from '#mcp/tool/output'
5
+
6
+ /**
7
+ * The path after `/files/`, one encoded segment per folder, so the URL ends in the file's name.
8
+ * Empty segments keep a POSIX root (`/files//Users/…`) and a Windows share (`/files///server/…`).
9
+ * Decoded from the raw URL, since the router's path is already partly decoded.
10
+ */
11
+ function filePath(c: Context): string {
12
+ const pathname = new URL(c.req.url).pathname
13
+ return pathname.slice('/files/'.length).split('/').map(decodeURIComponent).join('/')
14
+ }
15
+
16
+ function failure(c: Context, e: unknown) {
17
+ return c.json({ error: e instanceof Error ? e.message : String(e) }, 400)
18
+ }
19
+
20
+ /**
21
+ * A browser app cannot reach the paths the file tools name, so it reads and writes them through
22
+ * `/files/`, inside the same root the tools resolve them in. The caller guards the route with the
23
+ * server's token.
24
+ */
25
+ export function registerFileRoutes(app: Hono, root: string): void {
26
+ app.get('/files/*', async (c) => {
27
+ try {
28
+ const bytes = await readInsideRoot(filePath(c), root)
29
+ return c.body(bytes, 200, { 'content-type': 'application/octet-stream' })
30
+ } catch (e) {
31
+ return failure(c, e)
32
+ }
33
+ })
34
+ app.put(
35
+ '/files/*',
36
+ bodyLimit({
37
+ maxSize: MAX_FILE_TRANSFER_BYTES,
38
+ onError: (c) => c.json({ error: 'File is too large' }, 413)
39
+ }),
40
+ async (c) => {
41
+ try {
42
+ const bytes = new Uint8Array(await c.req.arrayBuffer())
43
+ return c.json(await writeInsideRoot(filePath(c), root, bytes))
44
+ } catch (e) {
45
+ return failure(c, e)
46
+ }
47
+ }
48
+ )
49
+ }
@@ -0,0 +1,24 @@
1
+ import { resolveCommand } from 'package-manager-detector/commands'
2
+ import { detect, getUserAgent } from 'package-manager-detector/detect'
3
+
4
+ let installCommandPromise: Promise<string> | null = null
5
+
6
+ async function resolveMCPInstallCommand(version: string): Promise<string> {
7
+ const agent =
8
+ getUserAgent() ??
9
+ (
10
+ await detect({
11
+ strategies: ['install-metadata', 'lockfile', 'packageManager-field', 'devEngines-field']
12
+ })
13
+ )?.agent ??
14
+ 'npm'
15
+ const resolved = resolveCommand(agent, 'global', [`@pairdraw/mcp@${version}`])
16
+ if (!resolved) return `npm install -g @pairdraw/mcp@${version}`
17
+ return [resolved.command, ...resolved.args].join(' ')
18
+ }
19
+
20
+ /** How to install this server version globally with the package manager that runs it. */
21
+ export function mcpInstallCommand(version: string): Promise<string> {
22
+ installCommandPromise ??= resolveMCPInstallCommand(version)
23
+ return installCommandPromise
24
+ }