@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.
- 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-BdiJUhSs.mjs +3261 -0
- package/dist/server-BdiJUhSs.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 +78 -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 @@
|
|
|
1
|
+
{"version":3,"file":"stdio.mjs","names":[],"sources":["../src/stdio/bridge.ts","../src/stdio.ts"],"sourcesContent":["import { request } from 'node:http'\nimport type { ClientRequest, RequestOptions } from 'node:http'\n\nimport { readDiscoveryFile } from '#mcp/transport/discovery'\nimport { getSocketPath, platformHasUnixSockets } from '#mcp/transport/paths'\n\ntype StdioRPCBridgeOptions = {\n /** Override socket path (if known). Auto-discovered if omitted. */\n socketPath?: string | null\n /** Auth token for /rpc Bearer header. */\n authToken?: string | null\n reconnectDelayMs?: number\n onReady?: () => void\n onReconnect?: () => void\n}\n\n// 35s gives a 5s margin over the worst case (10s app wait + 20s RPC timeout = 30s)\nconst RPC_TIMEOUT = 35_000\nconst DISCONNECTED_MESSAGE =\n 'Pairdraw app is not connected. ' +\n 'STOP and tell the user: \"The Pairdraw desktop app is not running or no document is open. ' +\n 'Please start the app and open a document, then try again.\" ' +\n 'Do NOT attempt to start the app yourself or retry automatically.'\n\ntype TransportMode = 'socket' | 'tcp'\n\n/**\n * Creates an RPC bridge that connects to the MCP server via HTTP\n * over a Unix domain socket.\n *\n * This replaces the previous WebSocket-based bridge with a simpler\n * HTTP approach that natively supports Unix domain sockets.\n */\nexport function createStdioRPCBridge({\n socketPath: socketPathOverride,\n authToken,\n reconnectDelayMs = 2000,\n onReady,\n onReconnect\n}: StdioRPCBridgeOptions) {\n let resolvedSocketPath: string | null = socketPathOverride ?? null\n let resolvedHttpPort: number | null = null\n let transportMode: TransportMode | null = null\n let ready = false\n let wasConnected = false\n let reconnectTimer: ReturnType<typeof setTimeout> | undefined\n let connectPromise: Promise<void> | null = null\n let closed = false\n let authFailure = false\n let socketFailed = false\n\n // Socket path resolution has two tiers:\n // Explicit: socketPathOverride parameter — authoritative pin, never\n // overwritten by discovery during reconnect.\n // Hint: PAIRDRAW_MCP_SOCKET env var — resolved through\n // getSocketPath() and readDiscoveryFile(); NOT treated as\n // explicit, so the bridge can pick up a changed path from the\n // discovery file after a server restart.\n const hasExplicitSocketPath = socketPathOverride !== undefined && socketPathOverride !== null\n // Track whether authToken was explicitly provided by the caller.\n // When false, the token is auto-discovered from the discovery file and\n // can be refreshed transparently on 401 without surfacing the error.\n const hasExplicitAuth = authToken !== undefined\n let resolvedAuthToken: string | null = authToken ?? null\n\n async function resolveAuthToken(): Promise<string | null> {\n if (hasExplicitAuth) return resolvedAuthToken\n if (resolvedAuthToken) return resolvedAuthToken\n const info = await readDiscoveryFile()\n if (info?.authToken) {\n resolvedAuthToken = info.authToken\n }\n return resolvedAuthToken\n }\n\n async function resolveTransport(): Promise<void> {\n // Already resolved\n if (transportMode) return\n\n // Try reading the discovery file\n const info = await readDiscoveryFile()\n\n // When the auth token was not explicitly provided, pick it up from the\n // discovery file whenever we re-read transport info. This ensures the\n // bridge picks up a new server-generated token after a restart without\n // waiting for a 401 response.\n if (!hasExplicitAuth && info?.authToken) {\n resolvedAuthToken = info.authToken\n }\n\n // When no Unix socket is available, prefer TCP via httpPort\n if (!platformHasUnixSockets()) {\n if (info?.httpPort) {\n resolvedHttpPort = info.httpPort\n transportMode = 'tcp'\n return\n }\n throw new Error('No MCP server discovery info found')\n }\n\n // Unix: prefer socket path from discovery file, fall back to default.\n // If no socket is available (TCP-only server), use TCP via httpPort.\n // The socketPath option (when provided directly by the caller) takes\n // precedence and is never overwritten by discovery.\n if (hasExplicitSocketPath && resolvedSocketPath) {\n // Caller explicitly provided a socket path — keep it, never overwrite\n } else if (info?.socketPath) {\n resolvedSocketPath = info.socketPath\n } else if (info?.httpPort) {\n // Server is TCP-only (no socket listener) — use TCP\n resolvedHttpPort = info.httpPort\n transportMode = 'tcp'\n return\n } else {\n resolvedSocketPath = await getSocketPath()\n }\n\n // Also capture httpPort as fallback\n if (info?.httpPort) {\n resolvedHttpPort = info.httpPort\n }\n\n // If the socket previously failed and TCP is available, use TCP\n // instead of retrying the same stale socket indefinitely.\n if (!hasExplicitSocketPath && socketFailed && resolvedHttpPort) {\n transportMode = 'tcp'\n return\n }\n\n transportMode = 'socket'\n }\n\n /**\n * Makes an HTTP request to the MCP server via socket or TCP.\n */\n function httpRequest(\n method: string,\n path: string,\n body?: Record<string, unknown>\n ): Promise<{ status: number; data: unknown; req: ClientRequest }> {\n return new Promise((resolve, reject) => {\n const bodyJSON = body ? JSON.stringify(body) : undefined\n const headers: Record<string, string> = {}\n if (bodyJSON) headers['Content-Type'] = 'application/json'\n if (resolvedAuthToken) headers.Authorization = `Bearer ${resolvedAuthToken}`\n\n let reqOpts: RequestOptions | null = null\n if (transportMode === 'socket' && resolvedSocketPath) {\n reqOpts = { socketPath: resolvedSocketPath, path, method, headers }\n } else if (transportMode === 'tcp' && resolvedHttpPort) {\n reqOpts = { hostname: '127.0.0.1', port: resolvedHttpPort, path, method, headers }\n }\n\n if (!reqOpts) {\n reject(new Error(DISCONNECTED_MESSAGE))\n return\n }\n\n const req = request(reqOpts, (res) => {\n const chunks: Buffer[] = []\n res.on('data', (chunk: Buffer) => chunks.push(chunk))\n res.on('end', () => {\n const raw = Buffer.concat(chunks).toString('utf-8')\n let data: unknown\n try {\n data = JSON.parse(raw)\n } catch {\n data = raw\n }\n resolve({ status: res.statusCode ?? 200, data, req })\n })\n res.on('error', reject)\n })\n\n req.on('error', reject)\n // Socket-level idle timeout to prevent indefinite hangs on\n // unresponsive connections. Set 5s shorter than the outer RPC_TIMEOUT\n // so this fires deterministically first, producing a clear \"server\n // unreachable\" signal rather than racing with the outer timer.\n // If the outer sendRPC timer already rejected, the error handler\n // is a no-op (settled guard in attempt()).\n req.setTimeout(RPC_TIMEOUT - 5_000, () => {\n req.destroy(new Error('Socket timeout'))\n })\n if (bodyJSON) req.write(bodyJSON)\n req.end()\n })\n }\n\n /**\n * Checks if the server is healthy and the browser is connected.\n */\n async function checkHealth(): Promise<{\n reachable: boolean\n appConnected: boolean\n authFailed: boolean\n }> {\n try {\n const { status, data } = await httpRequest('GET', '/health')\n if (status === 401) return { reachable: true, appConnected: false, authFailed: true }\n if (status !== 200) return { reachable: false, appConnected: false, authFailed: false }\n const health = data as { status?: string }\n return {\n reachable: health.status === 'ok' || health.status === 'no_app',\n appConnected: health.status === 'ok',\n authFailed: false\n }\n } catch {\n if (!hasExplicitSocketPath && transportMode === 'socket') socketFailed = true\n return { reachable: false, appConnected: false, authFailed: false }\n }\n }\n\n /**\n * Attempts to connect to the server. Retries with a fixed delay.\n */\n async function connect(): Promise<void> {\n if (closed) return\n try {\n await resolveTransport()\n if (!resolvedAuthToken) await resolveAuthToken()\n } catch {\n connectPromise = null\n scheduleReconnect()\n return\n }\n\n // close() may have been called while we were resolving transport.\n // oxlint-disable-next-line no-unnecessary-condition\n if (closed) return\n\n const { reachable, appConnected, authFailed } = await checkHealth()\n // oxlint-disable-next-line no-unnecessary-condition\n if (closed) return\n if (authFailed) {\n // Auth token is wrong — surface as an auth error rather than a generic\n // disconnect so the caller can prompt for a new token or re-read discovery.\n authFailure = true\n ready = false\n connectPromise = null\n // When using an auto-discovered token, clear it and transportMode so\n // the next reconnect re-reads the discovery file for a fresh token\n // instead of reusing the stale one (which would cause another 401 loop).\n if (!hasExplicitAuth) {\n resolvedAuthToken = null\n transportMode = null\n }\n scheduleReconnect()\n return\n }\n authFailure = false\n if (appConnected) {\n ready = true\n socketFailed = false\n connectPromise = null\n if (wasConnected) {\n onReconnect?.()\n } else {\n wasConnected = true\n onReady?.()\n }\n return\n }\n\n if (reachable) {\n // Server is up — we can send RPC requests and let the server\n // wait for the desktop app to connect.\n ready = true\n socketFailed = false\n connectPromise = null\n if (!wasConnected) {\n wasConnected = true\n onReady?.()\n }\n return\n }\n\n transportMode = null\n if (!hasExplicitSocketPath) resolvedSocketPath = null\n resolvedHttpPort = null\n connectPromise = null\n scheduleReconnect()\n }\n\n function scheduleReconnect() {\n if (closed) return\n clearTimeout(reconnectTimer)\n reconnectTimer = setTimeout(() => {\n connectPromise = connect()\n }, reconnectDelayMs)\n reconnectTimer.unref()\n }\n\n /**\n * Sends an RPC request to the MCP server.\n *\n * Routes through the /rpc HTTP endpoint, which proxies\n * the call to the connected browser.\n *\n * When using an auto-discovered auth token (hasExplicitAuth === false),\n * a 401 response triggers a transparent retry: the cached token is cleared,\n * the discovery file is re-read for a fresh token, and the request is\n * retried once. Only if the retry also fails is the error surfaced to the\n * caller. This makes server restarts with a new auto-generated token\n * seamless to the AI agent.\n */\n function sendRPC(body: Record<string, unknown>): Promise<unknown> {\n // If not ready, await the in-flight connect() promise first — the\n // bridge may still be resolving transport. Only reject after that\n // completes and we're still not ready.\n const awaitReady = async (): Promise<void> => {\n if (!ready && connectPromise) await connectPromise\n if (authFailure) throw new Error('Unauthorized: check PAIRDRAW_MCP_AUTH_TOKEN')\n if (!ready) throw new Error(DISCONNECTED_MESSAGE)\n }\n\n return awaitReady().then(\n () =>\n new Promise((resolve, reject) => {\n let settled = false\n const timer = setTimeout(() => {\n if (settled) return\n settled = true\n reject(new Error(`RPC timeout (${Math.round(RPC_TIMEOUT / 1000)}s)`))\n }, RPC_TIMEOUT)\n\n /**\n * Performs one HTTP request attempt. `allowAuthRetry` controls whether\n * a 401 with an auto-discovered token triggers a re-read and retry.\n * It is set to `false` for the second attempt to prevent infinite loops.\n */\n function attempt(allowAuthRetry: boolean) {\n httpRequest('POST', '/rpc', body)\n .then(({ status, data, req }) => {\n // If the overall RPC timeout fired while the request was in-flight,\n // the server may have already executed the tool. Destroying the\n // request only closes the TCP socket — it does not roll back any\n // server-side mutation. Callers must not assume that a timeout\n // means the operation was not executed.\n if (settled) {\n req.destroy()\n return undefined\n }\n\n if (status === 401) {\n if (allowAuthRetry && !hasExplicitAuth) {\n // Auto-discovered token may have rotated — re-read the\n // discovery file for a fresh token and retry transparently.\n // IMPORTANT: Do NOT clear the timer here — the retry must\n // still be protected by the overall 35-second timeout.\n resolvedAuthToken = null\n void readDiscoveryFile()\n .then((info) => {\n if (settled) return undefined\n if (info?.authToken) {\n resolvedAuthToken = info.authToken\n // Keep existing transport mode (socket path / port\n // doesn't change on server restart — only the token\n // does). Retry exactly once with the new token.\n attempt(false)\n return undefined\n }\n clearTimeout(timer)\n authFailure = true\n transportMode = null\n if (!hasExplicitSocketPath) resolvedSocketPath = null\n resolvedHttpPort = null\n ready = false\n settled = true\n scheduleReconnect()\n reject(new Error('Unauthorized'))\n return undefined\n })\n .catch(() => {\n if (settled) return\n clearTimeout(timer)\n // Discovery read failed — stale transport state must be\n // discarded so the bridge re-resolves on reconnect.\n transportMode = null\n if (!hasExplicitSocketPath) resolvedSocketPath = null\n resolvedHttpPort = null\n ready = false\n settled = true\n scheduleReconnect()\n reject(new Error(DISCONNECTED_MESSAGE))\n })\n return undefined\n }\n\n // Explicit token was rejected (config error), or auto-retry\n // already failed — surface the error immediately.\n clearTimeout(timer)\n authFailure = true\n if (!hasExplicitAuth) {\n resolvedAuthToken = null\n }\n transportMode = null\n // Clear auto-discovered transport params so resolveTransport()\n // picks up fresh values from the discovery file on reconnect.\n if (!hasExplicitSocketPath) resolvedSocketPath = null\n resolvedHttpPort = null\n ready = false\n settled = true\n scheduleReconnect()\n reject(new Error('Unauthorized: check PAIRDRAW_MCP_AUTH_TOKEN'))\n return undefined\n }\n\n clearTimeout(timer)\n\n if (status >= 400) {\n const errData = data as { error?: string }\n settled = true\n reject(new Error(errData.error ?? `RPC failed with status ${status}`))\n return undefined\n }\n settled = true\n resolve(data)\n return undefined\n })\n .catch(() => {\n if (settled) return\n clearTimeout(timer)\n if (!hasExplicitSocketPath && transportMode === 'socket') {\n socketFailed = true\n }\n transportMode = null\n // Clear auto-discovered transport params so resolveTransport()\n // picks up fresh values from the discovery file on reconnect.\n if (!hasExplicitSocketPath) resolvedSocketPath = null\n resolvedHttpPort = null\n ready = false\n settled = true\n scheduleReconnect()\n reject(new Error(DISCONNECTED_MESSAGE))\n })\n }\n\n attempt(true)\n })\n )\n }\n\n /**\n * Stops the reconnect timer and marks the bridge as not ready.\n * Call this to cleanly shut down the bridge and prevent timer leaks.\n */\n function close(): void {\n closed = true\n clearTimeout(reconnectTimer)\n reconnectTimer = undefined\n ready = false\n connectPromise = null\n }\n\n // Start connection\n connectPromise = connect()\n\n return { sendRPC, close }\n}\n","#!/usr/bin/env node\nimport { randomUUID } from 'node:crypto'\n\nimport { McpServer } from '@modelcontextprotocol/server'\nimport { StdioServerTransport } from '@modelcontextprotocol/server/stdio'\n\nimport { resolveMCPRoot } from '#mcp/root'\nimport { MCP_VERSION, registerTools } from '#mcp/server'\nimport { createServerInstructions } from '#mcp/skill/instructions'\nimport { registerSkill } from '#mcp/skill/register'\nimport { createStdioRPCBridge } from '#mcp/stdio/bridge'\nimport type { ToolPolicy } from '#mcp/tool/metadata'\nimport { parseDisabledTools } from '#mcp/tool/policy'\nimport { narrowestScope, parseToolScope } from '#mcp/tool/scope'\nimport { readDiscoveryFile } from '#mcp/transport/discovery'\n\nif (process.argv.includes('--version')) {\n process.stdout.write(`${MCP_VERSION}\\n`)\n process.exit(0)\n}\n\nif (process.argv.includes('--help') || process.argv.includes('-h')) {\n process.stdout.write(\n `pairdraw-mcp\\n\\n` +\n `Start the Pairdraw MCP stdio bridge.\\n\\n` +\n `Connects to the MCP server via Unix domain socket on macOS/Linux ` +\n `(with TCP fallback) or via TCP on Windows.\\n` +\n `The MCP server is started by the Pairdraw\\n` +\n `desktop app; this bridge only forwards stdio JSON-RPC to it.\\n\\n` +\n `Options:\\n` +\n ` --help, -h Show this help message\\n` +\n ` --version Print the version\\n\\n` +\n `Environment variables:\\n` +\n ` PAIRDRAW_MCP_SOCKET Override socket path (auto-discovered from discovery file when unset)\\n` +\n ` PAIRDRAW_MCP_AUTH_TOKEN Bearer token for RPC auth\\n` +\n ` PAIRDRAW_MCP_ROOT Allowed directory for file-scoped tools\\n` +\n ` (default: home directory on Windows, cwd elsewhere)\\n` +\n ` PAIRDRAW_MCP_EVAL Set to 1 to enable the eval tool\\n` +\n ` PAIRDRAW_MCP_DISABLED_TOOLS Comma-separated tool names to omit; defaults to the app setting\\n` +\n ` PAIRDRAW_MCP_SCOPE \"selection\" to read only the selected layers; defaults to the app setting\\n`\n )\n process.exit(0)\n}\n\nconst discovery = await readDiscoveryFile()\nconst toolPolicy: ToolPolicy = {\n allowEval: process.env.PAIRDRAW_MCP_EVAL === '1',\n disabledTools:\n process.env.PAIRDRAW_MCP_DISABLED_TOOLS === undefined\n ? (discovery?.disabledTools ?? [])\n : parseDisabledTools(process.env.PAIRDRAW_MCP_DISABLED_TOOLS),\n // The server enforces its own scope on every call; this keeps the tool list in step with it,\n // and lets the client limit itself further.\n scope: narrowestScope(\n discovery?.scope ?? 'document',\n parseToolScope(process.env.PAIRDRAW_MCP_SCOPE)\n )\n}\nconst mcpRoot = resolveMCPRoot(process.env.PAIRDRAW_MCP_ROOT)\n// Auth token: undefined → auto-discover from discovery file, empty string →\n// disable auth, whitespace-only → reject (same fail-fast as index.ts to catch\n// misconfiguration), otherwise → use the trimmed value.\nconst rawAuthToken = process.env.PAIRDRAW_MCP_AUTH_TOKEN\nif (rawAuthToken !== undefined && rawAuthToken !== '' && rawAuthToken.trim() === '') {\n process.stderr.write(\n 'Error: PAIRDRAW_MCP_AUTH_TOKEN is whitespace-only. Set a real token, or use an empty string to disable auth.\\n'\n )\n process.exit(1)\n}\nfunction resolveAuthToken(raw: string | undefined): string | null | undefined {\n if (raw === undefined) return undefined\n if (raw === '') return null\n return raw.trim()\n}\nconst authToken = resolveAuthToken(rawAuthToken)\n\n// PAIRDRAW_MCP_SOCKET is intentionally NOT forwarded as an explicit socketPath.\n// The bridge reads the socket path from the discovery file (whose `socketPath`\n// field records the override) via auto-discovery. Treating the env var as an\n// explicit pin would prevent the bridge from following discovery updates after\n// a server restart.\nconst bridge = createStdioRPCBridge({\n authToken,\n onReady: () => {\n process.stderr.write(\n 'Connected to Pairdraw MCP server; document availability is checked per tool call\\n'\n )\n },\n onReconnect: () => {\n process.stderr.write(\n 'Reconnected to Pairdraw MCP server; document availability is checked per tool call\\n'\n )\n }\n})\n\nconst mcpServer = new McpServer(\n { name: 'pairdraw', version: MCP_VERSION },\n {\n instructions: createServerInstructions({\n policy: toolPolicy,\n filesystemEnabled: Boolean(mcpRoot),\n agentKind: 'mcp'\n })\n }\n)\n// One client per process: its tool calls show as one agent in the app.\nregisterTools(mcpServer, {\n policy: toolPolicy,\n mcpRoot,\n sendRPC: bridge.sendRPC,\n agentSession: { id: randomUUID(), kind: 'mcp' }\n})\nregisterSkill(mcpServer)\n\nconst transport = new StdioServerTransport()\nmcpServer.connect(transport).catch((err) => {\n process.stderr.write(`Fatal: MCP connect failed — ${err instanceof Error ? err.message : err}\\n`)\n process.exit(1)\n})\n\nprocess.on('uncaughtException', (err) => {\n process.stderr.write(`Fatal: ${err instanceof Error ? err.message : err}\\n`)\n process.exit(1)\n})\n\nprocess.on('unhandledRejection', (reason: unknown) => {\n const message = reason instanceof Error ? reason.message : String(reason)\n process.stderr.write(`Fatal: unhandled rejection — ${message}\\n`)\n process.exit(1)\n})\n"],"mappings":";;;;;;;;;;;;;AAiBA,MAAM,cAAc;AACpB,MAAM,uBACJ;;;;;;;;AAcF,SAAgB,qBAAqB,EACnC,YAAY,oBACZ,WACA,mBAAmB,KACnB,SACA,eACwB;CACxB,IAAI,qBAAoC,sBAAsB;CAC9D,IAAI,mBAAkC;CACtC,IAAI,gBAAsC;CAC1C,IAAI,QAAQ;CACZ,IAAI,eAAe;CACnB,IAAI;CACJ,IAAI,iBAAuC;CAC3C,IAAI,SAAS;CACb,IAAI,cAAc;CAClB,IAAI,eAAe;CASnB,MAAM,wBAAwB,uBAAuB,UAAa,uBAAuB;CAIzF,MAAM,kBAAkB,cAAc;CACtC,IAAI,oBAAmC,aAAa;CAEpD,eAAe,mBAA2C;EACxD,IAAI,iBAAiB,OAAO;EAC5B,IAAI,mBAAmB,OAAO;EAC9B,MAAM,OAAO,MAAM,kBAAkB;EACrC,IAAI,MAAM,WACR,oBAAoB,KAAK;EAE3B,OAAO;CACT;CAEA,eAAe,mBAAkC;EAE/C,IAAI,eAAe;EAGnB,MAAM,OAAO,MAAM,kBAAkB;EAMrC,IAAI,CAAC,mBAAmB,MAAM,WAC5B,oBAAoB,KAAK;EAI3B,IAAI,CAAC,uBAAuB,GAAG;GAC7B,IAAI,MAAM,UAAU;IAClB,mBAAmB,KAAK;IACxB,gBAAgB;IAChB;GACF;GACA,MAAM,IAAI,MAAM,oCAAoC;EACtD;EAMA,IAAI,yBAAyB,oBAAoB,CAEjD,OAAO,IAAI,MAAM,YACf,qBAAqB,KAAK;OACrB,IAAI,MAAM,UAAU;GAEzB,mBAAmB,K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AChB,CAAC;AAED,QAAQ,GAAG,sBAAsB,QAAQ;CACvC,QAAQ,OAAO,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,IAAI,GAAG;CAC3E,QAAQ,KAAK,CAAC;AAChB,CAAC;AAED,QAAQ,GAAG,uBAAuB,WAAoB;CACpD,MAAM,UAAU,kBAAkB,QAAQ,OAAO,UAAU,OAAO,MAAM;CACxE,QAAQ,OAAO,MAAM,gCAAgC,QAAQ,GAAG;CAChE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
package/dist/tools.d.mts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import "./rolldown-runtime-ClRpJifh.mjs";
|
|
2
|
+
import { a as isSelectionScopeTool, i as SELECTION_SCOPE_TOOLS, n as MCP_TOOL_SCOPES, o as narrowestScope, r as SELECTION_SCOPE_FILE_OUTPUT_ERROR, s as parseToolScope, t as MCPToolScope } from "./scope-DJ9hsBYV.mjs";
|
|
3
|
+
import { a as parseToolDescriptor, i as ToolPolicy, n as ToolDescriptor, r as ToolEffect, t as ToolAvailability } from "./metadata-DVz00c8R.mjs";
|
|
4
|
+
import { ToolDef } from "@pairdraw/core/tools";
|
|
5
|
+
//#region src/tool/manifest.d.ts
|
|
6
|
+
declare function getMCPToolDefinitions(): ToolDef[];
|
|
7
|
+
declare function createToolDescriptors(filesystemEnabled: boolean): ToolDescriptor[];
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region src/tool/policy.d.ts
|
|
10
|
+
declare function parseDisabledTools(value: string | undefined): string[];
|
|
11
|
+
declare function isToolEnabled(descriptor: ToolDescriptor, policy: ToolPolicy): boolean;
|
|
12
|
+
declare function applyToolPolicy(descriptors: readonly ToolDescriptor[], policy: ToolPolicy): ToolDescriptor[];
|
|
13
|
+
declare function serializeDisabledTools(names: readonly string[]): string;
|
|
14
|
+
declare function readToolPolicyFromEnv(env?: NodeJS.ProcessEnv): ToolPolicy;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { type MCPToolScope, MCP_TOOL_SCOPES, SELECTION_SCOPE_FILE_OUTPUT_ERROR, SELECTION_SCOPE_TOOLS, ToolAvailability, ToolDescriptor, ToolEffect, ToolPolicy, createToolDescriptors, isSelectionScopeTool, isToolEnabled, narrowestScope, parseToolDescriptor, parseToolScope, serializeDisabledTools };
|
|
17
|
+
//# sourceMappingURL=tools.d.mts.map
|
package/dist/tools.mjs
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import "./rolldown-runtime-ClRpJifh.mjs";
|
|
2
|
+
import { a as serializeDisabledTools, n as isToolEnabled, o as createToolDescriptors } from "./policy-B8Ka4WRH.mjs";
|
|
3
|
+
import { a as narrowestScope, i as isSelectionScopeTool, n as SELECTION_SCOPE_FILE_OUTPUT_ERROR, o as parseToolScope, r as SELECTION_SCOPE_TOOLS, t as MCP_TOOL_SCOPES } from "./scope-D2LTTsDw.mjs";
|
|
4
|
+
import * as v from "valibot";
|
|
5
|
+
const toolDescriptorSchema = v.object({
|
|
6
|
+
name: v.pipe(v.string(), v.minLength(1)),
|
|
7
|
+
description: v.string(),
|
|
8
|
+
effect: v.picklist(["read", "write"]),
|
|
9
|
+
availability: v.picklist([
|
|
10
|
+
"default",
|
|
11
|
+
"eval",
|
|
12
|
+
"filesystem"
|
|
13
|
+
]),
|
|
14
|
+
capabilities: v.array(v.picklist([
|
|
15
|
+
"document:read",
|
|
16
|
+
"document:write",
|
|
17
|
+
"filesystem:read",
|
|
18
|
+
"filesystem:write",
|
|
19
|
+
"network:access",
|
|
20
|
+
"code:execute",
|
|
21
|
+
"settings:read",
|
|
22
|
+
"settings:write"
|
|
23
|
+
])),
|
|
24
|
+
enabled: v.boolean()
|
|
25
|
+
});
|
|
26
|
+
function parseToolDescriptor(value) {
|
|
27
|
+
const parsed = v.safeParse(toolDescriptorSchema, value);
|
|
28
|
+
return parsed.success ? parsed.output : null;
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
export { MCP_TOOL_SCOPES, SELECTION_SCOPE_FILE_OUTPUT_ERROR, SELECTION_SCOPE_TOOLS, createToolDescriptors, isSelectionScopeTool, isToolEnabled, narrowestScope, parseToolDescriptor, parseToolScope, serializeDisabledTools };
|
|
32
|
+
|
|
33
|
+
//# sourceMappingURL=tools.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tools.mjs","names":[],"sources":["../src/tool/metadata.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { ToolCapability } from '@pairdraw/core/tools'\n\nimport type { MCPToolScope } from '#mcp/tool/scope'\n\nconst TOOL_EFFECTS = ['read', 'write'] as const\nconst TOOL_AVAILABILITIES = ['default', 'eval', 'filesystem'] as const\nconst TOOL_CAPABILITIES = [\n 'document:read',\n 'document:write',\n 'filesystem:read',\n 'filesystem:write',\n 'network:access',\n 'code:execute',\n 'settings:read',\n 'settings:write'\n] as const satisfies readonly ToolCapability[]\n\nexport type ToolEffect = (typeof TOOL_EFFECTS)[number]\nexport type ToolAvailability = (typeof TOOL_AVAILABILITIES)[number]\n\nconst toolDescriptorSchema = v.object({\n name: v.pipe(v.string(), v.minLength(1)),\n description: v.string(),\n effect: v.picklist(TOOL_EFFECTS),\n availability: v.picklist(TOOL_AVAILABILITIES),\n capabilities: v.array(v.picklist(TOOL_CAPABILITIES)),\n enabled: v.boolean()\n})\n\nexport type ToolDescriptor = v.InferOutput<typeof toolDescriptorSchema>\n\nexport interface ToolPolicy {\n allowEval: boolean\n disabledTools: string[]\n /** What clients can reach; see `MCPToolScope`. */\n scope: MCPToolScope\n}\n\nexport function parseToolDescriptor(value: unknown): ToolDescriptor | null {\n const parsed = v.safeParse(toolDescriptorSchema, value)\n return parsed.success ? parsed.output : null\n}\n"],"mappings":";;;;AAsBA,MAAM,uBAAuB,EAAE,OAAO;CACpC,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,UAAU,CAAC,CAAC;CACvC,aAAa,EAAE,OAAO;CACtB,QAAQ,EAAE,SAAS,CAnBC,QAAQ,OAmBT,CAAY;CAC/B,cAAc,EAAE,SAAS;EAnBE;EAAW;EAAQ;CAmBrB,CAAmB;CAC5C,cAAc,EAAE,MAAM,EAAE,SAAS;EAlBjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAWiC,CAAiB,CAAC;CACnD,SAAS,EAAE,QAAQ;AACrB,CAAC;AAWD,SAAgB,oBAAoB,OAAuC;CACzE,MAAM,SAAS,EAAE,UAAU,sBAAsB,KAAK;CACtD,OAAO,OAAO,UAAU,OAAO,SAAS;AAC1C"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import "./rolldown-runtime-ClRpJifh.mjs";
|
|
2
|
+
//#region src/transport/paths.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Returns the directory for the MCP socket file.
|
|
5
|
+
*
|
|
6
|
+
* When PAIRDRAW_MCP_SOCKET is set, its dirname is used as the socket
|
|
7
|
+
* directory. When unset, the platform default from getPlatformDir() is used.
|
|
8
|
+
* Creates the directory (with restrictive permissions) if it does not exist.
|
|
9
|
+
*
|
|
10
|
+
* NOTE: The discovery file always lives at getPlatformDir(), regardless of
|
|
11
|
+
* PAIRDRAW_MCP_SOCKET. This function should NOT be used to locate it.
|
|
12
|
+
*/
|
|
13
|
+
declare function getSocketDir(): Promise<string>;
|
|
14
|
+
/**
|
|
15
|
+
* Returns the full path to the MCP Unix domain socket.
|
|
16
|
+
*
|
|
17
|
+
* On macOS/Linux: <socketDir>/mcp.sock
|
|
18
|
+
*
|
|
19
|
+
* When PAIRDRAW_MCP_SOCKET is set, its value is returned directly
|
|
20
|
+
* (no directory resolution needed).
|
|
21
|
+
*/
|
|
22
|
+
declare function getSocketPath(): Promise<string>;
|
|
23
|
+
/**
|
|
24
|
+
* Returns the full path to the MCP discovery JSON file.
|
|
25
|
+
*
|
|
26
|
+
* The discovery file lives at the platform-default location so clients can
|
|
27
|
+
* find it without knowing whether PAIRDRAW_MCP_SOCKET is set. It contains
|
|
28
|
+
* the actual socket path (which may be overridden) in its `socketPath` field,
|
|
29
|
+
* so clients read the discovery file to learn where to connect — not the other
|
|
30
|
+
* way around.
|
|
31
|
+
*
|
|
32
|
+
* Set PAIRDRAW_MCP_DISCOVERY_PATH to relocate the discovery file (e.g. to a
|
|
33
|
+
* temp directory for test isolation). The desktop app reads the platform
|
|
34
|
+
* default via its own path computation (src/app/automation/mcp/spawn.ts) and
|
|
35
|
+
* does not honor this override, so it is primarily useful for tests and
|
|
36
|
+
* standalone server invocations. The parent directory is created (0o700) so
|
|
37
|
+
* writeDiscoveryFile's atomic temp-then-rename succeeds.
|
|
38
|
+
*/
|
|
39
|
+
declare function getDiscoveryPath(): Promise<string>;
|
|
40
|
+
/** The private folder (0700) the companion keeps its pairing pages in, beside the discovery file. */
|
|
41
|
+
declare function getCompanionDir(): Promise<string>;
|
|
42
|
+
/**
|
|
43
|
+
* The folder coding agents start in when the companion runs them, beside the discovery file and
|
|
44
|
+
* outside the person's projects, whose settings an agent would otherwise read.
|
|
45
|
+
*/
|
|
46
|
+
declare function getAgentWorkspacePath(): Promise<string>;
|
|
47
|
+
/**
|
|
48
|
+
* Returns true if the current platform supports Unix domain sockets.
|
|
49
|
+
* Unix domain sockets are available on macOS, Linux, and other POSIX
|
|
50
|
+
* platforms but not on native Windows. WSL is detected as Linux.
|
|
51
|
+
*/
|
|
52
|
+
declare function platformHasUnixSockets(): boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Returns the platform name for display purposes.
|
|
55
|
+
*/
|
|
56
|
+
declare function platformName(): 'macos' | 'linux' | 'windows' | 'other';
|
|
57
|
+
//#endregion
|
|
58
|
+
export { getAgentWorkspacePath, getCompanionDir, getDiscoveryPath, getSocketDir, getSocketPath, platformHasUnixSockets, platformName };
|
|
59
|
+
//# sourceMappingURL=transport.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as getSocketPath, i as getSocketDir, n as getCompanionDir, o as platformHasUnixSockets, r as getDiscoveryPath, s as platformName, t as getAgentWorkspacePath } from "./paths-BpcXnrbP.mjs";
|
|
2
|
+
export { getAgentWorkspacePath, getCompanionDir, getDiscoveryPath, getSocketDir, getSocketPath, platformHasUnixSockets, platformName };
|
package/package.json
CHANGED
|
@@ -1,6 +1,80 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pairdraw/mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.16.1",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"files": [
|
|
6
|
+
"dist",
|
|
7
|
+
"src"
|
|
8
|
+
],
|
|
9
|
+
"main": "./dist/server.mjs",
|
|
10
|
+
"bin": {
|
|
11
|
+
"pairdraw-mcp": "./dist/stdio.mjs",
|
|
12
|
+
"pairdraw-mcp-http": "./dist/index.mjs",
|
|
13
|
+
"pairdraw-connect": "./dist/connect.mjs"
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"@hono/node-server": "^1.19.17",
|
|
17
|
+
"@modelcontextprotocol/server": "^2.0.0",
|
|
18
|
+
"@pairdraw/core": "^0.16.1",
|
|
19
|
+
"@valibot/to-json-schema": "^1.8.0",
|
|
20
|
+
"es-toolkit": "^1.52.0",
|
|
21
|
+
"hono": "^4.13.13",
|
|
22
|
+
"js-base64": "^3.9.3",
|
|
23
|
+
"package-manager-detector": "^1.8.0",
|
|
24
|
+
"valibot": "^1.5.0",
|
|
25
|
+
"ws": "^8.21.3"
|
|
26
|
+
},
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/server.d.mts",
|
|
30
|
+
"import": "./dist/server.mjs",
|
|
31
|
+
"default": "./dist/server.mjs"
|
|
32
|
+
},
|
|
33
|
+
"./stdio": {
|
|
34
|
+
"types": "./dist/stdio.d.mts",
|
|
35
|
+
"import": "./dist/stdio.mjs",
|
|
36
|
+
"default": "./dist/stdio.mjs"
|
|
37
|
+
},
|
|
38
|
+
"./transport": {
|
|
39
|
+
"types": "./dist/transport.d.mts",
|
|
40
|
+
"import": "./dist/transport.mjs",
|
|
41
|
+
"default": "./dist/transport.mjs"
|
|
42
|
+
},
|
|
43
|
+
"./discovery": {
|
|
44
|
+
"types": "./dist/discovery.d.mts",
|
|
45
|
+
"import": "./dist/discovery.mjs",
|
|
46
|
+
"default": "./dist/discovery.mjs"
|
|
47
|
+
},
|
|
48
|
+
"./tools": {
|
|
49
|
+
"types": "./dist/tools.d.mts",
|
|
50
|
+
"import": "./dist/tools.mjs",
|
|
51
|
+
"default": "./dist/tools.mjs"
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"imports": {
|
|
55
|
+
"#mcp/*": {
|
|
56
|
+
"types": "./src/*.ts",
|
|
57
|
+
"default": "./dist/*.mjs"
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
"description": "Model Context Protocol server for Pairdraw: inspect and edit designs over stdio or HTTP, and run coding agents for the web app.",
|
|
61
|
+
"keywords": [
|
|
62
|
+
"pairdraw",
|
|
63
|
+
"mcp",
|
|
64
|
+
"model-context-protocol",
|
|
65
|
+
"ai",
|
|
66
|
+
"agents",
|
|
67
|
+
"design"
|
|
68
|
+
],
|
|
69
|
+
"author": "Badryansah Bangsawan",
|
|
70
|
+
"homepage": "https://github.com/BadryansahBangsawan/pairdraw/tree/main/packages/mcp#readme",
|
|
71
|
+
"bugs": {
|
|
72
|
+
"url": "https://github.com/BadryansahBangsawan/pairdraw/issues"
|
|
73
|
+
},
|
|
74
|
+
"repository": {
|
|
75
|
+
"type": "git",
|
|
76
|
+
"url": "git+https://github.com/BadryansahBangsawan/pairdraw.git",
|
|
77
|
+
"directory": "packages/mcp"
|
|
78
|
+
},
|
|
79
|
+
"type": "module"
|
|
80
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { ChildProcess } from 'node:child_process'
|
|
2
|
+
|
|
3
|
+
import type { RawData, WebSocket } from 'ws'
|
|
4
|
+
|
|
5
|
+
import { ProgramNotFoundError, spawnFixed, terminate } from './process'
|
|
6
|
+
import type { CompanionAgent } from './registry'
|
|
7
|
+
import { CLOSE_CODES, rawBytes, sendJSON } from './socket'
|
|
8
|
+
|
|
9
|
+
/** Stop reading the agent's output while this much is waiting to reach the app. */
|
|
10
|
+
const OUTPUT_HIGH_WATER_BYTES = 8 * 1024 * 1024
|
|
11
|
+
const OUTPUT_LOW_WATER_BYTES = 1024 * 1024
|
|
12
|
+
/** The agent's diagnostic output the app sees; the rest is dropped. */
|
|
13
|
+
const MAX_STDERR_BYTES = 64 * 1024
|
|
14
|
+
const MAX_STDERR_CHUNK = 4 * 1024
|
|
15
|
+
|
|
16
|
+
export interface AgentProcessContext {
|
|
17
|
+
workspace: string
|
|
18
|
+
searchPath: string
|
|
19
|
+
/** Tracks the process so shutting the companion down stops it. */
|
|
20
|
+
track(child: ChildProcess): void
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface AgentPipeContext extends AgentProcessContext {
|
|
24
|
+
/** Rewrites what the app sends the agent; null closes the socket (`createACPFilter`). */
|
|
25
|
+
filter(chunk: Buffer): Buffer | null
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Starts an agent's ACP program for one authenticated socket and pipes its stdio as binary
|
|
30
|
+
* frames: frames from the app go to the program's stdin through `filter`, its stdout comes back.
|
|
31
|
+
* The program's command line is the registry's, and it runs in the companion's workspace.
|
|
32
|
+
* Closing the socket stops the program; the program exiting closes the socket.
|
|
33
|
+
*/
|
|
34
|
+
export function pipeAgent(ws: WebSocket, agent: CompanionAgent, context: AgentPipeContext): void {
|
|
35
|
+
// The socket may have closed while the workspace was prepared; nothing would stop the agent.
|
|
36
|
+
if (ws.readyState !== ws.OPEN) return
|
|
37
|
+
let child: ChildProcess
|
|
38
|
+
try {
|
|
39
|
+
child = spawnFixed(agent.command, agent.args, {
|
|
40
|
+
cwd: context.workspace,
|
|
41
|
+
searchPath: context.searchPath,
|
|
42
|
+
stdio: ['pipe', 'pipe', 'pipe']
|
|
43
|
+
})
|
|
44
|
+
} catch (error) {
|
|
45
|
+
const notFound = error instanceof ProgramNotFoundError
|
|
46
|
+
sendJSON(ws, {
|
|
47
|
+
type: 'error',
|
|
48
|
+
reason: notFound ? 'not-found' : 'spawn',
|
|
49
|
+
command: agent.command
|
|
50
|
+
})
|
|
51
|
+
ws.close(notFound ? CLOSE_CODES.notFound : CLOSE_CODES.failed, 'Agent did not start')
|
|
52
|
+
return
|
|
53
|
+
}
|
|
54
|
+
context.track(child)
|
|
55
|
+
const { stdin, stdout, stderr } = child
|
|
56
|
+
if (!stdin || !stdout || !stderr) {
|
|
57
|
+
void terminate(child)
|
|
58
|
+
ws.close(CLOSE_CODES.failed, 'Agent did not start')
|
|
59
|
+
return
|
|
60
|
+
}
|
|
61
|
+
let stderrSent = 0
|
|
62
|
+
|
|
63
|
+
child.once('spawn', () => sendJSON(ws, { type: 'ready' }))
|
|
64
|
+
child.once('error', () => {
|
|
65
|
+
sendJSON(ws, { type: 'error', reason: 'spawn', command: agent.command })
|
|
66
|
+
if (ws.readyState === ws.OPEN) ws.close(CLOSE_CODES.failed, 'Agent did not start')
|
|
67
|
+
})
|
|
68
|
+
// `close` comes after the output streams end, so nothing the agent printed is cut off.
|
|
69
|
+
child.once('close', (code, signal) => {
|
|
70
|
+
sendJSON(ws, { type: 'exit', code, signal })
|
|
71
|
+
if (ws.readyState === ws.OPEN) ws.close(1000, 'Agent exited')
|
|
72
|
+
})
|
|
73
|
+
// A program that exits while the app writes must not crash the companion.
|
|
74
|
+
stdin.on('error', () => undefined)
|
|
75
|
+
|
|
76
|
+
stdout.on('data', (chunk: Buffer) => {
|
|
77
|
+
if (ws.readyState !== ws.OPEN) return
|
|
78
|
+
ws.send(chunk, { binary: true }, () => {
|
|
79
|
+
if (stdout.isPaused() && ws.bufferedAmount < OUTPUT_LOW_WATER_BYTES) stdout.resume()
|
|
80
|
+
})
|
|
81
|
+
if (ws.bufferedAmount > OUTPUT_HIGH_WATER_BYTES) stdout.pause()
|
|
82
|
+
})
|
|
83
|
+
stderr.on('data', (chunk: Buffer) => {
|
|
84
|
+
if (stderrSent >= MAX_STDERR_BYTES) return
|
|
85
|
+
const text = chunk.subarray(0, MAX_STDERR_CHUNK).toString('utf8')
|
|
86
|
+
stderrSent += text.length
|
|
87
|
+
sendJSON(ws, { type: 'stderr', text })
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
ws.on('message', (data: RawData, isBinary: boolean) => {
|
|
91
|
+
// After authenticating, the socket carries only the agent's bytes.
|
|
92
|
+
if (!isBinary) {
|
|
93
|
+
ws.close(CLOSE_CODES.unsupported, 'Binary frames only')
|
|
94
|
+
return
|
|
95
|
+
}
|
|
96
|
+
const bytes = context.filter(rawBytes(data))
|
|
97
|
+
if (bytes === null) {
|
|
98
|
+
ws.close(CLOSE_CODES.unsupported, 'Not an ACP message')
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
if (bytes.length > 0 && !stdin.write(bytes)) {
|
|
102
|
+
ws.pause()
|
|
103
|
+
stdin.once('drain', () => ws.resume())
|
|
104
|
+
}
|
|
105
|
+
})
|
|
106
|
+
ws.once('close', () => {
|
|
107
|
+
stdin.end()
|
|
108
|
+
void terminate(child)
|
|
109
|
+
})
|
|
110
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises'
|
|
2
|
+
import { homedir, platform } from 'node:os'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
import * as v from 'valibot'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Which cloud Claude Code is set up to use instead of an Anthropic sign-in: Amazon Bedrock,
|
|
9
|
+
* Google Vertex AI, or Microsoft Foundry, chosen by `CLAUDE_CODE_USE_*` switches. The desktop
|
|
10
|
+
* shell reads the same switches in `desktop/src/agents/claude_cloud.rs`.
|
|
11
|
+
*/
|
|
12
|
+
export type ClaudeCodeCloud = 'bedrock' | 'vertex' | 'foundry'
|
|
13
|
+
|
|
14
|
+
/** The switches in the order Claude Code checks them. */
|
|
15
|
+
const SWITCHES = [
|
|
16
|
+
['CLAUDE_CODE_USE_BEDROCK', 'bedrock'],
|
|
17
|
+
['CLAUDE_CODE_USE_VERTEX', 'vertex'],
|
|
18
|
+
['CLAUDE_CODE_USE_FOUNDRY', 'foundry']
|
|
19
|
+
] as const satisfies readonly (readonly [string, ClaudeCodeCloud])[]
|
|
20
|
+
|
|
21
|
+
type SwitchName = (typeof SWITCHES)[number][0]
|
|
22
|
+
|
|
23
|
+
/** Reads one variable from a place Claude Code takes its switches from. */
|
|
24
|
+
export type SwitchSource = (name: SwitchName) => string | undefined
|
|
25
|
+
|
|
26
|
+
const switchValueSchema = v.union([
|
|
27
|
+
v.string(),
|
|
28
|
+
v.pipe(v.boolean(), v.toString()),
|
|
29
|
+
v.pipe(v.number(), v.toString())
|
|
30
|
+
])
|
|
31
|
+
|
|
32
|
+
// Only the switches are kept; other variables, which may hold keys, are dropped while parsing.
|
|
33
|
+
const claudeSettingsSchema = v.object({
|
|
34
|
+
env: v.optional(
|
|
35
|
+
v.object({
|
|
36
|
+
CLAUDE_CODE_USE_BEDROCK: v.optional(v.fallback(switchValueSchema, '')),
|
|
37
|
+
CLAUDE_CODE_USE_VERTEX: v.optional(v.fallback(switchValueSchema, '')),
|
|
38
|
+
CLAUDE_CODE_USE_FOUNDRY: v.optional(v.fallback(switchValueSchema, ''))
|
|
39
|
+
})
|
|
40
|
+
)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
/** Claude Code turns a switch on for `1`, `true`, `yes`, or `on`, in any case. */
|
|
44
|
+
function isOn(value: string): boolean {
|
|
45
|
+
return ['1', 'true', 'yes', 'on'].includes(value.trim().toLowerCase())
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The cloud the first switch that is on names. Settings override the environment, and managed
|
|
50
|
+
* settings override the user's, so `sources` lists the most specific source first.
|
|
51
|
+
*/
|
|
52
|
+
export function cloudFrom(sources: readonly SwitchSource[]): ClaudeCodeCloud | null {
|
|
53
|
+
for (const [name, cloud] of SWITCHES) {
|
|
54
|
+
const value = sources.map((source) => source(name)).find((found) => found !== undefined)
|
|
55
|
+
if (value !== undefined && isOn(value)) return cloud
|
|
56
|
+
}
|
|
57
|
+
return null
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The switches a settings file sets; nothing for a missing, unreadable, or malformed file. */
|
|
61
|
+
export async function settingsSwitches(path: string): Promise<SwitchSource> {
|
|
62
|
+
const text = await readFile(path, 'utf8').catch(() => null)
|
|
63
|
+
const parsed =
|
|
64
|
+
text === null
|
|
65
|
+
? null
|
|
66
|
+
: v.safeParse(v.pipe(v.string(), v.parseJson(), claudeSettingsSchema), text)
|
|
67
|
+
const env = parsed?.success ? parsed.output.env : undefined
|
|
68
|
+
return (name) => env?.[name]
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function managedSettings(runtimePlatform: NodeJS.Platform): string | null {
|
|
72
|
+
if (runtimePlatform === 'darwin') {
|
|
73
|
+
return '/Library/Application Support/ClaudeCode/managed-settings.json'
|
|
74
|
+
}
|
|
75
|
+
if (runtimePlatform === 'win32') return 'C:\\Program Files\\ClaudeCode\\managed-settings.json'
|
|
76
|
+
if (runtimePlatform === 'linux') return '/etc/claude-code/managed-settings.json'
|
|
77
|
+
return null
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The user's settings, in `CLAUDE_CONFIG_DIR` when that names another folder. */
|
|
81
|
+
function userSettings(env: NodeJS.ProcessEnv): string {
|
|
82
|
+
return join(env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'settings.json')
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The cloud Claude Code on this computer is set up to use, from the environment the companion
|
|
87
|
+
* starts agents with and Claude Code's managed and user settings; null when it signs in itself.
|
|
88
|
+
*/
|
|
89
|
+
export async function claudeCodeCloud(
|
|
90
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
91
|
+
runtimePlatform: NodeJS.Platform = platform()
|
|
92
|
+
): Promise<ClaudeCodeCloud | null> {
|
|
93
|
+
const managed = managedSettings(runtimePlatform)
|
|
94
|
+
const sources = await Promise.all([
|
|
95
|
+
managed ? settingsSwitches(managed) : () => undefined,
|
|
96
|
+
settingsSwitches(userSettings(env))
|
|
97
|
+
])
|
|
98
|
+
return cloudFrom([...sources, (name) => env[name]])
|
|
99
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import * as v from 'valibot'
|
|
2
|
+
|
|
3
|
+
import { acpAllowedMetaSchema, acpClientMessageSchema, acpHTTPServerSchema } from './schema'
|
|
4
|
+
|
|
5
|
+
/** One ndjson line may be this long; a prompt with images stays well below it. */
|
|
6
|
+
const MAX_LINE_BYTES = 16 * 1024 * 1024
|
|
7
|
+
const NEWLINE = 0x0a
|
|
8
|
+
|
|
9
|
+
export interface ACPFilterOptions {
|
|
10
|
+
/** The folder every session runs in, whatever the app asked for. */
|
|
11
|
+
workspace: string
|
|
12
|
+
/** Whether a URL is this companion's own MCP endpoint, the only server an agent may reach. */
|
|
13
|
+
isOwnMCP: (url: string) => boolean
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* What the companion lets through from the app to an agent. A session's working folder, the
|
|
18
|
+
* MCP servers it starts, and options the agent hands its SDK would otherwise let a tab run any
|
|
19
|
+
* program: an MCP server entry is a command line, and Claude's adapter takes its executable and
|
|
20
|
+
* environment from `_meta`. So every session runs in the companion's workspace, reaches only
|
|
21
|
+
* the companion's own MCP server, and keeps only the `_meta` the app sends.
|
|
22
|
+
*/
|
|
23
|
+
function sanitizeACPMessage(
|
|
24
|
+
text: string,
|
|
25
|
+
{ workspace, isOwnMCP }: ACPFilterOptions
|
|
26
|
+
): string | null {
|
|
27
|
+
const parsed = v.safeParse(acpClientMessageSchema, text)
|
|
28
|
+
if (!parsed.success) return null
|
|
29
|
+
const message = parsed.output
|
|
30
|
+
const params = message.params
|
|
31
|
+
if (!params) return JSON.stringify(message)
|
|
32
|
+
const meta = v.safeParse(acpAllowedMetaSchema, params._meta)
|
|
33
|
+
if (meta.success) params._meta = meta.output
|
|
34
|
+
else delete params._meta
|
|
35
|
+
if ('cwd' in params) params.cwd = workspace
|
|
36
|
+
if ('additionalDirectories' in params) delete params.additionalDirectories
|
|
37
|
+
if ('mcpServers' in params) {
|
|
38
|
+
const servers = Array.isArray(params.mcpServers) ? params.mcpServers : []
|
|
39
|
+
params.mcpServers = servers.filter((server) => {
|
|
40
|
+
const http = v.safeParse(acpHTTPServerSchema, server)
|
|
41
|
+
return http.success && isOwnMCP(http.output.url)
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
return JSON.stringify(message)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Splits the app's bytes into ndjson lines and passes each through `sanitizeACPMessage`.
|
|
49
|
+
* Returns the bytes to write to the agent, or null when a line is not a JSON-RPC message or
|
|
50
|
+
* grows past the limit, in which case the socket closes.
|
|
51
|
+
*/
|
|
52
|
+
export function createACPFilter(options: ACPFilterOptions) {
|
|
53
|
+
let pending: Buffer = Buffer.alloc(0)
|
|
54
|
+
return (chunk: Buffer): Buffer | null => {
|
|
55
|
+
pending = pending.length ? Buffer.concat([pending, chunk]) : chunk
|
|
56
|
+
const out: Buffer[] = []
|
|
57
|
+
for (;;) {
|
|
58
|
+
const end = pending.indexOf(NEWLINE)
|
|
59
|
+
if (end === -1) break
|
|
60
|
+
const line = pending.subarray(0, end).toString('utf8')
|
|
61
|
+
pending = pending.subarray(end + 1)
|
|
62
|
+
if (!line.trim()) continue
|
|
63
|
+
const clean = sanitizeACPMessage(line, options)
|
|
64
|
+
if (clean === null) return null
|
|
65
|
+
out.push(Buffer.from(`${clean}\n`, 'utf8'))
|
|
66
|
+
}
|
|
67
|
+
if (pending.length > MAX_LINE_BYTES) return null
|
|
68
|
+
return Buffer.concat(out)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Whether a URL is the MCP endpoint of the companion listening on `port` on this machine. */
|
|
73
|
+
export function isLoopbackMCP(url: string, port: number): boolean {
|
|
74
|
+
try {
|
|
75
|
+
const parsed = new URL(url)
|
|
76
|
+
return (
|
|
77
|
+
parsed.protocol === 'http:' &&
|
|
78
|
+
['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname) &&
|
|
79
|
+
Number(parsed.port) === port &&
|
|
80
|
+
parsed.pathname === '/mcp'
|
|
81
|
+
)
|
|
82
|
+
} catch {
|
|
83
|
+
return false
|
|
84
|
+
}
|
|
85
|
+
}
|