cursor-delegate-mcp 2.9.0 → 2.11.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/CHANGELOG.md +66 -0
- package/package.json +3 -2
- package/src/acp-client.js +24 -30
- package/src/acp-enums.js +3 -8
- package/src/delegate.js +117 -129
- package/src/doctor.js +78 -31
- package/src/errors.js +2 -4
- package/src/jsonrpc.js +14 -26
- package/src/model-options.js +9 -14
- package/src/proc.js +8 -13
- package/src/request-router.js +4 -11
- package/src/server.js +107 -119
- package/src/session-supervisor.js +4 -6
- package/src/spawn.js +124 -26
- package/src/turn-state.js +14 -22
- package/src/version.js +2 -4
package/src/server.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
import process from "node:process";
|
|
3
3
|
import { realpathSync } from "node:fs";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
-
import { McpServer } from "@modelcontextprotocol/
|
|
6
|
-
import {
|
|
5
|
+
import { McpServer, CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from "@modelcontextprotocol/server";
|
|
6
|
+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import { DEFAULT_MODEL, runDelegate as runDelegateDefault } from "./delegate.js";
|
|
9
9
|
import { runDoctor as runDoctorDefault } from "./doctor.js";
|
|
@@ -24,17 +24,15 @@ if (nodeMajor < 20) {
|
|
|
24
24
|
process.exit(1);
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
// sessionId -> the
|
|
28
|
-
//
|
|
29
|
-
// keying one handle per id let whichever finished first deregister the other — after which
|
|
30
|
-
// cancel reported a running session as already ended.
|
|
27
|
+
// sessionId -> the delegations running on it. A set because a resume can race the turn it
|
|
28
|
+
// resumes; with one handle per id, whichever finished first deregistered the other.
|
|
31
29
|
const inFlight = new Map();
|
|
32
30
|
function registerInFlight(map, sessionId, handle) {
|
|
33
31
|
const handles = map.get(sessionId);
|
|
34
32
|
if (handles) handles.add(handle);
|
|
35
33
|
else map.set(sessionId, new Set([handle]));
|
|
36
34
|
}
|
|
37
|
-
/** @returns {import("@modelcontextprotocol/
|
|
35
|
+
/** @returns {import("@modelcontextprotocol/server").CallToolResult} */
|
|
38
36
|
function cancelResult(status, sessionId) {
|
|
39
37
|
return { content: [{ type: "text", text: JSON.stringify({ status, sessionId }) }] };
|
|
40
38
|
}
|
|
@@ -44,31 +42,24 @@ function unregisterInFlight(map, sessionId, handle) {
|
|
|
44
42
|
handles.delete(handle);
|
|
45
43
|
if (handles.size === 0) map.delete(sessionId);
|
|
46
44
|
}
|
|
47
|
-
// Delegations whose session has not opened yet
|
|
48
|
-
//
|
|
49
|
-
// there is a live, auto-approved agent that the map cannot name. Shutdown walks this too.
|
|
50
|
-
// cancel deliberately does not: an id the caller has never been given is not one it can pass.
|
|
45
|
+
// Delegations whose session has not opened yet: the agent runs ~3.4s before inFlight can key it.
|
|
46
|
+
// Shutdown walks this; cancel cannot, since the caller has no id for these yet.
|
|
51
47
|
const pendingDelegations = new Set();
|
|
52
48
|
|
|
53
|
-
// Session ids seen this process, kept after the turn ends so cancel can tell a finished
|
|
54
|
-
//
|
|
55
|
-
// long-lived server does not grow without limit.
|
|
49
|
+
// Session ids seen by this process, kept after the turn ends so cancel can tell a finished
|
|
50
|
+
// (still resumable) session from an id that never existed. Bounded.
|
|
56
51
|
const seenSessions = new Set();
|
|
57
52
|
const SEEN_SESSIONS_CAP = 500;
|
|
58
53
|
function rememberSession(set, id) {
|
|
59
54
|
if (id == null) return;
|
|
60
|
-
//
|
|
61
|
-
// resumed moves back to the recent end, so it outlives an equally old id that was seen once
|
|
62
|
-
// and never again. Without it the id a caller is actually working with ages out on insertion
|
|
63
|
-
// order alone, and cancel then calls a live, resumable session one that never existed.
|
|
55
|
+
// Delete-then-add makes the Set an LRU, so a session still being resumed outlives one seen once.
|
|
64
56
|
if (set.has(id)) set.delete(id);
|
|
65
57
|
set.add(id);
|
|
66
58
|
if (set.size > SEEN_SESSIONS_CAP) set.delete(set.values().next().value);
|
|
67
59
|
}
|
|
68
60
|
|
|
69
|
-
//
|
|
70
|
-
//
|
|
71
|
-
// descriptions, read while the call is being written.
|
|
61
|
+
// Read at connect, so only what decides whether to delegate at all. Call-time facts belong on
|
|
62
|
+
// the parameter descriptions.
|
|
72
63
|
export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the delegate tool. Every permission the agent requests is auto-approved, in every mode: agent/plan/ask reach any file the user account can, and mode instructs the agent rather than limiting it. Scope workspace tightly and review the git diff after every run — filesReportedByEditTools carries only what the agent's edit tools reported; the diff is authoritative.`;
|
|
73
64
|
|
|
74
65
|
const planEntrySchema = z.object({
|
|
@@ -77,10 +68,9 @@ const planEntrySchema = z.object({
|
|
|
77
68
|
status: z.enum(PLAN_STATUSES).optional(),
|
|
78
69
|
}).passthrough();
|
|
79
70
|
|
|
80
|
-
// No outputSchema:
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
// its tool description.
|
|
71
|
+
// No outputSchema: it requires structuredContent too, and a host that reads both (Codex) puts the
|
|
72
|
+
// payload in context twice. Strict copy in delegate.test.js; field meanings in
|
|
73
|
+
// skills/delegate/reference.md.
|
|
84
74
|
export const delegateOutputShape = {
|
|
85
75
|
result: z.string(),
|
|
86
76
|
resultSource: z.enum(["pre-tool-fallback", "none"]).optional(),
|
|
@@ -111,9 +101,9 @@ export const delegateOutputShape = {
|
|
|
111
101
|
}).optional(),
|
|
112
102
|
};
|
|
113
103
|
|
|
114
|
-
// Same
|
|
115
|
-
//
|
|
116
|
-
//
|
|
104
|
+
// Same contract as delegateOutputShape; strict copy in doctor.test.js. Relayed agent fields stay
|
|
105
|
+
// unknown so an odd protocolVersion is a diagnostic, not a failed call. Handshake is its own
|
|
106
|
+
// shape because .strict() does not look inside a nested object.
|
|
117
107
|
export const doctorHandshakeShape = {
|
|
118
108
|
ok: z.boolean(),
|
|
119
109
|
error: z.string().optional(),
|
|
@@ -122,7 +112,7 @@ export const doctorHandshakeShape = {
|
|
|
122
112
|
models: z.array(z.unknown()).optional(),
|
|
123
113
|
currentModel: z.unknown().optional(),
|
|
124
114
|
modes: z.array(z.unknown()).optional(),
|
|
125
|
-
// Built here
|
|
115
|
+
// Built here, not relayed, so it gets a real type.
|
|
126
116
|
currentModelOptions: z.array(z.object({
|
|
127
117
|
id: z.string(),
|
|
128
118
|
name: z.string().optional(),
|
|
@@ -140,13 +130,14 @@ export const doctorAgentShape = {
|
|
|
140
130
|
handshake: z.object(doctorHandshakeShape).passthrough().optional(),
|
|
141
131
|
};
|
|
142
132
|
|
|
143
|
-
// agent is split out
|
|
133
|
+
// agent is split out for the same reason as handshake.
|
|
144
134
|
export const doctorOutputShape = {
|
|
145
135
|
plugin: z.object({ version: z.string() }).passthrough(),
|
|
146
136
|
client: z.object({
|
|
147
137
|
name: z.string().nullable(),
|
|
148
138
|
version: z.string().nullable(),
|
|
149
139
|
capabilities: z.record(z.string(), z.unknown()),
|
|
140
|
+
protocolVersion: z.string().optional(),
|
|
150
141
|
}).passthrough(),
|
|
151
142
|
agent: z.object(doctorAgentShape).passthrough(),
|
|
152
143
|
runtime: z.object({
|
|
@@ -166,8 +157,7 @@ export const delegateInputSchema = z.object({
|
|
|
166
157
|
workspace: z.string().trim().min(1, "workspace must not be blank").describe("The agent's working directory, not a limit. Smallest directory holding the task's files; with no such directory the project root is the floor. Must already exist; never create one for the call."),
|
|
167
158
|
model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL).describe("Bare ACP family id, version included: composer-2.5, grok-4.5, claude-opus-5, gpt-5.6-sol. doctor deep:true lists every id."),
|
|
168
159
|
fast: z.boolean().default(false).describe("Fast tier; higher cost — only when the user asks."),
|
|
169
|
-
//
|
|
170
|
-
// string and the bridge validates the exact token against the live option list.
|
|
160
|
+
// Open string: a model's values are known only once it is selected, then validated live.
|
|
171
161
|
effort: z.string().trim().min(1).optional().describe("Exact Cursor thinking-effort value for the selected model. Values differ per model and some expose no effort option; invalid values fail before the prompt and name the accepted set. Pass only when the user asks for Cursor effort — the host's own reasoning setting is unrelated."),
|
|
172
162
|
context: z.string().trim().min(1).optional().describe("Context window size; gpt-5.x accepts 272k and 1m. Do not pass speculatively."),
|
|
173
163
|
contextFiles: z.array(z.string()).optional().describe("Paths to attach instead of pasting contents into spec. Text becomes references the agent may open; images (png/jpg/gif/webp, <5MB) are sent inline. Relative paths resolve against workspace but are not limited to it. Skips are reported in protocolWarnings, never fatal."),
|
|
@@ -175,27 +165,26 @@ export const delegateInputSchema = z.object({
|
|
|
175
165
|
|
|
176
166
|
/**
|
|
177
167
|
* @param {{
|
|
178
|
-
* args: any,
|
|
168
|
+
* args: any, ctx?: any,
|
|
179
169
|
* runDelegate: (opts: any) => Promise<any>,
|
|
180
170
|
* inFlight: Map<string, Set<any>>,
|
|
181
171
|
* pending?: Set<any>,
|
|
182
172
|
* seenSessions?: Set<string>,
|
|
183
173
|
* }} deps
|
|
184
|
-
* @returns {Promise<import("@modelcontextprotocol/
|
|
174
|
+
* @returns {Promise<import("@modelcontextprotocol/server").CallToolResult>}
|
|
185
175
|
*/
|
|
186
|
-
export async function runDelegateTool({ args,
|
|
176
|
+
export async function runDelegateTool({ args, ctx, runDelegate, inFlight, pending = new Set(), seenSessions = new Set() }) {
|
|
187
177
|
const { spec, mode, resumeSessionId, workspace, model, fast, effort, context, contextFiles } = args;
|
|
188
178
|
|
|
189
|
-
const progressToken =
|
|
179
|
+
const progressToken = ctx?.mcpReq?._meta?.progressToken;
|
|
190
180
|
/** @type {(message: string) => void} */
|
|
191
181
|
let onProgress = () => {};
|
|
192
182
|
if (progressToken != null) {
|
|
193
183
|
let progress = 0;
|
|
194
184
|
onProgress = (message) => {
|
|
195
|
-
//
|
|
196
|
-
// server. The try stays for a sync throw, which lands before Promise.resolve can wrap it.
|
|
185
|
+
// An unhandled rejection from notify would exit the server; the try catches a sync throw.
|
|
197
186
|
try {
|
|
198
|
-
Promise.resolve(
|
|
187
|
+
Promise.resolve(ctx.mcpReq.notify({
|
|
199
188
|
method: "notifications/progress",
|
|
200
189
|
params: { progressToken, progress: ++progress, message },
|
|
201
190
|
})).catch(() => {});
|
|
@@ -217,39 +206,34 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
|
|
|
217
206
|
context,
|
|
218
207
|
contextFiles,
|
|
219
208
|
onProgress,
|
|
220
|
-
signal:
|
|
209
|
+
signal: ctx?.mcpReq?.signal,
|
|
221
210
|
onClientReady: (client) => {
|
|
222
211
|
handle = { client, cancelRequested: false };
|
|
223
212
|
pending.add(handle);
|
|
224
213
|
},
|
|
225
214
|
onSessionReady: (sessionId, client) => {
|
|
226
215
|
capturedSessionId = sessionId;
|
|
227
|
-
// The same handle moves across, so a
|
|
228
|
-
// one side of it rather than on neither.
|
|
216
|
+
// The same handle moves across, so a racing shutdown finds it on exactly one side.
|
|
229
217
|
handle ??= { client, cancelRequested: false };
|
|
230
218
|
pending.delete(handle);
|
|
231
219
|
registerInFlight(inFlight, sessionId, handle);
|
|
232
220
|
rememberSession(seenSessions, sessionId);
|
|
233
|
-
//
|
|
234
|
-
// can call tools concurrently has something to pass to cancel mid-run — otherwise the
|
|
235
|
-
// id only arrives when delegate returns, by which point there is nothing to cancel.
|
|
236
|
-
// (Hosts that serialize tool calls still cannot cancel in flight; that is a host limit.)
|
|
221
|
+
// Sent now so a host that can call tools concurrently has an id to cancel mid-run.
|
|
237
222
|
onProgress(`session ready: ${sessionId}`);
|
|
238
223
|
},
|
|
224
|
+
onTurnEnd: () => { if (handle) handle.ended = true; },
|
|
239
225
|
});
|
|
240
226
|
if (handle?.cancelRequested) out.cancelRequested = true;
|
|
241
227
|
return { content: [{ type: "text", text: JSON.stringify(out) }] };
|
|
242
228
|
} catch (err) {
|
|
243
229
|
return {
|
|
244
|
-
// The reason
|
|
245
|
-
// prose to tell a timeout from a rejected argument.
|
|
230
|
+
// The reason up front, so the caller need not parse prose to tell a timeout from a bad argument.
|
|
246
231
|
content: [{ type: "text", text: `delegate failed${err?.reason ? ` [${err.reason}]` : ""}: ` + (err?.message || String(err)) }],
|
|
247
232
|
isError: true,
|
|
248
233
|
};
|
|
249
234
|
} finally {
|
|
250
|
-
// Drops only this delegation's
|
|
251
|
-
//
|
|
252
|
-
// in pending, and one that opened is only ever in the map — the delete covers both.
|
|
235
|
+
// Drops only this delegation's handle, from whichever of pending or the map holds it; the id
|
|
236
|
+
// stays registered while another turn runs on it.
|
|
253
237
|
if (handle) pending.delete(handle);
|
|
254
238
|
if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
|
|
255
239
|
}
|
|
@@ -260,9 +244,10 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
|
|
|
260
244
|
* runDelegate?: (opts: any) => Promise<any>,
|
|
261
245
|
* runDoctor?: (opts: any) => Promise<any>,
|
|
262
246
|
* forceGraceMs?: number,
|
|
247
|
+
* pending?: Set<any>,
|
|
263
248
|
* }} [opts]
|
|
264
249
|
*/
|
|
265
|
-
export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000 } = {}) {
|
|
250
|
+
export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000, pending = pendingDelegations } = {}) {
|
|
266
251
|
const runDelegate = runDelegateInjected || runDelegateDefault;
|
|
267
252
|
const runDoctor = runDoctorInjected || runDoctorDefault;
|
|
268
253
|
const server = new McpServer(
|
|
@@ -284,7 +269,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
284
269
|
openWorldHint: true,
|
|
285
270
|
},
|
|
286
271
|
},
|
|
287
|
-
async (args,
|
|
272
|
+
async (args, ctx) => runDelegateTool({ args, ctx, runDelegate, inFlight, pending, seenSessions })
|
|
288
273
|
);
|
|
289
274
|
|
|
290
275
|
server.registerTool(
|
|
@@ -292,10 +277,11 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
292
277
|
{
|
|
293
278
|
description:
|
|
294
279
|
"Best-effort cancel of an in-flight delegation by sessionId. session/cancel is advisory — the agent may finish the turn anyway, and the delegate result then carries cancelRequested. Status: cancelled, killed (agent process observed to exit), not-running (turn already ended, still resumable), not-found (id not in this process's recent session history).",
|
|
295
|
-
inputSchema: {
|
|
296
|
-
|
|
280
|
+
inputSchema: z.object({
|
|
281
|
+
// Blank is a malformed call, not a stale id.
|
|
282
|
+
sessionId: z.string().trim().min(1, "sessionId must not be blank"),
|
|
297
283
|
force: z.boolean().default(false).describe("Kill the agent process if the turn is still running after a short grace period."),
|
|
298
|
-
},
|
|
284
|
+
}),
|
|
299
285
|
annotations: {
|
|
300
286
|
title: "Cancel Cursor delegation",
|
|
301
287
|
readOnlyHint: false,
|
|
@@ -307,39 +293,34 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
307
293
|
async ({ sessionId, force }) => {
|
|
308
294
|
const handles = inFlight.get(sessionId);
|
|
309
295
|
if (!handles || handles.size === 0) {
|
|
310
|
-
// A finished session
|
|
311
|
-
// would read as "bad id" for a session that ran and is still resumable.
|
|
296
|
+
// A finished session is still resumable; only an unknown id is not-found.
|
|
312
297
|
const known = seenSessions.has(sessionId);
|
|
313
298
|
return cancelResult(known ? "not-running" : "not-found", sessionId);
|
|
314
299
|
}
|
|
315
|
-
//
|
|
316
|
-
//
|
|
317
|
-
|
|
318
|
-
|
|
300
|
+
// Every turn on the id (the caller named a session), taken now: a resume that registers during
|
|
301
|
+
// the grace or the kill is not swept in. An ended turn stays registered while its agent is
|
|
302
|
+
// stopped; its result is decided, so a cancel leaves it alone.
|
|
303
|
+
const targeted = [...handles].filter((handle) => !handle.ended);
|
|
304
|
+
if (targeted.length === 0) return cancelResult("not-running", sessionId);
|
|
305
|
+
for (const handle of targeted) handle.cancelRequested = true;
|
|
306
|
+
await Promise.all(targeted.map((handle) => handle.client.cancel(sessionId).catch(() => {})));
|
|
319
307
|
if (!force) {
|
|
320
|
-
//
|
|
321
|
-
//
|
|
322
|
-
// with force — report not-found while the agent was alive. Each delegation's own
|
|
323
|
-
// finally removes its handle when the turn actually settles.
|
|
308
|
+
// Handles stay registered: session/cancel is advisory, and a later force must still find
|
|
309
|
+
// the turn. Each delegation's finally removes its handle when the turn settles.
|
|
324
310
|
return cancelResult("cancelled", sessionId);
|
|
325
311
|
}
|
|
326
|
-
//
|
|
327
|
-
|
|
312
|
+
// Polled, not slept through: the turn often settles well inside the grace.
|
|
313
|
+
const running = () => targeted.filter((handle) => !handle.ended && inFlight.get(sessionId)?.has(handle));
|
|
328
314
|
const graceEnds = Date.now() + forceGraceMs;
|
|
329
|
-
while (Date.now() < graceEnds &&
|
|
315
|
+
while (Date.now() < graceEnds && running().length) {
|
|
330
316
|
await new Promise((r) => setTimeout(r, Math.min(50, Math.max(1, graceEnds - Date.now()))));
|
|
331
317
|
}
|
|
332
|
-
const
|
|
333
|
-
if (
|
|
334
|
-
// Snapshot before awaiting stop. A resume that registers during teardown must not be
|
|
335
|
-
// swept out of the map — it was never killed, and inFlight.delete(sessionId) would
|
|
336
|
-
// hide it from cancel and shutdown.
|
|
337
|
-
const toKill = [...stillRunning];
|
|
318
|
+
const toKill = running();
|
|
319
|
+
if (toKill.length === 0) return cancelResult("cancelled", sessionId);
|
|
338
320
|
const observed = await Promise.all(
|
|
339
321
|
toKill.map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
|
|
340
322
|
);
|
|
341
|
-
// "killed"
|
|
342
|
-
// When one does not follow, the handles stay registered and force can be tried again.
|
|
323
|
+
// "killed" needs an observed exit; without one the handles stay and force can be retried.
|
|
343
324
|
if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
|
|
344
325
|
for (const handle of toKill) unregisterInFlight(inFlight, sessionId, handle);
|
|
345
326
|
return cancelResult("killed", sessionId);
|
|
@@ -351,12 +332,12 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
351
332
|
{
|
|
352
333
|
description:
|
|
353
334
|
"Setup diagnostics: plugin version, MCP client capabilities, cursor-agent launcher resolution. Run when delegation fails or agent.found is false.",
|
|
354
|
-
inputSchema: {
|
|
335
|
+
inputSchema: z.object({
|
|
355
336
|
deep: z
|
|
356
337
|
.boolean()
|
|
357
338
|
.default(false)
|
|
358
339
|
.describe("Run an ACP handshake (start → initialize → newSession) to verify the agent is usable; adds models, modes and the current model's options."),
|
|
359
|
-
},
|
|
340
|
+
}),
|
|
360
341
|
annotations: {
|
|
361
342
|
title: "Diagnose Cursor delegation setup",
|
|
362
343
|
readOnlyHint: true,
|
|
@@ -365,21 +346,37 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
|
|
|
365
346
|
openWorldHint: false,
|
|
366
347
|
},
|
|
367
348
|
},
|
|
368
|
-
async ({ deep }) => {
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
349
|
+
async ({ deep }, ctx) => {
|
|
350
|
+
// doctor's processes sit in pending while it runs, where shutdown already looks.
|
|
351
|
+
const handles = [];
|
|
352
|
+
try {
|
|
353
|
+
const out = await runDoctor({
|
|
354
|
+
deep,
|
|
355
|
+
signal: ctx?.mcpReq?.signal,
|
|
356
|
+
onClientReady: (client) => { const handle = { client }; handles.push(handle); pending.add(handle); },
|
|
357
|
+
getClientInfo: () => clientInfoOf(server, ctx),
|
|
358
|
+
});
|
|
359
|
+
return { content: [{ type: "text", text: JSON.stringify(out) }] };
|
|
360
|
+
} finally {
|
|
361
|
+
for (const handle of handles) pending.delete(handle);
|
|
362
|
+
}
|
|
377
363
|
}
|
|
378
364
|
);
|
|
379
365
|
|
|
380
366
|
return server;
|
|
381
367
|
}
|
|
382
368
|
|
|
369
|
+
// A 2025-era client sends its identity once, in initialize, which stays authoritative on that
|
|
370
|
+
// connection even if a request carries envelope keys; a 2026-07-28 one sends it with each request.
|
|
371
|
+
export function clientInfoOf(server, ctx) {
|
|
372
|
+
const envelope = ctx?.mcpReq?.envelope;
|
|
373
|
+
return {
|
|
374
|
+
capabilities: server.server.getClientCapabilities() ?? envelope?.[CLIENT_CAPABILITIES_META_KEY],
|
|
375
|
+
version: server.server.getClientVersion() ?? envelope?.[CLIENT_INFO_META_KEY],
|
|
376
|
+
protocolVersion: server.server.getNegotiatedProtocolVersion() ?? envelope?.[PROTOCOL_VERSION_META_KEY],
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
|
|
383
380
|
const __filename = fileURLToPath(import.meta.url);
|
|
384
381
|
let isMain = false;
|
|
385
382
|
if (process.argv[1]) {
|
|
@@ -399,57 +396,48 @@ export function installSignalCleanup(map, {
|
|
|
399
396
|
stdin = process.stdin,
|
|
400
397
|
} = {}) {
|
|
401
398
|
let shuttingDown = false;
|
|
402
|
-
const shutdown = (code) => {
|
|
403
|
-
// A second
|
|
404
|
-
//
|
|
405
|
-
if (shuttingDown) return exit(code);
|
|
399
|
+
const shutdown = (code, fromSignal = false) => {
|
|
400
|
+
// A second signal exits without the wait, the kills already sent. A stdin EOF does not: a
|
|
401
|
+
// hangup closes stdin right after its SIGHUP.
|
|
402
|
+
if (shuttingDown) return fromSignal ? exit(code) : undefined;
|
|
406
403
|
shuttingDown = true;
|
|
407
|
-
// Set
|
|
408
|
-
// has to die with the code the signal asked for, and the scheduled exit may never get a
|
|
409
|
-
// turn to run.
|
|
404
|
+
// Set now: the loop may run dry before the scheduled exit gets a turn.
|
|
410
405
|
setExitCode(code);
|
|
411
406
|
const stops = [];
|
|
407
|
+
// An unseen exit is not memoized, so a second stop dispatches a fresh kill before the exit.
|
|
408
|
+
const stopOnce = (handle) => Promise.resolve(handle.client.stop()).catch(() => false);
|
|
412
409
|
const dispatch = (handle) => {
|
|
413
|
-
try { stops.push(
|
|
410
|
+
try { stops.push(stopOnce(handle).then((exited) => (exited === false ? stopOnce(handle) : exited))); } catch {}
|
|
414
411
|
};
|
|
415
412
|
for (const handles of map.values()) for (const handle of handles) dispatch(handle);
|
|
416
|
-
// Delegations still
|
|
417
|
-
// is the only place it is reachable from — they have no session id to be keyed under yet.
|
|
413
|
+
// Delegations still in their handshake: their agent runs, and only pending reaches it.
|
|
418
414
|
for (const handle of pending) dispatch(handle);
|
|
419
|
-
//
|
|
420
|
-
//
|
|
421
|
-
//
|
|
422
|
-
// own deadline), so this wait is short and finite on every platform.
|
|
423
|
-
// Scheduled rather than called from the kill's own continuation, so the exit runs on a
|
|
424
|
-
// clean loop turn instead of on the settlement stack.
|
|
415
|
+
// Waits for the kills: on Windows taskkill is a separate process, and exiting first orphans the
|
|
416
|
+
// launcher and agent below the shell (measured). stop() bounds itself, so the wait is finite.
|
|
417
|
+
// The exit is scheduled onto a clean loop turn rather than run on the settlement stack.
|
|
425
418
|
const leave = () => schedule(() => exit(code));
|
|
426
419
|
Promise.all(stops).then(leave, leave);
|
|
427
420
|
};
|
|
428
|
-
//
|
|
429
|
-
//
|
|
430
|
-
// leak the agent. shutdown() already walks pending, so this covers spawn through session/new.
|
|
421
|
+
// On POSIX each agent has its own process group, which a signal to this process misses, so the
|
|
422
|
+
// handler kills them first. SIGHUP too: a closed terminal, whose default leaves them running.
|
|
431
423
|
if (DETACHED) {
|
|
432
|
-
const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143]]);
|
|
433
|
-
for (const [signal, code] of signals) process.on(signal, () => shutdown(code));
|
|
424
|
+
const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]);
|
|
425
|
+
for (const [signal, code] of signals) process.on(signal, () => shutdown(code, true));
|
|
434
426
|
}
|
|
435
|
-
//
|
|
436
|
-
//
|
|
437
|
-
// it subscribes to `data` and `error` only — so EOF leaves this process up with a delegation
|
|
438
|
-
// still running and nobody left to hand it to.
|
|
427
|
+
// A stdio host closes stdin before it resorts to a signal. The SDK aborts in-flight requests on
|
|
428
|
+
// EOF; this also stops their agents directly, waits for the kills, and exits.
|
|
439
429
|
stdin.on("end", () => shutdown(0));
|
|
440
430
|
}
|
|
441
431
|
|
|
442
432
|
if (isMain) {
|
|
443
|
-
//
|
|
444
|
-
//
|
|
445
|
-
// beside this file, so it reports the code that is actually running rather than what a
|
|
446
|
-
// manifest pinned. stdout is free here because the transport never starts.
|
|
433
|
+
// Answered before the transport starts, so an install can be checked without a host. Reads the
|
|
434
|
+
// package.json beside this file: the code actually running, not what a manifest pinned.
|
|
447
435
|
const argv = process.argv.slice(2);
|
|
448
436
|
if (argv.includes("--version") || argv.includes("-v")) {
|
|
449
437
|
console.log(readPackageVersion());
|
|
450
438
|
} else {
|
|
451
|
-
const server = buildServer();
|
|
452
439
|
installSignalCleanup(inFlight, { pending: pendingDelegations });
|
|
453
|
-
|
|
440
|
+
// One factory serves both protocol eras: a 2025-era initialize pins a legacy instance.
|
|
441
|
+
serveStdio(() => buildServer());
|
|
454
442
|
}
|
|
455
443
|
}
|
|
@@ -11,9 +11,8 @@ export class SessionSupervisor {
|
|
|
11
11
|
this.client = client;
|
|
12
12
|
this.handshakeMs = handshakeMs;
|
|
13
13
|
this.hardCapMs = hardCapMs;
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
// about liveness: a probe measured 26.9s of dead wire for a healthy 20s command.
|
|
14
|
+
// Idle detection is opt-in: cursor-agent sends no frames while a shell command runs (26.9s of
|
|
15
|
+
// silence measured for a healthy 20s command).
|
|
17
16
|
this.idleMs = idleMs > 0 ? idleMs : 0;
|
|
18
17
|
this.sessionId = null;
|
|
19
18
|
this.lastActivityAt = Date.now();
|
|
@@ -58,9 +57,8 @@ export class SessionSupervisor {
|
|
|
58
57
|
}, this.handshakeMs);
|
|
59
58
|
}
|
|
60
59
|
|
|
61
|
-
//
|
|
62
|
-
//
|
|
63
|
-
// must come off.
|
|
60
|
+
// Silence in the request/response handshake means a wedged agent; once the prompt is in flight
|
|
61
|
+
// it does not, so the deadline comes off.
|
|
64
62
|
promptStarted() {
|
|
65
63
|
if (this._promptStarted) return;
|
|
66
64
|
this._promptStarted = true;
|