@pairdraw/mcp 0.16.2 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
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-Byl3Tcf4.mjs";
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-DfBiXAjt.mjs";
2
2
  export { MCP_AGENT_KINDS, MCP_VERSION, fail, ok, registerTools, startServer };
package/dist/stdio.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import "./rolldown-runtime-ClRpJifh.mjs";
3
- import { a as createServerInstructions, c as registerSkill, s as registerTools, t as MCP_VERSION } from "./server-Byl3Tcf4.mjs";
3
+ import { c as registerSkill, r as createServerInstructions, s as registerTools, t as MCP_VERSION } from "./server-DfBiXAjt.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-B8Ka4WRH.mjs";
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-CB2Bv5WA.mjs";
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";
package/dist/tools.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./rolldown-runtime-ClRpJifh.mjs";
2
- import { a as serializeDisabledTools, n as isToolEnabled, o as createToolDescriptors } from "./policy-B8Ka4WRH.mjs";
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.16.2",
3
+ "version": "0.18.0",
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.16.2",
18
+ "@pairdraw/core": "^0.18.0",
19
19
  "@valibot/to-json-schema": "^1.8.0",
20
20
  "es-toolkit": "^1.52.0",
21
21
  "hono": "^4.13.13",
@@ -1,5 +1,25 @@
1
+ import { bodyLimit } from 'hono/body-limit'
2
+
3
+ import { MAX_FILE_TRANSFER_BYTES } from '#mcp/tool/output'
4
+
1
5
  export const MCP_CORS_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
2
6
 
7
+ /**
8
+ * The largest body `/rpc` and `/mcp` read. Tool arguments carry files inline as Base64, such as
9
+ * `set_image_fill`'s `image_data`, so a file as large as `/files` passes still fits, with room
10
+ * for the rest of the request.
11
+ */
12
+ export const MAX_REQUEST_BODY_BYTES = 2 * MAX_FILE_TRANSFER_BYTES
13
+
14
+ /**
15
+ * Refuses a larger body, counted as it streams in, so one without Content-Length is bounded too.
16
+ * Routes check the token before it, so a caller without one never makes the server buffer.
17
+ */
18
+ export const limitBody = bodyLimit({
19
+ maxSize: MAX_REQUEST_BODY_BYTES,
20
+ onError: (c) => c.json({ error: 'Request is too large' }, 413)
21
+ })
22
+
3
23
  // x-mcp-token: Pairdraw extension for MCP clients that cannot set the
4
24
  // Authorization header (e.g. some IDE plugins). Not part of the MCP spec.
