@pairdraw/mcp 0.17.0 → 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/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-DfBiXAjt.mjs} +262 -209
- package/dist/server-DfBiXAjt.mjs.map +1 -0
- package/dist/server.d.mts +7 -0
- package/dist/server.mjs +1 -1
- package/dist/stdio.mjs +3 -3
- package/dist/tools.mjs +1 -1
- package/package.json +2 -2
- package/src/index.ts +3 -0
- package/src/server/http-app.ts +172 -0
- package/src/server/sessions.ts +40 -4
- package/src/server.ts +32 -162
- package/src/skill/instructions.ts +10 -1
- 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
|
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-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 {
|
|
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-
|
|
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";
|
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-
|
|
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.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.
|
|
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",
|
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
|
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
|
|
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 {
|
|
10
|
+
import { isAuthorized } from '#mcp/auth'
|
|
14
11
|
import { createBrowserRPCBridge } from '#mcp/browser-rpc'
|
|
15
|
-
import
|
|
16
|
-
import
|
|
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 {
|
|
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
|
|
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,148 +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: httpOptions.MCP_CORS_METHODS,
|
|
155
|
-
allowHeaders: httpOptions.MCP_CORS_HEADERS,
|
|
156
|
-
exposeHeaders: httpOptions.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', httpOptions.limitBody, 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
|
-
const requireMCPToken = async (c: Context, next: Next) => {
|
|
207
|
-
const token = mcpRequestToken(c.req.header('authorization'), c.req.header('x-mcp-token'))
|
|
208
|
-
return verifyMCPToken(token) ? next() : c.json({ error: 'Unauthorized' }, 401)
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
app.all('/mcp', requireMCPToken, httpOptions.limitBody, async (c) => {
|
|
212
|
-
if (!MCP_METHODS.includes(c.req.method)) {
|
|
213
|
-
return c.json(
|
|
214
|
-
{ error: 'Method not allowed' },
|
|
215
|
-
{ status: 405, headers: { Allow: MCP_METHODS.join(', ') } }
|
|
216
|
-
)
|
|
217
|
-
}
|
|
218
|
-
const sessionId = c.req.header('mcp-session-id') ?? undefined
|
|
219
|
-
if (sessionId) {
|
|
220
|
-
// Never allocate a session for an unknown ID: DELETE or a stale client
|
|
221
|
-
// would burn a slot it can never use.
|
|
222
|
-
const existing = mcpSessions.getExistingTransport(sessionId)
|
|
223
|
-
if ('error' in existing) {
|
|
224
|
-
if (existing.error === 'closed') {
|
|
225
|
-
return c.json({ error: 'MCP server is shutting down' }, 503)
|
|
226
|
-
}
|
|
227
|
-
return c.json({ error: 'MCP session not found' }, 404)
|
|
228
|
-
}
|
|
229
|
-
if (c.req.method !== 'DELETE') return existing.handleRequest(c.req.raw)
|
|
230
|
-
try {
|
|
231
|
-
return await existing.handleRequest(c.req.raw)
|
|
232
|
-
} finally {
|
|
233
|
-
await mcpSessions.deleteSession(sessionId)
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
// Only an initializing POST may start a session.
|
|
237
|
-
if (c.req.method !== 'POST') {
|
|
238
|
-
return c.json({ error: 'Missing MCP session id' }, 400)
|
|
239
|
-
}
|
|
240
|
-
const transport = await mcpSessions.resolveTransport(
|
|
241
|
-
undefined,
|
|
242
|
-
sessionOpener(c.req.header(MCP_AGENT_HEADER), c.req.header(MCP_CHAT_HEADER))
|
|
243
|
-
)
|
|
244
|
-
if ('error' in transport) {
|
|
245
|
-
if (transport.error === 'closed') {
|
|
246
|
-
return c.json({ error: 'MCP server is shutting down' }, 503)
|
|
247
|
-
}
|
|
248
|
-
return c.json(
|
|
249
|
-
{ error: 'Too many active MCP sessions' },
|
|
250
|
-
{ status: 503, headers: { 'Retry-After': '5' } }
|
|
251
|
-
)
|
|
252
|
-
}
|
|
253
|
-
return transport.handleRequest(c.req.raw)
|
|
254
|
-
})
|
|
255
|
-
|
|
256
|
-
agentBridge?.routes(app)
|
|
257
|
-
|
|
258
|
-
return app
|
|
259
|
-
}
|
|
260
|
-
|
|
261
118
|
function buildServerContext(options: ServerOptions) {
|
|
262
119
|
const httpPort = options.httpPort ?? 7600
|
|
263
120
|
const evalRequestedWithAgents = options.agents !== undefined && (options.enableEval ?? false)
|
|
@@ -360,7 +217,8 @@ function buildServerContext(options: ServerOptions) {
|
|
|
360
217
|
browserRPC,
|
|
361
218
|
mcpSessions,
|
|
362
219
|
sendToBrowser,
|
|
363
|
-
toolDescriptors
|
|
220
|
+
toolDescriptors,
|
|
221
|
+
version: MCP_VERSION
|
|
364
222
|
})
|
|
365
223
|
const wss = new WebSocketServer({ noServer: true })
|
|
366
224
|
const upgrade = createUpgradeHandler(origins, wss, agentBridge)
|
|
@@ -541,7 +399,12 @@ export async function startServer(options: ServerOptions = {}): Promise<ServerHa
|
|
|
541
399
|
startedAt
|
|
542
400
|
)
|
|
543
401
|
|
|
544
|
-
armAppAttachWatchdog(
|
|
402
|
+
armAppAttachWatchdog(
|
|
403
|
+
options.appAttachTimeoutMs,
|
|
404
|
+
ctx.browserRPC,
|
|
405
|
+
handle,
|
|
406
|
+
options.onAppAttachTimeout
|
|
407
|
+
)
|
|
545
408
|
|
|
546
409
|
return handle
|
|
547
410
|
}
|
|
@@ -567,7 +430,8 @@ function validateTimeoutOption(name: string, timeoutMs: number | undefined): voi
|
|
|
567
430
|
function armAppAttachWatchdog(
|
|
568
431
|
timeoutMs: number | undefined,
|
|
569
432
|
browserRPC: ReturnType<typeof createBrowserRPCBridge>,
|
|
570
|
-
handle: ServerHandle
|
|
433
|
+
handle: ServerHandle,
|
|
434
|
+
onTimeout: (() => void) | undefined
|
|
571
435
|
): void {
|
|
572
436
|
if (timeoutMs === undefined || timeoutMs === 0) return
|
|
573
437
|
|
|
@@ -585,9 +449,15 @@ function armAppAttachWatchdog(
|
|
|
585
449
|
if (browserRPC.isConnected() || closing) return
|
|
586
450
|
closing = true
|
|
587
451
|
unsubscribe()
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
})
|
|
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
|
+
})
|
|
591
461
|
}, timeoutMs)
|
|
592
462
|
timer.unref()
|
|
593
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
|
-
|
|
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.',
|
package/src/tool/manifest.ts
CHANGED
|
@@ -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'],
|
package/src/tool/output.ts
CHANGED
|
@@ -1,18 +1,12 @@
|
|
|
1
1
|
import { constants } from 'node:fs'
|
|
2
|
-
import {
|
|
3
|
-
lstat,
|
|
4
|
-
mkdir,
|
|
5
|
-
open,
|
|
6
|
-
readlink,
|
|
7
|
-
realpath,
|
|
8
|
-
writeFile,
|
|
9
|
-
type FileHandle
|
|
10
|
-
} from 'node:fs/promises'
|
|
2
|
+
import { lstat, mkdir, open, readlink, realpath, type FileHandle } from 'node:fs/promises'
|
|
11
3
|
import { dirname, basename, isAbsolute, join, parse, resolve, sep as osSep } from 'node:path'
|
|
12
4
|
|
|
13
5
|
import { compact } from 'es-toolkit/array'
|
|
14
6
|
import { toUint8Array } from 'js-base64'
|
|
15
7
|
|
|
8
|
+
import { writeFileAtomic } from '@pairdraw/core/node/fs'
|
|
9
|
+
|
|
16
10
|
import { ok } from '#mcp/result'
|
|
17
11
|
import type { MCPResult } from '#mcp/result'
|
|
18
12
|
|
|
@@ -257,8 +251,9 @@ export async function writeInsideRoot(
|
|
|
257
251
|
const { resolved, realPath } = await resolveSafePath(filePath, root)
|
|
258
252
|
// Use the canonical realPath for filesystem operations to prevent TOCTOU:
|
|
259
253
|
// an attacker could swap a directory component with a symlink between
|
|
260
|
-
// resolveSafePath's validation and the
|
|
261
|
-
// realpath-validated path ensures the write lands inside root.
|
|
254
|
+
// resolveSafePath's validation and the write. Writing to the
|
|
255
|
+
// realpath-validated path ensures the write lands inside root. The replace
|
|
256
|
+
// does not follow a symlink planted at that path after the check.
|
|
262
257
|
const parentDir = dirname(realPath)
|
|
263
258
|
await mkdir(parentDir, { recursive: true })
|
|
264
259
|
// TOCTOU mitigation: re-verify the parent directory still resolves inside
|
|
@@ -266,7 +261,7 @@ export async function writeInsideRoot(
|
|
|
266
261
|
// with a symlink between resolveSafePath and the write would be detected
|
|
267
262
|
// here — realpath follows the ancestor symlink and resolves outside root.
|
|
268
263
|
await resolveSafePath(parentDir, root)
|
|
269
|
-
await
|
|
264
|
+
await writeFileAtomic(realPath, content)
|
|
270
265
|
await resolveSafePath(realPath, root)
|
|
271
266
|
const byteLength =
|
|
272
267
|
typeof content === 'string' ? Buffer.byteLength(content, 'utf8') : content.byteLength
|