@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
package/src/server.ts
ADDED
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto'
|
|
2
|
+
import type { Server as HttpServer } from 'node:http'
|
|
3
|
+
import { resolve } from 'node:path'
|
|
4
|
+
|
|
5
|
+
import type { McpServer } from '@modelcontextprotocol/server'
|
|
6
|
+
import { Hono, type Context, type Next } from 'hono'
|
|
7
|
+
import { cors } from 'hono/cors'
|
|
8
|
+
import { WebSocketServer } from 'ws'
|
|
9
|
+
|
|
10
|
+
import { MCP_AGENT_HEADER, MCP_CHAT_HEADER } from '@pairdraw/core/constants'
|
|
11
|
+
|
|
12
|
+
import { createAgentBridge, type AgentBridge, type AgentBridgeOptions } from '#mcp/agents/index'
|
|
13
|
+
import { bearerToken, isAuthorized, mcpRequestToken } from '#mcp/auth'
|
|
14
|
+
import { createBrowserRPCBridge } from '#mcp/browser-rpc'
|
|
15
|
+
import { MCP_CORS_HEADERS, MCP_CORS_METHODS, MCP_EXPOSED_HEADERS } from '#mcp/http-options'
|
|
16
|
+
import type { RPCJSONObject } from '#mcp/json'
|
|
17
|
+
import { registerFileRoutes } from '#mcp/server/files'
|
|
18
|
+
import { createMCPSessionManager, sessionOpener } from '#mcp/server/sessions'
|
|
19
|
+
import { createServerInstructions } from '#mcp/skill/instructions'
|
|
20
|
+
import { createToolDescriptors } from '#mcp/tool/manifest'
|
|
21
|
+
import type { ToolDescriptor, ToolPolicy } from '#mcp/tool/metadata'
|
|
22
|
+
import { applyToolPolicy } from '#mcp/tool/policy'
|
|
23
|
+
import { registerTools, type MCPAgentSession } from '#mcp/tool/registration'
|
|
24
|
+
import { scopeRPC, type MCPToolScope } from '#mcp/tool/scope'
|
|
25
|
+
import { admittedOrigins } from '#mcp/transport/origins'
|
|
26
|
+
|
|
27
|
+
import packageJSON from '../package.json' with { type: 'json' }
|
|
28
|
+
import { wireConnectionHandling } from './server/connections'
|
|
29
|
+
import { mcpInstallCommand } from './server/install-command'
|
|
30
|
+
import {
|
|
31
|
+
type ListenerState,
|
|
32
|
+
cleanupDiscovery,
|
|
33
|
+
closeWssGracefully,
|
|
34
|
+
createAppServer,
|
|
35
|
+
startSocketListener,
|
|
36
|
+
teardownListeners,
|
|
37
|
+
tryStartTcp,
|
|
38
|
+
tryWriteDiscovery
|
|
39
|
+
} from './server/lifecycle'
|
|
40
|
+
import { createUpgradeHandler, originGuard } from './server/origin'
|
|
41
|
+
|
|
42
|
+
export const MCP_VERSION: string = packageJSON.version
|
|
43
|
+
|
|
44
|
+
const MCP_METHODS: readonly string[] = ['GET', 'POST', 'DELETE']
|
|
45
|
+
|
|
46
|
+
export { fail, ok, type MCPContent, type MCPResult } from '#mcp/result'
|
|
47
|
+
|
|
48
|
+
export {
|
|
49
|
+
MCP_AGENT_KINDS,
|
|
50
|
+
registerTools,
|
|
51
|
+
type MCPAgentKind,
|
|
52
|
+
type MCPAgentSession,
|
|
53
|
+
type RegisterToolsOptions,
|
|
54
|
+
type RPCSender
|
|
55
|
+
} from '#mcp/tool/registration'
|
|
56
|
+
|
|
57
|
+
export interface ServerOptions {
|
|
58
|
+
/** TCP port for the HTTP + WebSocket server. Ignored when `withTcp` is false. When set to 0 with `withTcp: true`, binds to an ephemeral port. Defaults to 7600. */
|
|
59
|
+
httpPort?: number
|
|
60
|
+
/** Path to the Unix domain socket. Auto-resolved if omitted. */
|
|
61
|
+
socketPath?: string | null
|
|
62
|
+
/** Whether to also listen on TCP (in addition to the socket). API default is `false`; the CLI passes `true` by default (derived from PORT, default 7600). */
|
|
63
|
+
withTcp?: boolean
|
|
64
|
+
enableEval?: boolean
|
|
65
|
+
/** Tool names omitted from every MCP session. */
|
|
66
|
+
disabledTools?: Iterable<string>
|
|
67
|
+
/** What clients can reach: the whole document (default) or only the user's selection. */
|
|
68
|
+
scope?: MCPToolScope
|
|
69
|
+
mcpRoot?: string | null
|
|
70
|
+
/** Auth token for /mcp and /rpc endpoints. Auto-generated (32-hex) when omitted. Pass null explicitly to disable auth. */
|
|
71
|
+
authToken?: string | null
|
|
72
|
+
corsOrigin?: string | readonly string[] | null
|
|
73
|
+
/**
|
|
74
|
+
* If set, the server starts a grace-period timer while no app is attached.
|
|
75
|
+
* The timer closes the server and removes its discovery file unless an app
|
|
76
|
+
* registers before it expires. A later app disconnect starts a new grace
|
|
77
|
+
* period, which lets app-spawned servers survive brief reloads while still
|
|
78
|
+
* cleaning up after renderer or process crashes. Undefined/0 disables the
|
|
79
|
+
* watchdog — the default, since a bare CLI invocation for manual testing
|
|
80
|
+
* should not self-terminate just because nobody connected yet. The desktop
|
|
81
|
+
* app opts in when it spawns the server.
|
|
82
|
+
*/
|
|
83
|
+
appAttachTimeoutMs?: number
|
|
84
|
+
/**
|
|
85
|
+
* How long an MCP session may sit without requests before it is closed.
|
|
86
|
+
* Defaults to 15 minutes; 0 disables expiration. An open GET/SSE stream
|
|
87
|
+
* does not count as activity.
|
|
88
|
+
*/
|
|
89
|
+
sessionIdleTimeoutMs?: number
|
|
90
|
+
/**
|
|
91
|
+
* How long a tool call waits for the app to register before it fails with
|
|
92
|
+
* APP_NOT_CONNECTED. Defaults to 10 s so a stdio bridge started slightly
|
|
93
|
+
* before the desktop app still succeeds; tests shorten it.
|
|
94
|
+
*/
|
|
95
|
+
appWaitTimeoutMs?: number
|
|
96
|
+
/**
|
|
97
|
+
* Turns on the companion's agent bridge (`pairdraw-connect`): pairing with the web app, and
|
|
98
|
+
* finding, installing, signing in to, and starting the coding agents in `ACP_AGENTS` for a
|
|
99
|
+
* paired tab. Off unless set.
|
|
100
|
+
*/
|
|
101
|
+
agents?: AgentBridgeOptions
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface ServerHandle {
|
|
105
|
+
/** The Hono app (routes) */
|
|
106
|
+
app: Hono
|
|
107
|
+
/** The primary Node.js HTTP server (socket listener if present, otherwise TCP) */
|
|
108
|
+
server: HttpServer
|
|
109
|
+
/** Resolved socket path (null if not listening on socket) */
|
|
110
|
+
socketPath: string | null
|
|
111
|
+
/** TCP port the server is listening on (0 if TCP is disabled) */
|
|
112
|
+
httpPort: number
|
|
113
|
+
/** Shut down the server: close listeners, remove socket and discovery files */
|
|
114
|
+
close: () => Promise<void>
|
|
115
|
+
/** Issues a one-time pairing code, when the agent bridge is on; otherwise null. */
|
|
116
|
+
issuePairingCode: (() => string) | null
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Set up Hono routes: /health, /rpc, /files, /mcp */
|
|
120
|
+
function createHonoApp(options: {
|
|
121
|
+
authToken: string | null
|
|
122
|
+
/** Whether a token reaches the app's bridge, `/rpc`, and `/files`: the server's own, or a paired tab's. */
|
|
123
|
+
verifyToken: (token: string | null) => boolean
|
|
124
|
+
/** Whether a token reaches `/mcp`: also the agent token a paired tab hands its agents. */
|
|
125
|
+
verifyMCPToken: (token: string | null) => boolean
|
|
126
|
+
corsOrigin: string | readonly string[] | null
|
|
127
|
+
/** Origins whose pages may call the server; requests without an Origin come from programs. */
|
|
128
|
+
origins: readonly string[]
|
|
129
|
+
/** The filtered list `cors()` answers with; never carries a stray `*` when the bridge is on. */
|
|
130
|
+
corsAllowed: readonly string[] | null
|
|
131
|
+
agentBridge: AgentBridge | null
|
|
132
|
+
/** The root `/files` reads and writes inside, or null to leave the route out. */
|
|
133
|
+
fileRoot: string | null
|
|
134
|
+
browserRPC: ReturnType<typeof createBrowserRPCBridge>
|
|
135
|
+
mcpSessions: ReturnType<typeof createMCPSessionManager>
|
|
136
|
+
sendToBrowser: (msg: RPCJSONObject) => Promise<unknown>
|
|
137
|
+
toolDescriptors: ToolDescriptor[]
|
|
138
|
+
}): Hono {
|
|
139
|
+
const { authToken, corsOrigin, corsAllowed, fileRoot, browserRPC, mcpSessions, sendToBrowser } =
|
|
140
|
+
options
|
|
141
|
+
const { toolDescriptors, verifyToken, verifyMCPToken, origins, agentBridge } = options
|
|
142
|
+
|
|
143
|
+
const app = new Hono()
|
|
144
|
+
|
|
145
|
+
app.use('*', originGuard(origins))
|
|
146
|
+
|
|
147
|
+
if (corsOrigin) {
|
|
148
|
+
const corsOrigins =
|
|
149
|
+
corsAllowed ?? (typeof corsOrigin === 'string' ? [corsOrigin] : [...corsOrigin])
|
|
150
|
+
app.use(
|
|
151
|
+
'*',
|
|
152
|
+
cors({
|
|
153
|
+
origin: [...corsOrigins],
|
|
154
|
+
allowMethods: MCP_CORS_METHODS,
|
|
155
|
+
allowHeaders: MCP_CORS_HEADERS,
|
|
156
|
+
exposeHeaders: MCP_EXPOSED_HEADERS
|
|
157
|
+
})
|
|
158
|
+
)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
app.get('/health', async (c) => {
|
|
162
|
+
const provided = bearerToken(c.req.header('authorization'))
|
|
163
|
+
const canInspectConfiguration = verifyMCPToken(provided)
|
|
164
|
+
return c.json({
|
|
165
|
+
status: browserRPC.isConnected() ? 'ok' : 'no_app',
|
|
166
|
+
version: MCP_VERSION,
|
|
167
|
+
installCommand: await mcpInstallCommand(MCP_VERSION),
|
|
168
|
+
authRequired: authToken !== null,
|
|
169
|
+
// Tells the app it reports agent_session_opened, so a chat may wait for its agent.
|
|
170
|
+
agentSessionEvents: true,
|
|
171
|
+
...(canInspectConfiguration ? { tools: toolDescriptors } : {})
|
|
172
|
+
})
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
const requireToken = async (c: Context, next: Next) => {
|
|
176
|
+
// When authToken is null (operator explicitly disabled auth), skip token check —
|
|
177
|
+
// the Unix socket or localhost TCP already restricts access to local processes.
|
|
178
|
+
if (!verifyToken(bearerToken(c.req.header('authorization')))) {
|
|
179
|
+
return c.json({ error: 'Unauthorized' }, 401)
|
|
180
|
+
}
|
|
181
|
+
return next()
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
app.use('/rpc', requireToken)
|
|
185
|
+
|
|
186
|
+
if (fileRoot !== null) {
|
|
187
|
+
app.use('/files/*', requireToken)
|
|
188
|
+
registerFileRoutes(app, fileRoot)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Errors from sendToBrowser surface as 502, including a disconnected app (formerly 503).
|
|
192
|
+
app.post('/rpc', async (c) => {
|
|
193
|
+
const body = await c.req.json().catch(() => null)
|
|
194
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
195
|
+
return c.json({ error: 'Invalid request body' }, 400)
|
|
196
|
+
}
|
|
197
|
+
try {
|
|
198
|
+
const result = await sendToBrowser(body as RPCJSONObject)
|
|
199
|
+
return c.json(result)
|
|
200
|
+
} catch (e) {
|
|
201
|
+
const msg = e instanceof Error ? e.message : String(e)
|
|
202
|
+
return c.json({ ok: false, error: msg }, 502)
|
|
203
|
+
}
|
|
204
|
+
})
|
|
205
|
+
|
|
206
|
+
app.all('/mcp', async (c) => {
|
|
207
|
+
const token = mcpRequestToken(c.req.header('authorization'), c.req.header('x-mcp-token'))
|
|
208
|
+
if (!verifyMCPToken(token)) {
|
|
209
|
+
return c.json({ error: 'Unauthorized' }, 401)
|
|
210
|
+
}
|
|
211
|
+
if (!MCP_METHODS.includes(c.req.method)) {
|
|
212
|
+
return c.json(
|
|
213
|
+
{ error: 'Method not allowed' },
|
|
214
|
+
{ status: 405, headers: { Allow: MCP_METHODS.join(', ') } }
|
|
215
|
+
)
|
|
216
|
+
}
|
|
217
|
+
const sessionId = c.req.header('mcp-session-id') ?? undefined
|
|
218
|
+
if (sessionId) {
|
|
219
|
+
// Never allocate a session for an unknown ID: DELETE or a stale client
|
|
220
|
+
// would burn a slot it can never use.
|
|
221
|
+
const existing = mcpSessions.getExistingTransport(sessionId)
|
|
222
|
+
if ('error' in existing) {
|
|
223
|
+
if (existing.error === 'closed') {
|
|
224
|
+
return c.json({ error: 'MCP server is shutting down' }, 503)
|
|
225
|
+
}
|
|
226
|
+
return c.json({ error: 'MCP session not found' }, 404)
|
|
227
|
+
}
|
|
228
|
+
if (c.req.method !== 'DELETE') return existing.handleRequest(c.req.raw)
|
|
229
|
+
try {
|
|
230
|
+
return await existing.handleRequest(c.req.raw)
|
|
231
|
+
} finally {
|
|
232
|
+
await mcpSessions.deleteSession(sessionId)
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
// Only an initializing POST may start a session.
|
|
236
|
+
if (c.req.method !== 'POST') {
|
|
237
|
+
return c.json({ error: 'Missing MCP session id' }, 400)
|
|
238
|
+
}
|
|
239
|
+
const transport = await mcpSessions.resolveTransport(
|
|
240
|
+
undefined,
|
|
241
|
+
sessionOpener(c.req.header(MCP_AGENT_HEADER), c.req.header(MCP_CHAT_HEADER))
|
|
242
|
+
)
|
|
243
|
+
if ('error' in transport) {
|
|
244
|
+
if (transport.error === 'closed') {
|
|
245
|
+
return c.json({ error: 'MCP server is shutting down' }, 503)
|
|
246
|
+
}
|
|
247
|
+
return c.json(
|
|
248
|
+
{ error: 'Too many active MCP sessions' },
|
|
249
|
+
{ status: 503, headers: { 'Retry-After': '5' } }
|
|
250
|
+
)
|
|
251
|
+
}
|
|
252
|
+
return transport.handleRequest(c.req.raw)
|
|
253
|
+
})
|
|
254
|
+
|
|
255
|
+
agentBridge?.routes(app)
|
|
256
|
+
|
|
257
|
+
return app
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function buildServerContext(options: ServerOptions) {
|
|
261
|
+
const httpPort = options.httpPort ?? 7600
|
|
262
|
+
const evalRequestedWithAgents = options.agents !== undefined && (options.enableEval ?? false)
|
|
263
|
+
if (evalRequestedWithAgents) {
|
|
264
|
+
process.stderr.write(
|
|
265
|
+
'Warning: enableEval is ignored while the agent bridge is on; eval stays off.\n'
|
|
266
|
+
)
|
|
267
|
+
}
|
|
268
|
+
const toolPolicy: ToolPolicy = {
|
|
269
|
+
allowEval: (options.enableEval ?? false) && options.agents === undefined,
|
|
270
|
+
disabledTools: [...new Set(options.disabledTools)],
|
|
271
|
+
scope: options.scope ?? 'document'
|
|
272
|
+
}
|
|
273
|
+
const mcpRoot = options.mcpRoot ?? null
|
|
274
|
+
// Auto-generated so all transports require auth by default. Override via PAIRDRAW_MCP_AUTH_TOKEN or authToken option.
|
|
275
|
+
// Pass authToken: null explicitly to disable auth entirely.
|
|
276
|
+
const authToken =
|
|
277
|
+
options.authToken === undefined ? randomBytes(16).toString('hex') : options.authToken
|
|
278
|
+
const corsOrigin = options.corsOrigin ?? null
|
|
279
|
+
const withTcp = options.withTcp ?? false
|
|
280
|
+
const origins = admittedOrigins(corsOrigin, { withAgents: options.agents !== undefined })
|
|
281
|
+
// The bridge learns the TCP port once the listener is up; agents may reach only that `/mcp`.
|
|
282
|
+
const listening = { port: 0 }
|
|
283
|
+
const bridgeOptions = {
|
|
284
|
+
port: () => listening.port,
|
|
285
|
+
version: MCP_VERSION,
|
|
286
|
+
entry: process.argv[1] ?? ''
|
|
287
|
+
}
|
|
288
|
+
const agentBridge = options.agents
|
|
289
|
+
? createAgentBridge({ ...options.agents, ...bridgeOptions })
|
|
290
|
+
: null
|
|
291
|
+
/** The server's own token, or a tab paired through the agent bridge. */
|
|
292
|
+
const verifyToken = (token: string | null): boolean =>
|
|
293
|
+
isAuthorized(token, authToken) || (agentBridge?.isSession(token) ?? false)
|
|
294
|
+
// Agents' own token reaches only `/mcp`: not the app's bridge or the routes that start programs.
|
|
295
|
+
const verifyMCPToken = (token: string | null): boolean =>
|
|
296
|
+
verifyToken(token) || (agentBridge?.isAgentToken(token) ?? false)
|
|
297
|
+
|
|
298
|
+
// Warn if auth is disabled while TCP is active — any local process can
|
|
299
|
+
// interact with the server without authentication. Socket-only transport
|
|
300
|
+
// (PORT=0) is safer because 0o600 permissions restrict access to the
|
|
301
|
+
// same OS user.
|
|
302
|
+
if (authToken === null && withTcp) {
|
|
303
|
+
process.stderr.write(
|
|
304
|
+
`WARNING: MCP server is running without authentication on TCP port ${httpPort}. ` +
|
|
305
|
+
'Any local process can interact with the server. ' +
|
|
306
|
+
'Set PAIRDRAW_MCP_AUTH_TOKEN to enable auth, or use PORT=0 for socket-only transport.\n'
|
|
307
|
+
)
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const mcpSessions = createMCPSessionManager({
|
|
311
|
+
serverVersion: MCP_VERSION,
|
|
312
|
+
sessionIdleTimeoutMs: options.sessionIdleTimeoutMs,
|
|
313
|
+
registerTools: (mcpServer: McpServer, agentSession: MCPAgentSession, onToolSettled) =>
|
|
314
|
+
registerTools(mcpServer, {
|
|
315
|
+
policy: toolPolicy,
|
|
316
|
+
mcpRoot,
|
|
317
|
+
sendRPC: sendToBrowser,
|
|
318
|
+
agentSession,
|
|
319
|
+
onToolSettled
|
|
320
|
+
}),
|
|
321
|
+
instructions: ({ kind }) =>
|
|
322
|
+
createServerInstructions({
|
|
323
|
+
policy: toolPolicy,
|
|
324
|
+
filesystemEnabled: Boolean(mcpRoot),
|
|
325
|
+
agentKind: kind
|
|
326
|
+
}),
|
|
327
|
+
onSessionOpened: ({ id, kind, chat }) => {
|
|
328
|
+
sendToBrowser({ command: 'agent_session_opened', args: { session: id, kind, chat } }).catch(
|
|
329
|
+
() => undefined
|
|
330
|
+
)
|
|
331
|
+
},
|
|
332
|
+
onSessionClosed: (sessionId) => {
|
|
333
|
+
// Best-effort: the app may be gone already, and then it shows no agents anyway.
|
|
334
|
+
sendToBrowser({ command: 'agent_session_closed', args: { session: sessionId } }).catch(
|
|
335
|
+
() => undefined
|
|
336
|
+
)
|
|
337
|
+
}
|
|
338
|
+
})
|
|
339
|
+
const browserRPC = createBrowserRPCBridge({
|
|
340
|
+
authToken,
|
|
341
|
+
authorize: verifyToken,
|
|
342
|
+
onConnectionChange: mcpSessions.notifyToolsChanged,
|
|
343
|
+
appWaitTimeoutMs: options.appWaitTimeoutMs
|
|
344
|
+
})
|
|
345
|
+
// Every call into the app, from MCP sessions and /rpc alike, stays within the scope.
|
|
346
|
+
const sendToBrowser = scopeRPC(browserRPC.sendRPC, toolPolicy.scope)
|
|
347
|
+
const toolDescriptors = applyToolPolicy(createToolDescriptors(mcpRoot !== null), toolPolicy)
|
|
348
|
+
|
|
349
|
+
const app = createHonoApp({
|
|
350
|
+
authToken,
|
|
351
|
+
verifyToken,
|
|
352
|
+
verifyMCPToken,
|
|
353
|
+
corsOrigin,
|
|
354
|
+
origins,
|
|
355
|
+
corsAllowed: corsOrigin === null ? null : origins,
|
|
356
|
+
agentBridge,
|
|
357
|
+
// A client limited to the selection reaches no files, as the file tools are left out then.
|
|
358
|
+
fileRoot: mcpRoot !== null && toolPolicy.scope !== 'selection' ? resolve(mcpRoot) : null,
|
|
359
|
+
browserRPC,
|
|
360
|
+
mcpSessions,
|
|
361
|
+
sendToBrowser,
|
|
362
|
+
toolDescriptors
|
|
363
|
+
})
|
|
364
|
+
const wss = new WebSocketServer({ noServer: true })
|
|
365
|
+
const upgrade = createUpgradeHandler(origins, wss, agentBridge)
|
|
366
|
+
|
|
367
|
+
return {
|
|
368
|
+
httpPort,
|
|
369
|
+
withTcp,
|
|
370
|
+
mcpSessions,
|
|
371
|
+
browserRPC,
|
|
372
|
+
sendToBrowser,
|
|
373
|
+
app,
|
|
374
|
+
wss,
|
|
375
|
+
upgrade,
|
|
376
|
+
agentBridge,
|
|
377
|
+
listening,
|
|
378
|
+
authToken,
|
|
379
|
+
disabledTools: toolPolicy.disabledTools,
|
|
380
|
+
scope: toolPolicy.scope
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Unified runtime shutdown: closes browserRPC, clears MCP sessions,
|
|
386
|
+
* terminates WebSocket clients, closes the WSS, and tears down HTTP
|
|
387
|
+
* listeners. Used by both the startup catch block and ServerHandle.close()
|
|
388
|
+
* to ensure no runtime resources (WebSocket, browserRPC, mcpSessions) are
|
|
389
|
+
* left alive.
|
|
390
|
+
*/
|
|
391
|
+
async function shutdownRuntime(
|
|
392
|
+
browserRPC: ReturnType<typeof createBrowserRPCBridge>,
|
|
393
|
+
mcpSessions: ReturnType<typeof createMCPSessionManager>,
|
|
394
|
+
wss: WebSocketServer,
|
|
395
|
+
state: ListenerState,
|
|
396
|
+
agentBridge: AgentBridge | null
|
|
397
|
+
): Promise<void> {
|
|
398
|
+
const errors: unknown[] = []
|
|
399
|
+
try {
|
|
400
|
+
// Agents and sign-ins the companion started end with it.
|
|
401
|
+
await agentBridge?.close()
|
|
402
|
+
} catch (e) {
|
|
403
|
+
errors.push(e)
|
|
404
|
+
}
|
|
405
|
+
try {
|
|
406
|
+
browserRPC.close()
|
|
407
|
+
} catch (e) {
|
|
408
|
+
errors.push(e)
|
|
409
|
+
}
|
|
410
|
+
try {
|
|
411
|
+
await mcpSessions.clear()
|
|
412
|
+
} catch (e) {
|
|
413
|
+
errors.push(e)
|
|
414
|
+
}
|
|
415
|
+
try {
|
|
416
|
+
await closeWssGracefully(wss)
|
|
417
|
+
} catch (e) {
|
|
418
|
+
errors.push(e)
|
|
419
|
+
}
|
|
420
|
+
try {
|
|
421
|
+
await teardownListeners(state)
|
|
422
|
+
} catch (e) {
|
|
423
|
+
errors.push(e)
|
|
424
|
+
}
|
|
425
|
+
if (errors.length === 1) throw errors[0]
|
|
426
|
+
if (errors.length > 1) throw new AggregateError(errors, 'Multiple shutdown errors')
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function buildHandle(
|
|
430
|
+
app: Hono,
|
|
431
|
+
wss: WebSocketServer,
|
|
432
|
+
agentBridge: AgentBridge | null,
|
|
433
|
+
browserRPC: ReturnType<typeof createBrowserRPCBridge>,
|
|
434
|
+
mcpSessions: ReturnType<typeof createMCPSessionManager>,
|
|
435
|
+
state: ListenerState,
|
|
436
|
+
resolvedSocketPath: string | null,
|
|
437
|
+
actualHttpPort: number,
|
|
438
|
+
authToken: string | null,
|
|
439
|
+
startedAt: string
|
|
440
|
+
): ServerHandle {
|
|
441
|
+
// Promise-based lock ensures idempotency even under concurrent calls:
|
|
442
|
+
// the first call creates the teardown promise; subsequent calls return
|
|
443
|
+
// the same promise. JavaScript's event loop guarantees no preemption
|
|
444
|
+
// between the guard check and the assignment.
|
|
445
|
+
let closePromise: Promise<void> | null = null
|
|
446
|
+
|
|
447
|
+
async function close() {
|
|
448
|
+
if (closePromise) return closePromise
|
|
449
|
+
closePromise = (async () => {
|
|
450
|
+
const errors: unknown[] = []
|
|
451
|
+
try {
|
|
452
|
+
// Stop advertising this process before the slower WebSocket grace
|
|
453
|
+
// period. This also makes signal-driven shutdown resilient when a
|
|
454
|
+
// parent process exits before all clients finish closing.
|
|
455
|
+
await cleanupDiscovery(authToken, resolvedSocketPath, actualHttpPort, startedAt)
|
|
456
|
+
} catch (error) {
|
|
457
|
+
errors.push(error)
|
|
458
|
+
}
|
|
459
|
+
try {
|
|
460
|
+
await shutdownRuntime(browserRPC, mcpSessions, wss, state, agentBridge)
|
|
461
|
+
} catch (error) {
|
|
462
|
+
errors.push(error)
|
|
463
|
+
}
|
|
464
|
+
if (errors.length === 1) throw errors[0]
|
|
465
|
+
if (errors.length > 1) throw new AggregateError(errors, 'Multiple shutdown errors')
|
|
466
|
+
})()
|
|
467
|
+
return closePromise
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const primary = state.socketResult?.server ?? state.tcpResult?.server ?? createAppServer(app)
|
|
471
|
+
return {
|
|
472
|
+
app,
|
|
473
|
+
server: primary,
|
|
474
|
+
socketPath: resolvedSocketPath,
|
|
475
|
+
httpPort: actualHttpPort,
|
|
476
|
+
close,
|
|
477
|
+
issuePairingCode: agentBridge ? agentBridge.issuePairingCode : null
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
export async function startServer(options: ServerOptions = {}): Promise<ServerHandle> {
|
|
482
|
+
validateTimeoutOption('appAttachTimeoutMs', options.appAttachTimeoutMs)
|
|
483
|
+
validateTimeoutOption('appWaitTimeoutMs', options.appWaitTimeoutMs)
|
|
484
|
+
validateTimeoutOption('sessionIdleTimeoutMs', options.sessionIdleTimeoutMs)
|
|
485
|
+
const ctx = buildServerContext(options)
|
|
486
|
+
|
|
487
|
+
// Wire shared connection handling BEFORE starting listeners so that
|
|
488
|
+
// any client connecting during startup is handled immediately.
|
|
489
|
+
wireConnectionHandling(ctx.wss, ctx.browserRPC)
|
|
490
|
+
|
|
491
|
+
const state: ListenerState = { socketResult: null, tcpResult: null }
|
|
492
|
+
let startedAt: string
|
|
493
|
+
try {
|
|
494
|
+
state.socketResult = await startSocketListener(ctx.app, ctx.upgrade, options.socketPath ?? null)
|
|
495
|
+
state.tcpResult = ctx.withTcp
|
|
496
|
+
? await tryStartTcp(ctx.app, ctx.upgrade, ctx.httpPort, state)
|
|
497
|
+
: null
|
|
498
|
+
ctx.listening.port = state.tcpResult?.port ?? 0
|
|
499
|
+
const resolvedSocketPath = state.socketResult?.resolvedPath ?? null
|
|
500
|
+
const actualHttpPort = state.tcpResult?.port ?? 0
|
|
501
|
+
|
|
502
|
+
if (!resolvedSocketPath && !actualHttpPort) {
|
|
503
|
+
throw new Error(
|
|
504
|
+
'MCP server has no active listeners (both socket and TCP are unavailable). ' +
|
|
505
|
+
'Ensure Unix domain sockets are supported on this platform or enable TCP with withTcp: true.'
|
|
506
|
+
)
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
startedAt = await tryWriteDiscovery(
|
|
510
|
+
resolvedSocketPath,
|
|
511
|
+
actualHttpPort,
|
|
512
|
+
ctx.authToken,
|
|
513
|
+
MCP_VERSION,
|
|
514
|
+
ctx.disabledTools,
|
|
515
|
+
ctx.scope,
|
|
516
|
+
state
|
|
517
|
+
)
|
|
518
|
+
} catch (err) {
|
|
519
|
+
// Tear down any listeners that started before the failure, then close
|
|
520
|
+
// all resources so nothing leaks when startServer rejects.
|
|
521
|
+
await shutdownRuntime(ctx.browserRPC, ctx.mcpSessions, ctx.wss, state, ctx.agentBridge).catch(
|
|
522
|
+
() => undefined
|
|
523
|
+
)
|
|
524
|
+
throw err
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
const resolvedSocketPath = state.socketResult?.resolvedPath ?? null
|
|
528
|
+
const actualHttpPort = state.tcpResult?.port ?? 0
|
|
529
|
+
|
|
530
|
+
const handle = buildHandle(
|
|
531
|
+
ctx.app,
|
|
532
|
+
ctx.wss,
|
|
533
|
+
ctx.agentBridge,
|
|
534
|
+
ctx.browserRPC,
|
|
535
|
+
ctx.mcpSessions,
|
|
536
|
+
state,
|
|
537
|
+
resolvedSocketPath,
|
|
538
|
+
actualHttpPort,
|
|
539
|
+
ctx.authToken,
|
|
540
|
+
startedAt
|
|
541
|
+
)
|
|
542
|
+
|
|
543
|
+
armAppAttachWatchdog(options.appAttachTimeoutMs, ctx.browserRPC, handle)
|
|
544
|
+
|
|
545
|
+
return handle
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
const MAX_TIMER_MS = 2_147_483_647
|
|
549
|
+
|
|
550
|
+
function validateTimeoutOption(name: string, timeoutMs: number | undefined): void {
|
|
551
|
+
if (timeoutMs === undefined) return
|
|
552
|
+
if (!Number.isSafeInteger(timeoutMs)) {
|
|
553
|
+
throw new RangeError(`${name} must be a safe integer`)
|
|
554
|
+
}
|
|
555
|
+
if (timeoutMs < 0 || timeoutMs > MAX_TIMER_MS) {
|
|
556
|
+
throw new RangeError(`${name} must be in the range 0–${MAX_TIMER_MS}`)
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* Closes an app-spawned server after it remains unattached for the configured
|
|
562
|
+
* grace period. Registering an app cancels the pending shutdown; disconnecting
|
|
563
|
+
* starts a fresh grace period so renderer reloads can reconnect without
|
|
564
|
+
* leaving a permanently orphaned process behind.
|
|
565
|
+
*/
|
|
566
|
+
function armAppAttachWatchdog(
|
|
567
|
+
timeoutMs: number | undefined,
|
|
568
|
+
browserRPC: ReturnType<typeof createBrowserRPCBridge>,
|
|
569
|
+
handle: ServerHandle
|
|
570
|
+
): void {
|
|
571
|
+
if (timeoutMs === undefined || timeoutMs === 0) return
|
|
572
|
+
|
|
573
|
+
let timer: ReturnType<typeof setTimeout> | null = null
|
|
574
|
+
let closing = false
|
|
575
|
+
const clearTimer = () => {
|
|
576
|
+
if (!timer) return
|
|
577
|
+
clearTimeout(timer)
|
|
578
|
+
timer = null
|
|
579
|
+
}
|
|
580
|
+
const armTimer = () => {
|
|
581
|
+
clearTimer()
|
|
582
|
+
timer = setTimeout(() => {
|
|
583
|
+
timer = null
|
|
584
|
+
if (browserRPC.isConnected() || closing) return
|
|
585
|
+
closing = true
|
|
586
|
+
unsubscribe()
|
|
587
|
+
void handle.close().catch((e) => {
|
|
588
|
+
console.error('[MCP] Watchdog: failed to close orphaned (no_app) server:', e)
|
|
589
|
+
})
|
|
590
|
+
}, timeoutMs)
|
|
591
|
+
timer.unref()
|
|
592
|
+
}
|
|
593
|
+
const unsubscribe = browserRPC.subscribeConnectionChange((connected) => {
|
|
594
|
+
if (connected) clearTimer()
|
|
595
|
+
else armTimer()
|
|
596
|
+
})
|
|
597
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import designAuthoring from '#skills/pairdraw/references/design-authoring.md?raw'
|
|
2
|
+
// The installable skill in `skills/pairdraw`, embedded at build time so the published server
|
|
3
|
+
// serves the copy it shipped with and never reads the repository at runtime.
|
|
4
|
+
import skill from '#skills/pairdraw/SKILL.md?raw'
|
|
5
|
+
|
|
6
|
+
/** The skill's name, as its frontmatter and `npx skills add` know it. */
|
|
7
|
+
export const SKILL_NAME = 'pairdraw'
|
|
8
|
+
|
|
9
|
+
/** Every file of the skill, by its path inside the skill folder, as `SKILL.md` links them. */
|
|
10
|
+
export const SKILL_FILE_PATHS = ['SKILL.md', 'references/design-authoring.md'] as const
|
|
11
|
+
export type SkillFilePath = (typeof SKILL_FILE_PATHS)[number]
|
|
12
|
+
|
|
13
|
+
export interface SkillFile {
|
|
14
|
+
path: SkillFilePath
|
|
15
|
+
title: string
|
|
16
|
+
description: string
|
|
17
|
+
text: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const SKILL_FILES: Readonly<Record<SkillFilePath, SkillFile>> = {
|
|
21
|
+
'SKILL.md': {
|
|
22
|
+
path: 'SKILL.md',
|
|
23
|
+
title: 'Pairdraw agent skill',
|
|
24
|
+
description:
|
|
25
|
+
'How to inspect, edit, and export designs in the running Pairdraw editor with these tools, the CLI, JSX, and eval. Read it first.',
|
|
26
|
+
text: skill
|
|
27
|
+
},
|
|
28
|
+
'references/design-authoring.md': {
|
|
29
|
+
path: 'references/design-authoring.md',
|
|
30
|
+
title: 'Pairdraw design authoring reference',
|
|
31
|
+
description:
|
|
32
|
+
'The JSX the render tool accepts: layout, paint, text, variables, components, and controls, with tested examples. Read it before creating or changing designs.',
|
|
33
|
+
text: designAuthoring
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Where a skill file is served as an MCP resource. */
|
|
38
|
+
export function skillResourceURI(path: SkillFilePath): string {
|
|
39
|
+
return `pairdraw://skills/${SKILL_NAME}/${path}`
|
|
40
|
+
}
|