@pairdraw/mcp 0.17.0 → 0.19.0-beta.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/dist/connect.mjs +2 -2
- package/dist/{discovery-CB2Bv5WA.mjs → discovery-EZhmHKtk.mjs} +2 -2
- package/dist/{discovery-CB2Bv5WA.mjs.map → discovery-EZhmHKtk.mjs.map} +1 -1
- package/dist/discovery.mjs +1 -1
- package/dist/index.mjs +3 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{policy-B8Ka4WRH.mjs → policy-3SjGqzs8.mjs} +2 -2
- package/dist/policy-3SjGqzs8.mjs.map +1 -0
- package/dist/{server-B-NBTb6z.mjs → server-BALpRMlf.mjs} +322 -217
- package/dist/server-BALpRMlf.mjs.map +1 -0
- package/dist/server.d.mts +17 -0
- package/dist/server.mjs +1 -1
- package/dist/stdio.mjs +5 -5
- package/dist/stdio.mjs.map +1 -1
- package/dist/tools.mjs +1 -1
- package/package.json +2 -2
- package/src/browser-rpc.ts +50 -5
- package/src/index.ts +3 -0
- package/src/server/http-app.ts +172 -0
- package/src/server/sessions.ts +49 -5
- package/src/server.ts +73 -163
- package/src/skill/instructions.ts +10 -1
- package/src/stdio/bridge.ts +3 -2
- package/src/tool/manifest.ts +1 -1
- package/src/tool/output.ts +7 -12
- package/src/tool/registration.ts +30 -15
- package/dist/policy-B8Ka4WRH.mjs.map +0 -1
- package/dist/server-B-NBTb6z.mjs.map +0 -1
package/dist/server.d.mts
CHANGED
|
@@ -226,6 +226,13 @@ interface ServerOptions {
|
|
|
226
226
|
* app opts in when it spawns the server.
|
|
227
227
|
*/
|
|
228
228
|
appAttachTimeoutMs?: number;
|
|
229
|
+
/**
|
|
230
|
+
* Called once the app-attach watchdog has closed the server. A process that
|
|
231
|
+
* exists only for this server passes a shutdown, such as `process.exit`;
|
|
232
|
+
* without one, anything else still holding the event loop keeps it running
|
|
233
|
+
* with no listeners.
|
|
234
|
+
*/
|
|
235
|
+
onAppAttachTimeout?: () => void;
|
|
229
236
|
/**
|
|
230
237
|
* How long an MCP session may sit without requests before it is closed.
|
|
231
238
|
* Defaults to 15 minutes; 0 disables expiration. An open GET/SSE stream
|
|
@@ -238,6 +245,16 @@ interface ServerOptions {
|
|
|
238
245
|
* before the desktop app still succeeds; tests shorten it.
|
|
239
246
|
*/
|
|
240
247
|
appWaitTimeoutMs?: number;
|
|
248
|
+
/**
|
|
249
|
+
* How long an ordinary app call may take before it is reported as timed out.
|
|
250
|
+
* Defaults to 20 s; tests shorten it.
|
|
251
|
+
*/
|
|
252
|
+
rpcTimeoutMs?: number;
|
|
253
|
+
/**
|
|
254
|
+
* How long a document edit, or a call sent while one runs, may take.
|
|
255
|
+
* Defaults to 120 s, because drawing a page can outlast a read by a minute.
|
|
256
|
+
*/
|
|
257
|
+
documentRPCTimeoutMs?: number;
|
|
241
258
|
/**
|
|
242
259
|
* Turns on the companion's agent bridge (`pairdraw-connect`): pairing with the web app, and
|
|
243
260
|
* finding, installing, signing in to, and starting the coding agents in `ACP_AGENTS` for a
|
package/dist/server.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { l as fail, n as startServer, o as MCP_AGENT_KINDS, s as registerTools, t as MCP_VERSION, u as ok } from "./server-
|
|
1
|
+
import { l as fail, n as startServer, o as MCP_AGENT_KINDS, s as registerTools, t as MCP_VERSION, u as ok } from "./server-BALpRMlf.mjs";
|
|
2
2
|
export { MCP_AGENT_KINDS, MCP_VERSION, fail, ok, registerTools, startServer };
|
package/dist/stdio.mjs
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import "./rolldown-runtime-ClRpJifh.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import { c as registerSkill, r as createServerInstructions, s as registerTools, t as MCP_VERSION } from "./server-BALpRMlf.mjs";
|
|
4
4
|
import { a as getSocketPath, o as platformHasUnixSockets } from "./paths-BpcXnrbP.mjs";
|
|
5
5
|
import { t as resolveMCPRoot } from "./root-BzmoiT2g.mjs";
|
|
6
|
-
import { r as parseDisabledTools } from "./policy-
|
|
6
|
+
import { r as parseDisabledTools } from "./policy-3SjGqzs8.mjs";
|
|
7
7
|
import { a as narrowestScope, o as parseToolScope } from "./scope-D2LTTsDw.mjs";
|
|
8
|
-
import { n as readDiscoveryFile } from "./discovery-
|
|
8
|
+
import { n as readDiscoveryFile } from "./discovery-EZhmHKtk.mjs";
|
|
9
9
|
import { randomUUID } from "node:crypto";
|
|
10
10
|
import { McpServer } from "@modelcontextprotocol/server";
|
|
11
11
|
import { request } from "node:http";
|
|
12
12
|
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
|
13
13
|
//#region src/stdio/bridge.ts
|
|
14
|
-
const RPC_TIMEOUT =
|
|
14
|
+
const RPC_TIMEOUT = 135e3;
|
|
15
15
|
const DISCONNECTED_MESSAGE = "Pairdraw app is not connected. STOP and tell the user: \"The Pairdraw desktop app is not running or no document is open. Please start the app and open a document, then try again.\" Do NOT attempt to start the app yourself or retry automatically.";
|
|
16
16
|
/**
|
|
17
17
|
* Creates an RPC bridge that connects to the MCP server via HTTP
|
|
@@ -113,7 +113,7 @@ function createStdioRPCBridge({ socketPath: socketPathOverride, authToken, recon
|
|
|
113
113
|
res.on("error", reject);
|
|
114
114
|
});
|
|
115
115
|
req.on("error", reject);
|
|
116
|
-
req.setTimeout(
|
|
116
|
+
req.setTimeout(13e4, () => {
|
|
117
117
|
req.destroy(/* @__PURE__ */ new Error("Socket timeout"));
|
|
118
118
|
});
|
|
119
119
|
if (bodyJSON) req.write(bodyJSON);
|
package/dist/stdio.mjs.map
CHANGED
|
@@ -1 +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;EA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OAAO,QAAQ;CAC1C,QAAQ,OAAO,MAAM,+BAA+B,eAAe,QAAQ,IAAI,UAAU,IAAI,GAAG;CAChG,QAAQ,KAAK,CAAC;AAChB,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"}
|
|
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// 135s gives a 5s margin over the worst case (10s app wait + 120s document edit = 130s),\n// so a slow render arrives instead of being reported as a timeout the app then applies anyway.\nconst RPC_TIMEOUT = 135_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":";;;;;;;;;;;;;AAkBA,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;CAC1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ToolDescriptors } from "./policy-
|
|
2
|
+
import { a as serializeDisabledTools, n as isToolEnabled, o as createToolDescriptors } from "./policy-3SjGqzs8.mjs";
|
|
3
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
4
|
import * as v from "valibot";
|
|
5
5
|
const toolDescriptorSchema = v.object({
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pairdraw/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.0-beta.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"dependencies": {
|
|
16
16
|
"@hono/node-server": "^1.19.17",
|
|
17
17
|
"@modelcontextprotocol/server": "^2.0.0",
|
|
18
|
-
"@pairdraw/core": "^0.
|
|
18
|
+
"@pairdraw/core": "^0.19.0-beta.1",
|
|
19
19
|
"@valibot/to-json-schema": "^1.8.0",
|
|
20
20
|
"es-toolkit": "^1.52.0",
|
|
21
21
|
"hono": "^4.13.13",
|
package/src/browser-rpc.ts
CHANGED
|
@@ -8,6 +8,8 @@ import type { RPCJSONObject } from '#mcp/json'
|
|
|
8
8
|
import type { PendingRequest } from '#mcp/rpc-types'
|
|
9
9
|
|
|
10
10
|
const RPC_TIMEOUT = 20_000
|
|
11
|
+
/** A document edit lays out and draws a whole page, which can outlast a read by a minute. */
|
|
12
|
+
const DOCUMENT_RPC_TIMEOUT = 120_000
|
|
11
13
|
const APP_WAIT_TIMEOUT = 10_000
|
|
12
14
|
|
|
13
15
|
const APP_NOT_CONNECTED_MESSAGE =
|
|
@@ -20,6 +22,12 @@ type BrowserRPCBridgeOptions = {
|
|
|
20
22
|
onConnectionChange: () => void
|
|
21
23
|
/** How long an RPC waits for the app to register before failing with APP_NOT_CONNECTED. Defaults to 10 s. */
|
|
22
24
|
appWaitTimeoutMs?: number
|
|
25
|
+
/** How long an ordinary app call may take. Defaults to 20 s. */
|
|
26
|
+
rpcTimeoutMs?: number
|
|
27
|
+
/** How long a document edit, or a call sent while one is running, may take. Defaults to 120 s. */
|
|
28
|
+
documentRPCTimeoutMs?: number
|
|
29
|
+
/** Whether a request edits the document, which lets it and the calls behind it keep waiting. */
|
|
30
|
+
writesDocument?: (body: RPCJSONObject) => boolean
|
|
23
31
|
}
|
|
24
32
|
|
|
25
33
|
type ConnectionListener = (connected: boolean) => void
|
|
@@ -73,6 +81,13 @@ function sendJSON(ws: WebSocket, body: Record<string, unknown>) {
|
|
|
73
81
|
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(body))
|
|
74
82
|
}
|
|
75
83
|
|
|
84
|
+
/** Why a call gave up, saying whether the app may still be working on it. */
|
|
85
|
+
function timeoutMessage(editing: boolean, limitMs: number): string {
|
|
86
|
+
const seconds = Math.round(limitMs / 1000)
|
|
87
|
+
if (!editing) return `RPC timeout (${seconds}s)`
|
|
88
|
+
return `RPC timeout (${seconds}s): the edit may still be applied. Do not retry it; call get_page_tree to see what the document now holds.`
|
|
89
|
+
}
|
|
90
|
+
|
|
76
91
|
function createSettler<T>(resolve: (value: T) => void, reject: (error: Error) => void) {
|
|
77
92
|
let settled = false
|
|
78
93
|
return {
|
|
@@ -94,10 +109,15 @@ export function createBrowserRPCBridge({
|
|
|
94
109
|
authToken,
|
|
95
110
|
authorize = (token) => isAuthorized(token, authToken),
|
|
96
111
|
onConnectionChange,
|
|
97
|
-
appWaitTimeoutMs = APP_WAIT_TIMEOUT
|
|
112
|
+
appWaitTimeoutMs = APP_WAIT_TIMEOUT,
|
|
113
|
+
rpcTimeoutMs = RPC_TIMEOUT,
|
|
114
|
+
documentRPCTimeoutMs = DOCUMENT_RPC_TIMEOUT,
|
|
115
|
+
writesDocument = () => false
|
|
98
116
|
}: BrowserRPCBridgeOptions) {
|
|
99
117
|
const pending = new Map<string, PendingRequest & { ws: WebSocket }>()
|
|
100
118
|
const clients = new Set<WebSocket>()
|
|
119
|
+
/** How many document edits each window is still working on. */
|
|
120
|
+
const editsRunning = new Map<WebSocket, number>()
|
|
101
121
|
const connectionWaiters = new Set<PendingRequest>()
|
|
102
122
|
// Track which WebSocket clients have authenticated via a valid
|
|
103
123
|
// register message. Unauthenticated clients can only send register;
|
|
@@ -236,8 +256,9 @@ export function createBrowserRPCBridge({
|
|
|
236
256
|
for (const client of clients) sendRegisterPrompt(client)
|
|
237
257
|
}
|
|
238
258
|
|
|
239
|
-
function sendRPC(body:
|
|
259
|
+
function sendRPC(body: RPCJSONObject): Promise<unknown> {
|
|
240
260
|
if (bridgeClosed) return Promise.reject(new Error('Server shutting down'))
|
|
261
|
+
const editing = writesDocument(body)
|
|
241
262
|
return new Promise((resolve, reject) => {
|
|
242
263
|
const doSend = () => {
|
|
243
264
|
const ws = targetBrowser()
|
|
@@ -247,16 +268,40 @@ export function createBrowserRPCBridge({
|
|
|
247
268
|
}
|
|
248
269
|
const id = randomUUID()
|
|
249
270
|
const settle = createSettler(resolve, reject)
|
|
271
|
+
// A call sent while the window is still editing waits for that edit: the app lays out
|
|
272
|
+
// and draws on one thread, so a read cannot answer before the edit finishes.
|
|
273
|
+
const running = editsRunning.get(ws) ?? 0
|
|
274
|
+
const limit = editing || running > 0 ? documentRPCTimeoutMs : rpcTimeoutMs
|
|
275
|
+
if (editing) editsRunning.set(ws, running + 1)
|
|
276
|
+
const editFinished = () => {
|
|
277
|
+
if (!editing) return
|
|
278
|
+
const left = (editsRunning.get(ws) ?? 1) - 1
|
|
279
|
+
if (left > 0) editsRunning.set(ws, left)
|
|
280
|
+
else editsRunning.delete(ws)
|
|
281
|
+
}
|
|
250
282
|
const timer = setTimeout(() => {
|
|
251
283
|
pending.delete(id)
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
284
|
+
editFinished()
|
|
285
|
+
settle.reject(new Error(timeoutMessage(editing, limit)))
|
|
286
|
+
}, limit)
|
|
287
|
+
pending.set(id, {
|
|
288
|
+
resolve: (value) => {
|
|
289
|
+
editFinished()
|
|
290
|
+
settle.resolve(value)
|
|
291
|
+
},
|
|
292
|
+
reject: (error) => {
|
|
293
|
+
editFinished()
|
|
294
|
+
settle.reject(error)
|
|
295
|
+
},
|
|
296
|
+
timer,
|
|
297
|
+
ws
|
|
298
|
+
})
|
|
255
299
|
try {
|
|
256
300
|
ws.send(JSON.stringify({ ...body, type: 'request', id }))
|
|
257
301
|
} catch (e) {
|
|
258
302
|
clearTimeout(timer)
|
|
259
303
|
pending.delete(id)
|
|
304
|
+
editFinished()
|
|
260
305
|
if (!settle.isSettled()) {
|
|
261
306
|
settle.reject(e instanceof Error ? e : new Error(String(e)))
|
|
262
307
|
}
|
package/src/index.ts
CHANGED
|
@@ -140,6 +140,9 @@ const handle = await startServer({
|
|
|
140
140
|
})(),
|
|
141
141
|
corsOrigin: resolveCORSOrigins(process.env.PAIRDRAW_MCP_CORS_ORIGIN),
|
|
142
142
|
appAttachTimeoutMs,
|
|
143
|
+
// This process exists for the server it started, and resumed stdin keeps the event loop alive,
|
|
144
|
+
// so a watchdog shutdown must end it rather than leave a process with no listeners.
|
|
145
|
+
onAppAttachTimeout: () => process.exit(0),
|
|
143
146
|
sessionIdleTimeoutMs,
|
|
144
147
|
agents: agents ?? undefined
|
|
145
148
|
})
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { Hono, type Context, type Next } from 'hono'
|
|
2
|
+
import { cors } from 'hono/cors'
|
|
3
|
+
|
|
4
|
+
import { MCP_AGENT_HEADER, MCP_CHAT_HEADER } from '@pairdraw/core/constants'
|
|
5
|
+
|
|
6
|
+
import type { AgentBridge } from '#mcp/agents/index'
|
|
7
|
+
import { bearerToken, mcpRequestToken } from '#mcp/auth'
|
|
8
|
+
import type { createBrowserRPCBridge } from '#mcp/browser-rpc'
|
|
9
|
+
import * as httpOptions from '#mcp/http-options'
|
|
10
|
+
import type { RPCJSONObject } from '#mcp/json'
|
|
11
|
+
import { registerFileRoutes } from '#mcp/server/files'
|
|
12
|
+
import {
|
|
13
|
+
type createMCPSessionManager,
|
|
14
|
+
MCP_SESSION_EVICT_IDLE_MS,
|
|
15
|
+
MCP_SESSION_LIMIT,
|
|
16
|
+
sessionOpener
|
|
17
|
+
} from '#mcp/server/sessions'
|
|
18
|
+
import type { ToolDescriptor } from '#mcp/tool/metadata'
|
|
19
|
+
|
|
20
|
+
import { mcpInstallCommand } from './install-command'
|
|
21
|
+
import { originGuard } from './origin'
|
|
22
|
+
|
|
23
|
+
const MCP_METHODS: readonly string[] = ['GET', 'POST', 'DELETE']
|
|
24
|
+
|
|
25
|
+
/** Set up Hono routes: /health, /rpc, /files, /mcp */
|
|
26
|
+
export function createHonoApp(options: {
|
|
27
|
+
authToken: string | null
|
|
28
|
+
/** Whether a token reaches the app's bridge, `/rpc`, and `/files`: the server's own, or a paired tab's. */
|
|
29
|
+
verifyToken: (token: string | null) => boolean
|
|
30
|
+
/** Whether a token reaches `/mcp`: also the agent token a paired tab hands its agents. */
|
|
31
|
+
verifyMCPToken: (token: string | null) => boolean
|
|
32
|
+
corsOrigin: string | readonly string[] | null
|
|
33
|
+
/** Origins whose pages may call the server; requests without an Origin come from programs. */
|
|
34
|
+
origins: readonly string[]
|
|
35
|
+
/** The filtered list `cors()` answers with; never carries a stray `*` when the bridge is on. */
|
|
36
|
+
corsAllowed: readonly string[] | null
|
|
37
|
+
agentBridge: AgentBridge | null
|
|
38
|
+
/** The root `/files` reads and writes inside, or null to leave the route out. */
|
|
39
|
+
fileRoot: string | null
|
|
40
|
+
browserRPC: ReturnType<typeof createBrowserRPCBridge>
|
|
41
|
+
mcpSessions: ReturnType<typeof createMCPSessionManager>
|
|
42
|
+
sendToBrowser: (msg: RPCJSONObject) => Promise<unknown>
|
|
43
|
+
toolDescriptors: ToolDescriptor[]
|
|
44
|
+
version: string
|
|
45
|
+
}): Hono {
|
|
46
|
+
const { authToken, corsOrigin, corsAllowed, fileRoot, browserRPC, mcpSessions, sendToBrowser } =
|
|
47
|
+
options
|
|
48
|
+
const { toolDescriptors, verifyToken, verifyMCPToken, origins, agentBridge } = options
|
|
49
|
+
|
|
50
|
+
const app = new Hono()
|
|
51
|
+
|
|
52
|
+
app.use('*', originGuard(origins))
|
|
53
|
+
|
|
54
|
+
if (corsOrigin) {
|
|
55
|
+
const corsOrigins =
|
|
56
|
+
corsAllowed ?? (typeof corsOrigin === 'string' ? [corsOrigin] : [...corsOrigin])
|
|
57
|
+
app.use(
|
|
58
|
+
'*',
|
|
59
|
+
cors({
|
|
60
|
+
origin: [...corsOrigins],
|
|
61
|
+
allowMethods: httpOptions.MCP_CORS_METHODS,
|
|
62
|
+
allowHeaders: httpOptions.MCP_CORS_HEADERS,
|
|
63
|
+
exposeHeaders: httpOptions.MCP_EXPOSED_HEADERS
|
|
64
|
+
})
|
|
65
|
+
)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
app.get('/health', async (c) => {
|
|
69
|
+
const provided = bearerToken(c.req.header('authorization'))
|
|
70
|
+
const canInspectConfiguration = verifyMCPToken(provided)
|
|
71
|
+
return c.json({
|
|
72
|
+
status: browserRPC.isConnected() ? 'ok' : 'no_app',
|
|
73
|
+
version: options.version,
|
|
74
|
+
installCommand: await mcpInstallCommand(options.version),
|
|
75
|
+
authRequired: authToken !== null,
|
|
76
|
+
// Tells the app it reports agent_session_opened, so a chat may wait for its agent.
|
|
77
|
+
agentSessionEvents: true,
|
|
78
|
+
...(canInspectConfiguration ? { tools: toolDescriptors } : {})
|
|
79
|
+
})
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
const requireToken = async (c: Context, next: Next) => {
|
|
83
|
+
// When authToken is null (operator explicitly disabled auth), skip token check —
|
|
84
|
+
// the Unix socket or localhost TCP already restricts access to local processes.
|
|
85
|
+
if (!verifyToken(bearerToken(c.req.header('authorization')))) {
|
|
86
|
+
return c.json({ error: 'Unauthorized' }, 401)
|
|
87
|
+
}
|
|
88
|
+
return next()
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
app.use('/rpc', requireToken)
|
|
92
|
+
|
|
93
|
+
if (fileRoot !== null) {
|
|
94
|
+
app.use('/files/*', requireToken)
|
|
95
|
+
registerFileRoutes(app, fileRoot)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Errors from sendToBrowser surface as 502, including a disconnected app (formerly 503).
|
|
99
|
+
app.post('/rpc', httpOptions.limitBody, async (c) => {
|
|
100
|
+
const body = await c.req.json().catch(() => null)
|
|
101
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
102
|
+
return c.json({ error: 'Invalid request body' }, 400)
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
const result = await sendToBrowser(body as RPCJSONObject)
|
|
106
|
+
return c.json(result)
|
|
107
|
+
} catch (e) {
|
|
108
|
+
const msg = e instanceof Error ? e.message : String(e)
|
|
109
|
+
return c.json({ ok: false, error: msg }, 502)
|
|
110
|
+
}
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
const requireMCPToken = async (c: Context, next: Next) => {
|
|
114
|
+
const token = mcpRequestToken(c.req.header('authorization'), c.req.header('x-mcp-token'))
|
|
115
|
+
return verifyMCPToken(token) ? next() : c.json({ error: 'Unauthorized' }, 401)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
app.all('/mcp', requireMCPToken, httpOptions.limitBody, async (c) => {
|
|
119
|
+
if (!MCP_METHODS.includes(c.req.method)) {
|
|
120
|
+
return c.json(
|
|
121
|
+
{ error: 'Method not allowed' },
|
|
122
|
+
{ status: 405, headers: { Allow: MCP_METHODS.join(', ') } }
|
|
123
|
+
)
|
|
124
|
+
}
|
|
125
|
+
const sessionId = c.req.header('mcp-session-id') ?? undefined
|
|
126
|
+
if (sessionId) {
|
|
127
|
+
// Never allocate a session for an unknown ID: DELETE or a stale client
|
|
128
|
+
// would burn a slot it can never use.
|
|
129
|
+
const existing = mcpSessions.getExistingTransport(sessionId)
|
|
130
|
+
if ('error' in existing) {
|
|
131
|
+
if (existing.error === 'closed') {
|
|
132
|
+
return c.json({ error: 'MCP server is shutting down' }, 503)
|
|
133
|
+
}
|
|
134
|
+
return c.json({ error: 'MCP session not found' }, 404)
|
|
135
|
+
}
|
|
136
|
+
if (c.req.method !== 'DELETE') return existing.handleRequest(c.req.raw)
|
|
137
|
+
try {
|
|
138
|
+
return await existing.handleRequest(c.req.raw)
|
|
139
|
+
} finally {
|
|
140
|
+
await mcpSessions.deleteSession(sessionId)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// Only an initializing POST may start a session.
|
|
144
|
+
if (c.req.method !== 'POST') {
|
|
145
|
+
return c.json({ error: 'Missing MCP session id' }, 400)
|
|
146
|
+
}
|
|
147
|
+
const transport = await mcpSessions.resolveTransport(
|
|
148
|
+
undefined,
|
|
149
|
+
sessionOpener(c.req.header(MCP_AGENT_HEADER), c.req.header(MCP_CHAT_HEADER))
|
|
150
|
+
)
|
|
151
|
+
if ('error' in transport) {
|
|
152
|
+
if (transport.error === 'closed') {
|
|
153
|
+
return c.json({ error: 'MCP server is shutting down' }, 503)
|
|
154
|
+
}
|
|
155
|
+
// The refusal names what the caller ran into, so a client can tell why it was turned away
|
|
156
|
+
// and when to come back.
|
|
157
|
+
return c.json(
|
|
158
|
+
{
|
|
159
|
+
error: `The server holds ${MCP_SESSION_LIMIT} MCP sessions at once; close one with DELETE, or wait for one left idle for ${MCP_SESSION_EVICT_IDLE_MS / 1000} seconds to be released.`,
|
|
160
|
+
limit: MCP_SESSION_LIMIT,
|
|
161
|
+
retryAfterSeconds: 5
|
|
162
|
+
},
|
|
163
|
+
{ status: 503, headers: { 'Retry-After': '5' } }
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
return transport.handleRequest(c.req.raw)
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
agentBridge?.routes(app)
|
|
170
|
+
|
|
171
|
+
return app
|
|
172
|
+
}
|
package/src/server/sessions.ts
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
McpServer,
|
|
6
6
|
WebStandardStreamableHTTPServerTransport
|
|
7
7
|
} from '@modelcontextprotocol/server'
|
|
8
|
+
import { minBy } from 'es-toolkit'
|
|
8
9
|
import { withTimeout } from 'es-toolkit/promise'
|
|
9
10
|
|
|
10
11
|
import { createPendingRequests } from '#mcp/server/pending-requests'
|
|
@@ -44,9 +45,17 @@ type MCPSessionManagerOptions = {
|
|
|
44
45
|
onSessionClosed?: (sessionId: string) => void
|
|
45
46
|
/** Idle lifetime in ms; 0 disables expiration. Defaults to 15 minutes. */
|
|
46
47
|
sessionIdleTimeoutMs?: number
|
|
48
|
+
/**
|
|
49
|
+
* How long a session must sit idle before a new client may take its slot at the cap. A session
|
|
50
|
+
* younger than this belongs to someone who may still be using it. Defaults to two minutes.
|
|
51
|
+
*/
|
|
52
|
+
evictIdleMs?: number
|
|
47
53
|
}
|
|
48
54
|
|
|
49
|
-
|
|
55
|
+
/** How many sessions the server holds at once. */
|
|
56
|
+
export const MCP_SESSION_LIMIT = 10
|
|
57
|
+
/** How long a session must sit idle before a newcomer may take its slot. */
|
|
58
|
+
export const MCP_SESSION_EVICT_IDLE_MS = 2 * 60_000
|
|
50
59
|
/** App chat ids are random hex; anything else is ignored rather than forwarded. */
|
|
51
60
|
const CHAT_ID = /^[0-9a-f]{16,64}$/
|
|
52
61
|
|
|
@@ -103,7 +112,8 @@ export function createMCPSessionManager({
|
|
|
103
112
|
instructions,
|
|
104
113
|
onSessionOpened,
|
|
105
114
|
onSessionClosed,
|
|
106
|
-
sessionIdleTimeoutMs = MCP_SESSION_IDLE_TIMEOUT_MS
|
|
115
|
+
sessionIdleTimeoutMs = MCP_SESSION_IDLE_TIMEOUT_MS,
|
|
116
|
+
evictIdleMs = MCP_SESSION_EVICT_IDLE_MS
|
|
107
117
|
}: MCPSessionManagerOptions) {
|
|
108
118
|
const sessions = new Map<string, MCPSession>()
|
|
109
119
|
const closing = new Map<string, Promise<void>>()
|
|
@@ -158,6 +168,29 @@ export function createMCPSessionManager({
|
|
|
158
168
|
const creating = new Map<string, Promise<MCPTransport>>()
|
|
159
169
|
let closed = false
|
|
160
170
|
|
|
171
|
+
/**
|
|
172
|
+
* A session whose slot a newcomer may take. A client may replace its own idle session, and any
|
|
173
|
+
* client may take the slot of one left idle long enough that nobody is using it. A session
|
|
174
|
+
* another client may still be working in is never taken, so no client can push another out;
|
|
175
|
+
* when live sessions are below the cap, the slots are held by ones still closing, and the
|
|
176
|
+
* caller waits for them.
|
|
177
|
+
*/
|
|
178
|
+
function evictionCandidate(
|
|
179
|
+
opener: MCPSessionOpener
|
|
180
|
+
): { id: string; session: MCPSession } | undefined {
|
|
181
|
+
if (sessions.size + creating.size < MCP_SESSION_LIMIT) return undefined
|
|
182
|
+
const idle = [...sessions]
|
|
183
|
+
.map(([id, session]) => ({ id, session }))
|
|
184
|
+
.filter((entry) => entry.session.activeRequests === 0)
|
|
185
|
+
if (idle.length === 0) return undefined
|
|
186
|
+
const own = opener.chat ? idle.filter((entry) => entry.session.agent.chat === opener.chat) : []
|
|
187
|
+
const now = Date.now()
|
|
188
|
+
const pool =
|
|
189
|
+
own.length > 0 ? own : idle.filter((entry) => now - entry.session.lastSeen >= evictIdleMs)
|
|
190
|
+
if (pool.length === 0) return undefined
|
|
191
|
+
return minBy(pool, (entry) => entry.session.lastSeen)
|
|
192
|
+
}
|
|
193
|
+
|
|
161
194
|
async function createSession(id: string, opener: MCPSessionOpener): Promise<MCPTransport> {
|
|
162
195
|
if (closed) throw new Error('Session manager is closed')
|
|
163
196
|
const inFlight = creating.get(id)
|
|
@@ -275,8 +308,11 @@ export function createMCPSessionManager({
|
|
|
275
308
|
})
|
|
276
309
|
}
|
|
277
310
|
}
|
|
278
|
-
if (sessions.size + creating.size + closing.size >=
|
|
279
|
-
|
|
311
|
+
if (sessions.size + creating.size + closing.size >= MCP_SESSION_LIMIT) {
|
|
312
|
+
const victim = evictionCandidate(opener)
|
|
313
|
+
if (!victim) return Promise.resolve({ error: 'too_many' })
|
|
314
|
+
sessions.delete(victim.id)
|
|
315
|
+
void scheduleClose(victim.session, victim.id)
|
|
280
316
|
}
|
|
281
317
|
return createSession(sessionId ?? randomUUID(), opener).catch((e) => {
|
|
282
318
|
// If the manager was closed during session creation, return the structured
|
|
@@ -331,5 +367,13 @@ export function createMCPSessionManager({
|
|
|
331
367
|
])
|
|
332
368
|
}
|
|
333
369
|
|
|
334
|
-
return {
|
|
370
|
+
return {
|
|
371
|
+
clear,
|
|
372
|
+
deleteSession,
|
|
373
|
+
getExistingTransport,
|
|
374
|
+
notifyToolsChanged,
|
|
375
|
+
resolveTransport,
|
|
376
|
+
/** Whether a client holds an initialized session, which keeps the server in use. */
|
|
377
|
+
hasClients: () => [...sessions.values()].some((session) => session.initialized)
|
|
378
|
+
}
|
|
335
379
|
}
|