5
25
  export const MCP_CORS_HEADERS = [
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
+ }
@@ -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
- const MAX_MCP_SESSIONS = 10
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 >= MAX_MCP_SESSIONS) {
279
- return Promise.resolve({ error: 'too_many' })
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
package/src/server.ts CHANGED
@@ -3,22 +3,17 @@ import type { Server as HttpServer } from 'node:http'
3
3
  import { resolve } from 'node:path'
4
4
 
5
5
  import type { McpServer } from '@modelcontextprotocol/server'
6
- import { Hono, type Context, type Next } from 'hono'
7
- import { cors } from 'hono/cors'
6
+ import type { Hono } from 'hono'
8
7
  import { WebSocketServer } from 'ws'
9
8
 
10
- import { MCP_AGENT_HEADER, MCP_CHAT_HEADER } from '@pairdraw/core/constants'
11
-
12
9
  import { createAgentBridge, type AgentBridge, type AgentBridgeOptions } from '#mcp/agents/index'
13
- import { bearerToken, isAuthorized, mcpRequestToken } from '#mcp/auth'
10
+ import { isAuthorized } from '#mcp/auth'
14
11
  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'
12
+ import { createHonoApp } from '#mcp/server/http-app'
13
+ import { createMCPSessionManager } from '#mcp/server/sessions'
19
14
  import { createServerInstructions } from '#mcp/skill/instructions'
20
15
  import { createToolDescriptors } from '#mcp/tool/manifest'
21
- import type { ToolDescriptor, ToolPolicy } from '#mcp/tool/metadata'
16
+ import type { ToolPolicy } from '#mcp/tool/metadata'
22
17
  import { applyToolPolicy } from '#mcp/tool/policy'
23
18
  import { registerTools, type MCPAgentSession } from '#mcp/tool/registration'
24
19
  import { scopeRPC, type MCPToolScope } from '#mcp/tool/scope'
@@ -26,7 +21,6 @@ import { admittedOrigins } from '#mcp/transport/origins'
26
21
 
27
22
  import packageJSON from '../package.json' with { type: 'json' }
28
23
  import { wireConnectionHandling } from './server/connections'
29
- import { mcpInstallCommand } from './server/install-command'
30
24
  import {
31
25
  type ListenerState,
32
26
  cleanupDiscovery,
@@ -37,12 +31,10 @@ import {
37
31
  tryStartTcp,
38
32
  tryWriteDiscovery
39
33
  } from './server/lifecycle'
40
- import { createUpgradeHandler, originGuard } from './server/origin'
34
+ import { createUpgradeHandler } from './server/origin'
41
35
 
42
36
  export const MCP_VERSION: string = packageJSON.version
43
37
 
44
- const MCP_METHODS: readonly string[] = ['GET', 'POST', 'DELETE']
45
-
46
38
  export { fail, ok, type MCPContent, type MCPResult } from '#mcp/result'
47
39
 
48
40
  export {
@@ -81,6 +73,13 @@ export interface ServerOptions {
81
73
  * app opts in when it spawns the server.
82
74
  */
83
75
  appAttachTimeoutMs?: number
76
+ /**
77
+ * Called once the app-attach watchdog has closed the server. A process that
78
+ * exists only for this server passes a shutdown, such as `process.exit`;
79
+ * without one, anything else still holding the event loop keeps it running
80
+ * with no listeners.
81
+ */
82
+ onAppAttachTimeout?: () => void
84
83
  /**
85
84
  * How long an MCP session may sit without requests before it is closed.
86
85
  * Defaults to 15 minutes; 0 disables expiration. An open GET/SSE stream
@@ -116,147 +115,6 @@ export interface ServerHandle {
116
115
  issuePairingCode: (() => string) | null
117
116
  }
118
117
 
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
118
  function buildServerContext(options: ServerOptions) {
261
119
  const httpPort = options.httpPort ?? 7600
262
120
  const evalRequestedWithAgents = options.agents !== undefined && (options.enableEval ?? false)
@@ -359,7 +217,8 @@ function buildServerContext(options: ServerOptions) {
359
217
  browserRPC,
360
218
  mcpSessions,
361
219
  sendToBrowser,
362
- toolDescriptors
220
+ toolDescriptors,
221
+ version: MCP_VERSION
363
222
  })
364
223
  const wss = new WebSocketServer({ noServer: true })
365
224
  const upgrade = createUpgradeHandler(origins, wss, agentBridge)
@@ -540,7 +399,12 @@ export async function startServer(options: ServerOptions = {}): Promise<ServerHa
540
399
  startedAt
541
400
  )
542
401
 
543
- armAppAttachWatchdog(options.appAttachTimeoutMs, ctx.browserRPC, handle)
402
+ armAppAttachWatchdog(
403
+ options.appAttachTimeoutMs,
404
+ ctx.browserRPC,
405
+ handle,
406
+ options.onAppAttachTimeout
407
+ )
544
408
 
545
409
  return handle
546
410
  }
@@ -566,7 +430,8 @@ function validateTimeoutOption(name: string, timeoutMs: number | undefined): voi
566
430
  function armAppAttachWatchdog(
567
431
  timeoutMs: number | undefined,
568
432
  browserRPC: ReturnType<typeof createBrowserRPCBridge>,
569
- handle: ServerHandle
433
+ handle: ServerHandle,
434
+ onTimeout: (() => void) | undefined
570
435
  ): void {
571
436
  if (timeoutMs === undefined || timeoutMs === 0) return
572
437
 
@@ -584,9 +449,15 @@ function armAppAttachWatchdog(
584
449
  if (browserRPC.isConnected() || closing) return
585
450
  closing = true
586
451
  unsubscribe()
587
- void handle.close().catch((e) => {
588
- console.error('[MCP] Watchdog: failed to close orphaned (no_app) server:', e)
589
- })
452
+ // The reason a server the app owned went away is otherwise invisible: it wrote nothing
453
+ // else to stderr, and its discovery file and socket are gone with it.
454
+ process.stderr.write(`[MCP] No app attached for ${timeoutMs} ms; closing the server.\n`)
455
+ void handle
456
+ .close()
457
+ .then(() => onTimeout?.())
458
+ .catch((e) => {
459
+ console.error('[MCP] Watchdog: failed to close orphaned (no_app) server:', e)
460
+ })
590
461
  }, timeoutMs)
591
462
  timer.unref()
592
463
  }
@@ -28,11 +28,20 @@ function skillParagraph(enabled: (name: string) => boolean): string {
28
28
  return `${lead}, read the ${SKILL_NAME} skill: call read_skill for SKILL.md, then read_skill with path "${REFERENCE_PATH}"${reference}. Clients without that tool can read the same files as the resources ${SKILL_FILE_URI} and ${REFERENCE_URI}.`
29
29
  }
30
30
 
31
+ function closedRecovery(enabled: (name: string) => boolean): string {
32
+ const actions = compact([
33
+ enabled('new_document') && 'new_document',
34
+ enabled('open_file') && 'open_file'
35
+ ])
36
+ if (actions.length === 0) return ''
37
+ return ` After that document is closed, pass document_id from list_documents, or call ${actions.join(' or ')}.`
38
+ }
39
+
31
40
  function usageParagraph(enabled: (name: string) => boolean, policy: ToolPolicy): string {
32
41
  const undo = enabled('undo')
33
42
  return compact([
34
43
  enabled('list_documents') &&
35
- 'When several documents may be open, call list_documents first and pass its document_id and page_id to later calls.',
44
+ `When several documents may be open, call list_documents first and pass its document_id and page_id to later calls. Each session keeps the document it edits. Home is not a document. Closing without document_id only closes a document this session opened.${closedRecovery(enabled)}`,
36
45
  policy.scope === 'document' &&
37
46
  enabled('export_image') &&
38
47
  'Check visual changes with export_image.',
@@ -84,7 +84,7 @@ export function createToolDescriptors(filesystemEnabled: boolean): ToolDescripto
84
84
  {
85
85
  name: 'close_file',
86
86
  description:
87
- 'Close an open document tab. With unsaved changes it fails unless unsaved is "save" or "discard"; it never prompts in the app.',
87
+ 'Close an open document tab. With unsaved changes it fails unless unsaved is "save" or "discard"; it never prompts in the app. The document’s draft and recovery copy stay, so the person can recover its work from Home.',
88
88
  effect: 'write',
89
89
  availability: 'default',
90
90
  capabilities: ['document:write', 'filesystem:write'],