@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,336 @@
1
+ import { constants } from 'node:fs'
2
+ import {
3
+ lstat,
4
+ mkdir,
5
+ open,
6
+ readlink,
7
+ realpath,
8
+ writeFile,
9
+ type FileHandle
10
+ } from 'node:fs/promises'
11
+ import { dirname, basename, isAbsolute, join, parse, resolve, sep as osSep } from 'node:path'
12
+
13
+ import { compact } from 'es-toolkit/array'
14
+ import { toUint8Array } from 'js-base64'
15
+
16
+ import { ok } from '#mcp/result'
17
+ import type { MCPResult } from '#mcp/result'
18
+
19
+ /** Returns true for filesystem errors that indicate a missing or unresolvable path (ENOENT, ENOTDIR, ELOOP). */
20
+ function isMissingPathError(e: unknown): boolean {
21
+ const code =
22
+ typeof e === 'object' && e !== null && 'code' in e ? (e as { code?: unknown }).code : undefined
23
+ return code === 'ENOENT' || code === 'ENOTDIR' || code === 'ELOOP'
24
+ }
25
+
26
+ /**
27
+ * Resolve a file path and verify it stays within the allowed root directory.
28
+ * Uses fs.realpath to resolve symlinks for the security check, preventing
29
+ * traversal attacks where a symlink inside root points outside root.
30
+ * Returns the resolved (normalized) path for display and file operations.
31
+ */
32
+
33
+ /** Walk up from `p` until we find a path that realpath() can resolve. */
34
+ async function resolveRealAncestor(
35
+ p: string
36
+ ): Promise<{ realAncestor: string; remainder: string }> {
37
+ let current = resolve(p)
38
+ let remainder = ''
39
+ let iterations = 0
40
+ do {
41
+ try {
42
+ const real = await realpath(current)
43
+ return { realAncestor: real, remainder }
44
+ } catch (e) {
45
+ if (!isMissingPathError(e)) throw e
46
+ const parent = dirname(current)
47
+ if (parent === current) return { realAncestor: current, remainder }
48
+ remainder = osSep + basename(current) + remainder
49
+ current = parent
50
+ }
51
+ iterations++
52
+ } while (iterations < 64) // depth limit to prevent infinite loops
53
+ // Fail closed: if we exceeded the depth limit, the path may contain
54
+ // unresolved symlink components (e.g., circular symlinks). Returning a
55
+ // partially-resolved path would allow it to pass containment checks
56
+ // even though the fully-resolved path could be outside root.
57
+ throw new Error(`Path resolution depth limit exceeded (possible circular symlinks): ${p}`)
58
+ }
59
+
60
+ /**
61
+ * Walks the non-existent path segments (remainder) from the real ancestor and
62
+ * rejects any that are symlinks. A symlink in a non-existent path segment
63
+ * could point outside the allowed root — when the file is eventually written,
64
+ * the OS follows the symlink chain and the write lands outside root.
65
+ */
66
+ async function assertNoSymlinksInRemainder(realAncestor: string, remainder: string): Promise<void> {
67
+ if (!remainder) return
68
+ const segments = compact(remainder.split(osSep))
69
+ let current = realAncestor
70
+ for (const seg of segments) {
71
+ current = join(current, seg)
72
+ try {
73
+ const stat = await lstat(current)
74
+ if (stat.isSymbolicLink()) {
75
+ throw new Error(`Path is outside the allowed root: symlink at ${current}`)
76
+ }
77
+ } catch (e) {
78
+ if (e instanceof Error && e.message.includes('outside the allowed root')) throw e
79
+ if (!isMissingPathError(e)) throw e
80
+ // lstat failed — the component doesn't exist at all, which is expected
81
+ // since we're creating a new file. No symlink to worry about.
82
+ }
83
+ }
84
+ }
85
+
86
+ /** Throw if `rootPath` is trivially broad (e.g. "/" or "C:\"). */
87
+ function assertNarrowRoot(rootPath: string, original: string): void {
88
+ const normalized = resolve(rootPath)
89
+ const parsedRoot = parse(normalized).root
90
+ if (normalized === '/' || normalized === osSep || normalized === parsedRoot) {
91
+ throw new Error(
92
+ `Root path is too broad: "${original}" (resolved to "${normalized}"). ` +
93
+ 'Specify a narrower PAIRDRAW_MCP_ROOT directory.'
94
+ )
95
+ }
96
+ }
97
+
98
+ /** Resolve `p` to its realpath-validated canonical form, handling non-existent paths. */
99
+ async function resolveRealPath(p: string): Promise<string> {
100
+ try {
101
+ return await realpath(p)
102
+ } catch (e) {
103
+ if (!isMissingPathError(e)) throw e
104
+ const parentDir = dirname(p)
105
+ const baseName = basename(p)
106
+ try {
107
+ const realParent = await realpath(parentDir)
108
+ return join(realParent, baseName)
109
+ } catch (e) {
110
+ if (!isMissingPathError(e)) throw e
111
+ const { realAncestor, remainder } = await resolveRealAncestor(parentDir)
112
+ await assertNoSymlinksInRemainder(realAncestor, remainder)
113
+ return join(realAncestor, remainder.slice(osSep.length), baseName)
114
+ }
115
+ }
116
+ }
117
+
118
+ export interface SafePathResult {
119
+ /** The user-provided normalized path (for display/error messages). */
120
+ resolved: string
121
+ /** The canonical realpath-validated path (for filesystem operations). */
122
+ realPath: string
123
+ }
124
+
125
+ const MAX_SYMLINK_DEPTH = 16
126
+
127
+ /**
128
+ * Resolve a dangling symlink's target. When realpath fails on a symlink,
129
+ * read the link target and recursively validate it is inside root.
130
+ * Returns the canonical realPath of the target, or undefined if `resolved`
131
+ * is not a symlink.
132
+ */
133
+ async function resolveDanglingSymlink(
134
+ resolved: string,
135
+ root: string,
136
+ realRoot: string,
137
+ symlinkDepth: number
138
+ ): Promise<string | undefined> {
139
+ try {
140
+ const stat = await lstat(resolved)
141
+ if (!stat.isSymbolicLink()) return undefined
142
+ // Dangling symlink — realpath already failed, which means the
143
+ // target doesn't exist. Read the symlink target and validate it
144
+ // is inside root. Absolute-path targets pointing outside root are
145
+ // rejected. Relative targets are resolved relative to the symlink
146
+ // directory and checked against root.
147
+ const linkTarget = await readlink(resolved)
148
+ const linkDir = dirname(resolved)
149
+ const resolvedTarget = isAbsolute(linkTarget) ? linkTarget : resolve(linkDir, linkTarget)
150
+ // Recursively validate the target (handles nested symlinks).
151
+ // Pass the already-canonical realRoot so the recursive call skips
152
+ // redundant assertNarrowRoot + realpath(root) work.
153
+ const targetResult = await resolveSafePathInternal(
154
+ resolvedTarget,
155
+ root,
156
+ symlinkDepth + 1,
157
+ realRoot
158
+ )
159
+ return targetResult.realPath
160
+ } catch (e) {
161
+ if (e instanceof Error) {
162
+ // Re-throw security, root-scope, and depth-limit errors — these must
163
+ // not be swallowed. They indicate genuine validation failures, not
164
+ // the expected "path doesn't exist" case.
165
+ if (
166
+ e.message.includes('outside the allowed root') ||
167
+ e.message.includes('Root path is too broad') ||
168
+ e.message.includes('depth limit exceeded')
169
+ )
170
+ throw e
171
+ }
172
+ if (!isMissingPathError(e)) throw e
173
+ // lstat failed (file doesn't exist at all) — not a symlink
174
+ return undefined
175
+ }
176
+ }
177
+
178
+ async function resolveSafePathInternal(
179
+ filePath: string,
180
+ root: string,
181
+ symlinkDepth: number,
182
+ realRoot?: string
183
+ ): Promise<SafePathResult> {
184
+ if (symlinkDepth >= MAX_SYMLINK_DEPTH) {
185
+ throw new Error(
186
+ `Symlink resolution depth limit exceeded (possible circular symlinks): ${filePath}`
187
+ )
188
+ }
189
+
190
+ const normalizedRoot = resolve(root)
191
+ const resolved = isAbsolute(filePath) ? resolve(filePath) : resolve(normalizedRoot, filePath)
192
+
193
+ if (!realRoot) {
194
+ assertNarrowRoot(root, root)
195
+
196
+ try {
197
+ realRoot = await realpath(root)
198
+ } catch (e) {
199
+ if (!isMissingPathError(e)) throw e
200
+ const { realAncestor, remainder } = await resolveRealAncestor(root)
201
+ realRoot = remainder ? join(realAncestor, remainder.slice(osSep.length)) : realAncestor
202
+ }
203
+
204
+ assertNarrowRoot(realRoot, root)
205
+ }
206
+
207
+ const realSep = realRoot.endsWith('/') || realRoot.endsWith('\\') ? '' : osSep
208
+
209
+ let realPath: string
210
+ try {
211
+ realPath = await realpath(resolved)
212
+ } catch (e) {
213
+ if (!isMissingPathError(e)) throw e
214
+ const symlinkRealPath = await resolveDanglingSymlink(resolved, root, realRoot, symlinkDepth)
215
+ realPath = symlinkRealPath ?? (await resolveRealPath(resolved))
216
+ }
217
+
218
+ if (!realPath.startsWith(realRoot + realSep) && realPath !== realRoot) {
219
+ throw new Error(`Path is outside the allowed root: ${root}`)
220
+ }
221
+ return { resolved, realPath }
222
+ }
223
+
224
+ export async function resolveSafePath(filePath: string, root: string): Promise<SafePathResult> {
225
+ return resolveSafePathInternal(filePath, root, 0)
226
+ }
227
+
228
+ /**
229
+ * The tools whose `path` names a file to write their result to, and the bytes each writes. Other
230
+ * tools' `path` is their own data, such as `create_vector`'s SVG path, and never touches disk.
231
+ */
232
+ const FILE_OUTPUTS: Record<
233
+ string,
234
+ (result: Record<string, unknown>) => string | Uint8Array | null
235
+ > = {
236
+ export_svg: (result) => (typeof result.svg === 'string' ? result.svg : null),
237
+ get_jsx: (result) => (typeof result.jsx === 'string' ? result.jsx : null),
238
+ export_image: (result) =>
239
+ typeof result.base64 === 'string' ? toUint8Array(result.base64) : null,
240
+ export_pdf: (result) => (typeof result.base64 === 'string' ? toUint8Array(result.base64) : null)
241
+ }
242
+
243
+ /** Whether a tool's `path` argument names a file it writes, rather than data of its own. */
244
+ export function writesFileOutput(toolName: string): boolean {
245
+ return toolName in FILE_OUTPUTS
246
+ }
247
+
248
+ /** The largest document `/files` passes either way, as the app caps documents it fetches. */
249
+ export const MAX_FILE_TRANSFER_BYTES = 64 * 1024 * 1024
250
+
251
+ /** Write `content` to a path inside `root`, creating its folders, and return where it landed. */
252
+ export async function writeInsideRoot(
253
+ filePath: string,
254
+ root: string,
255
+ content: string | Uint8Array
256
+ ): Promise<{ written: string; byteLength: number }> {
257
+ const { resolved, realPath } = await resolveSafePath(filePath, root)
258
+ // Use the canonical realPath for filesystem operations to prevent TOCTOU:
259
+ // an attacker could swap a directory component with a symlink between
260
+ // resolveSafePath's validation and the writeFile call. Writing to the
261
+ // realpath-validated path ensures the write lands inside root.
262
+ const parentDir = dirname(realPath)
263
+ await mkdir(parentDir, { recursive: true })
264
+ // TOCTOU mitigation: re-verify the parent directory still resolves inside
265
+ // the root after mkdir. An attacker who replaces an ancestor directory
266
+ // with a symlink between resolveSafePath and the write would be detected
267
+ // here — realpath follows the ancestor symlink and resolves outside root.
268
+ await resolveSafePath(parentDir, root)
269
+ await writeFile(realPath, content)
270
+ await resolveSafePath(realPath, root)
271
+ const byteLength =
272
+ typeof content === 'string' ? Buffer.byteLength(content, 'utf8') : content.byteLength
273
+ return { written: resolved, byteLength }
274
+ }
275
+
276
+ const READ_CHUNK_BYTES = 1024 * 1024
277
+
278
+ /**
279
+ * Read an open file to its end in chunks, refusing it as soon as it passes the cap, so a file
280
+ * that grows while it is read is never buffered whole.
281
+ */
282
+ async function readBounded(handle: FileHandle, name: string): Promise<Uint8Array<ArrayBuffer>> {
283
+ const chunks: Uint8Array[] = []
284
+ let total = 0
285
+ for (;;) {
286
+ const chunk = new Uint8Array(READ_CHUNK_BYTES)
287
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, total)
288
+ if (bytesRead === 0) break
289
+ total += bytesRead
290
+ if (total > MAX_FILE_TRANSFER_BYTES) {
291
+ throw new Error(`"${name}" is larger than ${MAX_FILE_TRANSFER_BYTES} bytes`)
292
+ }
293
+ chunks.push(chunk.subarray(0, bytesRead))
294
+ }
295
+ const bytes = new Uint8Array(total)
296
+ let offset = 0
297
+ for (const chunk of chunks) {
298
+ bytes.set(chunk, offset)
299
+ offset += chunk.length
300
+ }
301
+ return bytes
302
+ }
303
+
304
+ /** Read a file inside `root`, refusing one larger than `MAX_FILE_TRANSFER_BYTES`. */
305
+ export async function readInsideRoot(
306
+ filePath: string,
307
+ root: string
308
+ ): Promise<Uint8Array<ArrayBuffer>> {
309
+ const { realPath } = await resolveSafePath(filePath, root)
310
+ // One descriptor for the checks and the read, so the file cannot be swapped between them; a
311
+ // symlink in its place is refused, and a folder swapped above it is caught by the re-check.
312
+ // Windows has no O_NOFOLLOW (it is undefined there), so only the re-check guards it.
313
+ const handle = await open(realPath, constants.O_RDONLY | constants.O_NOFOLLOW)
314
+ try {
315
+ const stats = await handle.stat()
316
+ if (!stats.isFile()) throw new Error(`"${basename(realPath)}" is not a file`)
317
+ if (stats.size > MAX_FILE_TRANSFER_BYTES) {
318
+ throw new Error(`"${basename(realPath)}" is larger than ${MAX_FILE_TRANSFER_BYTES} bytes`)
319
+ }
320
+ await resolveSafePath(realPath, root)
321
+ return await readBounded(handle, basename(realPath))
322
+ } finally {
323
+ await handle.close()
324
+ }
325
+ }
326
+
327
+ export async function writeToolOutput(
328
+ toolName: string,
329
+ result: Record<string, unknown>,
330
+ filePath: string,
331
+ root: string
332
+ ): Promise<MCPResult | null> {
333
+ const content = FILE_OUTPUTS[toolName]?.(result)
334
+ if (content == null) return null
335
+ return ok(await writeInsideRoot(filePath, root, content))
336
+ }
@@ -0,0 +1,37 @@
1
+ import { compact, uniq } from 'es-toolkit/array'
2
+
3
+ import type { ToolDescriptor, ToolPolicy } from '#mcp/tool/metadata'
4
+ import { isSelectionScopeTool, parseToolScope } from '#mcp/tool/scope'
5
+
6
+ export function parseDisabledTools(value: string | undefined): string[] {
7
+ if (!value) return []
8
+ return uniq(compact(value.split(',').map((name) => name.trim())))
9
+ }
10
+
11
+ export function isToolEnabled(descriptor: ToolDescriptor, policy: ToolPolicy): boolean {
12
+ if (policy.scope === 'selection' && !isSelectionScopeTool(descriptor.name)) return false
13
+ if (policy.disabledTools.includes(descriptor.name)) return false
14
+ return descriptor.availability !== 'eval' || policy.allowEval
15
+ }
16
+
17
+ export function applyToolPolicy(
18
+ descriptors: readonly ToolDescriptor[],
19
+ policy: ToolPolicy
20
+ ): ToolDescriptor[] {
21
+ return descriptors.map((descriptor) => ({
22
+ ...descriptor,
23
+ enabled: isToolEnabled(descriptor, policy)
24
+ }))
25
+ }
26
+
27
+ export function serializeDisabledTools(names: readonly string[]): string {
28
+ return names.join(',')
29
+ }
30
+
31
+ export function readToolPolicyFromEnv(env: NodeJS.ProcessEnv = process.env): ToolPolicy {
32
+ return {
33
+ allowEval: env.PAIRDRAW_MCP_EVAL === '1',
34
+ disabledTools: parseDisabledTools(env.PAIRDRAW_MCP_DISABLED_TOOLS),
35
+ scope: parseToolScope(env.PAIRDRAW_MCP_SCOPE)
36
+ }
37
+ }