cursor-delegate-mcp 2.10.0 → 3.0.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 CHANGED
@@ -6,6 +6,63 @@ All notable changes to this project are documented here. The format follows
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [3.0.0] - 2026-11-23
10
+
11
+ `delegate` no longer holds your agent while Cursor works. In an interactive Claude Code CLI session
12
+ it runs as an MCP task, and the Antigravity plugin runs it in the background: your agent stays free
13
+ to plan, review or start the next delegation, and Cursor's result arrives when its turn ends. Codex
14
+ and other hosts keep the blocking call. One thing changes on upgrade in Claude Code: the
15
+ `delegate` call returns before Cursor has finished, and its result comes back as a task
16
+ notification.
17
+
18
+ ### Added
19
+
20
+ - The server serves the MCP Tasks extension (`io.modelcontextprotocol/tasks`, 2026-07-28) to a
21
+ request that lists it: `tasks/get`, `tasks/update` and `tasks/cancel`. A finished task's result
22
+ is kept for an hour, up to 100 tasks.
23
+
24
+ ### Changed
25
+
26
+ - **Breaking: in an interactive Claude Code CLI session, `delegate` runs as an MCP task.** The call
27
+ returns once cursor-agent has the prompt, and the same result arrives as a task notification
28
+ when the turn ends. Progress shows as the task's status message in `/tasks`, and stopping the
29
+ task cancels the turn and stops cursor-agent. An argument cursor-agent rejects still fails the
30
+ call before the prompt. A request that does not list the extension, as Codex's and
31
+ Antigravity's do not, is answered with the result, as before.
32
+ `CLAUDE_CODE_DISABLE_MCP_TASK_BACKGROUND=1` makes Claude Code wait for the result in the call.
33
+ - The Antigravity plugin runs `delegate` in the background (`tools.delegate.background: "always"`):
34
+ Antigravity hands the call back to the model at once and wakes it with the result.
35
+ `timeoutSeconds` still bounds the call.
36
+
37
+ ## [2.11.0] - 2026-11-23
38
+
39
+ ### Added
40
+
41
+ - `doctor` reports `client.protocolVersion`: `2026-07-28`, or the 2025-era revision the host
42
+ negotiated.
43
+
44
+ ### Changed
45
+
46
+ - MCP SDK v2 (`@modelcontextprotocol/server` 2.4.0): the server takes 2025-era and 2026-07-28
47
+ hosts. The runtime dependencies are this package and `zod`.
48
+ - A delegation returns once cursor-agent has exited, about 0.1 s after the turn ends. A host that
49
+ closes stdin on the result, as a one-shot run does, exits the server, which on Windows left a
50
+ cursor-agent still being killed running.
51
+
52
+ ### Fixed
53
+
54
+ - An agent whose exit is not seen after the kill is killed once more, by the delegation and by
55
+ server shutdown. A delegation that still sees no exit says so in `protocolWarnings` or its
56
+ error.
57
+ - `cancel` reports `not-running` for a turn that has ended while its agent is being stopped, and
58
+ leaves its result alone. `force` leaves a turn that ends during its grace to that turn's own
59
+ teardown.
60
+ - `doctor` on a 2025-era connection reports the identity and revision from `initialize`, even
61
+ when a request carries per-request envelope keys.
62
+ - On Windows, quotes and empty arguments in `ACP_AGENT_ARGS` reach cursor-agent when
63
+ `cursor-agent.cmd` forwards to its `.ps1` through Windows PowerShell 5.1.
64
+ - The Claude plugin manifest names its image `icon`, the field Anthropic's plugin directory reads.
65
+
9
66
  ## [2.10.0] - 2026-11-22
10
67
 
11
68
  ### Changed
package/README.md CHANGED
@@ -42,6 +42,7 @@ Composer and Grok draw from the **Cursor Models usage pool**, separate from thir
42
42
 
43
43
  - 🤝 **Native plugins** — install into Claude Code, ChatGPT/Codex, Google Antigravity, or GitHub Copilot CLI and just say *"delegate this to Cursor"*. The shared skill teaches your agent how to delegate well.
44
44
  - 💬 **No stalled runs** — if Cursor needs to clarify, it ends the turn and returns the question as a normal result. Your agent reads it and answers by resuming the same session — nothing blocks on a modal waiting for input.
45
+ - ⏳ **Runs in the background in Claude Code** — in an interactive Claude Code CLI session, `delegate` runs as an MCP task: the call returns once Cursor has the prompt, and the result arrives as a task notification when Cursor finishes.
45
46
  - 📦 **Clean, named results** — final answer, changed files, session id, and the plan, returned as one compact JSON payload. Nothing to scrape.
46
47
  - 📋 **Plan first** — `plan` mode: Cursor drafts a plan, you review it, then the same session implements it.
47
48
  - 🔍 **Ask anything** — `ask` mode: Q&A over your codebase.
@@ -180,7 +181,8 @@ OpenCode does **not** use `mcpServers`. Local servers go under `mcp`, with `type
180
181
  "cursor-delegate": {
181
182
  "command": "npx",
182
183
  "args": ["-y", "cursor-delegate-mcp"],
183
- "timeoutSeconds": 21660
184
+ "timeoutSeconds": 21660,
185
+ "tools": { "delegate": { "background": "always" } }
184
186
  }
185
187
  }
186
188
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "2.10.0",
3
+ "version": "3.0.0",
4
4
  "mcpName": "io.github.andreilungeanu/cursor-delegate-mcp",
5
5
  "type": "module",
6
6
  "description": "Delegate multi-file coding work from Claude Code, Codex, Copilot, or any MCP client to Cursor's CLI agent — structured results, plan mode, and changed files.",
@@ -57,10 +57,11 @@
57
57
  "typecheck": "tsc -p tsconfig.json"
58
58
  },
59
59
  "dependencies": {
60
- "@modelcontextprotocol/sdk": "^1.23.0",
60
+ "@modelcontextprotocol/server": "^2.4.0",
61
61
  "zod": "^4.6.5"
62
62
  },
63
63
  "devDependencies": {
64
+ "@modelcontextprotocol/client": "^2.4.0",
64
65
  "@types/node": "^26.1.1",
65
66
  "typescript": "^7.0.2"
66
67
  }
package/src/delegate.js CHANGED
@@ -251,6 +251,8 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
251
251
  * idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
252
252
  * onClientReady?: (client: any) => void,
253
253
  * onSessionReady?: (sessionId: string, client: any) => void,
254
+ * onPromptSent?: (sessionId: string) => void,
255
+ * onTurnEnd?: () => void,
254
256
  * onProgress?: (message: string) => void,
255
257
  * progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
256
258
  * }} [opts]
@@ -259,7 +261,7 @@ export async function runDelegate({
259
261
  spec, mode = "agent", resumeSessionId, workspace,
260
262
  model = DEFAULT_MODEL, fast = false, effort, context, contextFiles, clientFactory,
261
263
  idleMs, handshakeMs, hardCapMs, timeoutMs,
262
- onClientReady, onSessionReady, onProgress, progressThrottleMs = 2000,
264
+ onClientReady, onSessionReady, onPromptSent, onTurnEnd, onProgress, progressThrottleMs = 2000,
263
265
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
264
266
  signal,
265
267
  } = {}) {
@@ -449,6 +451,11 @@ export async function runDelegate({
449
451
  let servedModel;
450
452
  let effectiveEffort;
451
453
  const contextWarnings = [];
454
+ // Set before the teardown in finally, which notes an unseen exit on whichever is going out.
455
+ /** @type {any} */
456
+ let out;
457
+ /** @type {any} */
458
+ let failed;
452
459
  try {
453
460
  const res = await supervisor.supervise(async () => {
454
461
  await client.start();
@@ -513,7 +520,10 @@ export async function runDelegate({
513
520
  const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
514
521
  // The caller has the id from session/new on, so a cancel can come before there is a turn.
515
522
  if (client.cancelRequested) return { stopReason: "cancelled", cancelledBeforePrompt: true };
516
- return await client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
523
+ const turn = client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
524
+ // Every argument has been accepted by now, so a caller may stop waiting on the result.
525
+ try { onPromptSent?.(sessionId); } catch {}
526
+ return await turn;
517
527
  } finally {
518
528
  // The result is assembled across later awaits; a frame trailing the turn must not join it.
519
529
  promptInFlight = false;
@@ -548,7 +558,7 @@ export async function runDelegate({
548
558
  stopReason = res.stopReason;
549
559
  }
550
560
  }
551
- const out = {
561
+ out = {
552
562
  result,
553
563
  sessionId,
554
564
  };
@@ -632,13 +642,26 @@ export async function runDelegate({
632
642
  if (transcript) err.message += `\n\n--- recent ACP transcript (last ${frames} frames) ---\n` + transcript;
633
643
  } catch {}
634
644
  }
645
+ failed = err;
635
646
  throw err;
636
647
  } finally {
648
+ // The turn is decided: from here a cancel finds nothing running.
649
+ try { onTurnEnd?.(); } catch {}
637
650
  clearInterval(heartbeat);
638
651
  signal?.removeEventListener("abort", onAbort);
639
652
  try { supervisor.finish(); } catch {}
640
- // Deliberately not awaited: stop() waits for the child to exit, and every turn — success as
641
- // much as failure — would pay that before returning. Nothing here reads whether it landed.
642
- Promise.resolve(client.stop()).catch(() => {});
653
+ // Awaited: a host may close stdin on the result, and on Windows the server's exit does not take
654
+ // a running agent with it (server.smoke.test.js). An exit not seen is noted instead.
655
+ // A rejected stop counts as unseen; an unseen exit is not memoized, so a retry kills afresh.
656
+ const stopOnce = () => Promise.resolve(client.stop()).catch(() => false);
657
+ let exited = await stopOnce();
658
+ if (exited === false) exited = await stopOnce();
659
+ if (exited === false) {
660
+ const pid = client.child?.pid;
661
+ const note = `the bridge stopped cursor-agent${pid ? ` (pid ${pid})` : ""} but did not see it exit; it may still be running.`;
662
+ // A failure whose message cannot be written keeps its own error rather than a TypeError.
663
+ if (failed) { try { failed.message += ` Note: ${note}`; } catch {} }
664
+ else if (out) (out.protocolWarnings ??= []).push(note);
665
+ }
643
666
  }
644
667
  }
package/src/doctor.js CHANGED
@@ -165,7 +165,7 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
165
165
  /**
166
166
  * onClientReady gets each process doctor starts, probe then agent, so a shutdown can stop it.
167
167
  * @param {{
168
- * getClientInfo?: () => { capabilities?: any, version?: any },
168
+ * getClientInfo?: () => { capabilities?: any, version?: any, protocolVersion?: string },
169
169
  * deep?: boolean,
170
170
  * spawnSpec?: { command: string, args: string[], options?: object },
171
171
  * clientFactory?: (opts: any) => any,
@@ -189,7 +189,7 @@ export async function runDoctor({
189
189
  signal,
190
190
  onClientReady,
191
191
  } = {}) {
192
- const { capabilities, version } = getClientInfo();
192
+ const { capabilities, version, protocolVersion } = getClientInfo();
193
193
  const agentProbe = await probeAgentVersion(spawnSpec, versionTimeoutMs, { signal, onSpawn: onClientReady });
194
194
 
195
195
  /** @type {{ plugin: any, client: any, agent: any & { handshake?: any }, runtime: any, env: any }} */
@@ -199,6 +199,8 @@ export async function runDoctor({
199
199
  name: version?.name ?? null,
200
200
  version: version?.version ?? null,
201
201
  capabilities: capabilities ?? {},
202
+ // The MCP revision the host speaks: 2026-07-28 or a 2025-era one.
203
+ ...(typeof protocolVersion === "string" ? { protocolVersion } : {}),
202
204
  },
203
205
  agent: {
204
206
  found: agentProbe.found,
package/src/server.js CHANGED
@@ -2,14 +2,15 @@
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/sdk/server/mcp.js";
6
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
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";
10
10
  import { VERSION, readPackageVersion } from "./version.js";
11
11
  import { DETACHED } from "./proc.js";
12
12
  import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
13
+ import { TASKS_EXTENSION, createTaskStore, listsTasks, registerTaskHandlers, runAsTask } from "./tasks.js";
13
14
 
14
15
  const ICON_BASE = `https://raw.githubusercontent.com/andreilungeanu/cursor-delegate-mcp/v${VERSION}/assets`;
15
16
  /** @type {Array<{ src: string, mimeType: string, sizes: string[], theme: "light" | "dark" }>} */
@@ -32,7 +33,7 @@ function registerInFlight(map, sessionId, handle) {
32
33
  if (handles) handles.add(handle);
33
34
  else map.set(sessionId, new Set([handle]));
34
35
  }
35
- /** @returns {import("@modelcontextprotocol/sdk/types.js").CallToolResult} */
36
+ /** @returns {import("@modelcontextprotocol/server").CallToolResult} */
36
37
  function cancelResult(status, sessionId) {
37
38
  return { content: [{ type: "text", text: JSON.stringify({ status, sessionId }) }] };
38
39
  }
@@ -58,6 +59,10 @@ function rememberSession(set, id) {
58
59
  if (set.size > SEEN_SESSIONS_CAP) set.delete(set.values().next().value);
59
60
  }
60
61
 
62
+ // Delegations answered as MCP tasks. Module-level, as inFlight: a task outlives the request that
63
+ // started it, and serveStdio may build more than one server instance.
64
+ const taskStore = createTaskStore();
65
+
61
66
  // Read at connect, so only what decides whether to delegate at all. Call-time facts belong on
62
67
  // the parameter descriptions.
63
68
  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.`;
@@ -137,6 +142,7 @@ export const doctorOutputShape = {
137
142
  name: z.string().nullable(),
138
143
  version: z.string().nullable(),
139
144
  capabilities: z.record(z.string(), z.unknown()),
145
+ protocolVersion: z.string().optional(),
140
146
  }).passthrough(),
141
147
  agent: z.object(doctorAgentShape).passthrough(),
142
148
  runtime: z.object({
@@ -162,36 +168,42 @@ export const delegateInputSchema = z.object({
162
168
  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."),
163
169
  });
164
170
 
171
+ /** @returns {(message: string) => void} */
172
+ export function progressNotifier(ctx) {
173
+ const progressToken = ctx?.mcpReq?._meta?.progressToken;
174
+ if (progressToken == null) return () => {};
175
+ let progress = 0;
176
+ return (message) => {
177
+ // An unhandled rejection from notify would exit the server; the try catches a sync throw.
178
+ try {
179
+ Promise.resolve(ctx.mcpReq.notify({
180
+ method: "notifications/progress",
181
+ params: { progressToken, progress: ++progress, message },
182
+ })).catch(() => {});
183
+ } catch {}
184
+ };
185
+ }
186
+
165
187
  /**
166
188
  * @param {{
167
- * args: any, extra?: any,
189
+ * args: any, ctx?: any,
168
190
  * runDelegate: (opts: any) => Promise<any>,
169
191
  * inFlight: Map<string, Set<any>>,
170
192
  * pending?: Set<any>,
171
193
  * seenSessions?: Set<string>,
194
+ * signal?: AbortSignal,
195
+ * onProgress?: (message: string) => void,
196
+ * onPromptSent?: (sessionId: string) => void,
197
+ * onTurnEnd?: () => void,
172
198
  * }} deps
173
- * @returns {Promise<import("@modelcontextprotocol/sdk/types.js").CallToolResult>}
199
+ * @returns {Promise<import("@modelcontextprotocol/server").CallToolResult>}
174
200
  */
175
- export async function runDelegateTool({ args, extra, runDelegate, inFlight, pending = new Set(), seenSessions = new Set() }) {
201
+ export async function runDelegateTool({
202
+ args, ctx, runDelegate, inFlight, pending = new Set(), seenSessions = new Set(),
203
+ signal = ctx?.mcpReq?.signal, onProgress = progressNotifier(ctx), onPromptSent, onTurnEnd,
204
+ }) {
176
205
  const { spec, mode, resumeSessionId, workspace, model, fast, effort, context, contextFiles } = args;
177
206
 
178
- const progressToken = extra?._meta?.progressToken;
179
- /** @type {(message: string) => void} */
180
- let onProgress = () => {};
181
- if (progressToken != null) {
182
- let progress = 0;
183
- onProgress = (message) => {
184
- // An unhandled rejection from sendNotification would exit the server; the try catches a
185
- // sync throw.
186
- try {
187
- Promise.resolve(extra.sendNotification({
188
- method: "notifications/progress",
189
- params: { progressToken, progress: ++progress, message },
190
- })).catch(() => {});
191
- } catch {}
192
- };
193
- }
194
-
195
207
  let capturedSessionId;
196
208
  let handle;
197
209
  try {
@@ -206,7 +218,8 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
206
218
  context,
207
219
  contextFiles,
208
220
  onProgress,
209
- signal: extra?.signal,
221
+ signal,
222
+ onPromptSent,
210
223
  onClientReady: (client) => {
211
224
  handle = { client, cancelRequested: false };
212
225
  pending.add(handle);
@@ -221,6 +234,10 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
221
234
  // Sent now so a host that can call tools concurrently has an id to cancel mid-run.
222
235
  onProgress(`session ready: ${sessionId}`);
223
236
  },
237
+ onTurnEnd: () => {
238
+ if (handle) handle.ended = true;
239
+ onTurnEnd?.();
240
+ },
224
241
  });
225
242
  if (handle?.cancelRequested) out.cancelRequested = true;
226
243
  return { content: [{ type: "text", text: JSON.stringify(out) }] };
@@ -244,15 +261,27 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
244
261
  * runDoctor?: (opts: any) => Promise<any>,
245
262
  * forceGraceMs?: number,
246
263
  * pending?: Set<any>,
264
+ * inFlight?: Map<string, Set<any>>,
265
+ * era?: "legacy" | "modern",
266
+ * tasks?: ReturnType<typeof createTaskStore>,
247
267
  * }} [opts]
248
268
  */
249
- export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000, pending = pendingDelegations } = {}) {
269
+ export function buildServer({
270
+ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000, pending = pendingDelegations,
271
+ inFlight: flights = inFlight, era, tasks = taskStore,
272
+ } = {}) {
250
273
  const runDelegate = runDelegateInjected || runDelegateDefault;
251
274
  const runDoctor = runDoctorInjected || runDoctorDefault;
275
+ // Tasks only on a 2026-07-28 instance: the SDK also lifts envelope keys off 2025-era requests.
276
+ const servesTasks = era === "modern";
252
277
  const server = new McpServer(
253
278
  { name: "cursor-delegate-mcp", version: VERSION, icons: SERVER_ICONS },
254
- { instructions: SERVER_INSTRUCTIONS }
279
+ {
280
+ instructions: SERVER_INSTRUCTIONS,
281
+ ...(servesTasks ? { capabilities: { extensions: { [TASKS_EXTENSION]: {} } } } : {}),
282
+ }
255
283
  );
284
+ if (servesTasks) registerTaskHandlers(server, tasks);
256
285
 
257
286
  server.registerTool(
258
287
  "delegate",
@@ -268,7 +297,12 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
268
297
  openWorldHint: true,
269
298
  },
270
299
  },
271
- async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending, seenSessions })
300
+ async (args, ctx) => {
301
+ /** @param {Record<string, any>} [over] */
302
+ const run = (over) => runDelegateTool({ args, ctx, runDelegate, inFlight: flights, pending, seenSessions, ...over });
303
+ if (!servesTasks || !listsTasks(ctx)) return run();
304
+ return /** @type {any} */ (runAsTask({ run, signal: ctx?.mcpReq?.signal, notify: progressNotifier(ctx), store: tasks }));
305
+ }
272
306
  );
273
307
 
274
308
  server.registerTool(
@@ -276,11 +310,11 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
276
310
  {
277
311
  description:
278
312
  "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).",
279
- inputSchema: {
313
+ inputSchema: z.object({
280
314
  // Blank is a malformed call, not a stale id.
281
315
  sessionId: z.string().trim().min(1, "sessionId must not be blank"),
282
316
  force: z.boolean().default(false).describe("Kill the agent process if the turn is still running after a short grace period."),
283
- },
317
+ }),
284
318
  annotations: {
285
319
  title: "Cancel Cursor delegation",
286
320
  readOnlyHint: false,
@@ -290,15 +324,17 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
290
324
  },
291
325
  },
292
326
  async ({ sessionId, force }) => {
293
- const handles = inFlight.get(sessionId);
327
+ const handles = flights.get(sessionId);
294
328
  if (!handles || handles.size === 0) {
295
329
  // A finished session is still resumable; only an unknown id is not-found.
296
330
  const known = seenSessions.has(sessionId);
297
331
  return cancelResult(known ? "not-running" : "not-found", sessionId);
298
332
  }
299
333
  // Every turn on the id (the caller named a session), taken now: a resume that registers during
300
- // the grace or the kill is not swept in.
301
- const targeted = [...handles];
334
+ // the grace or the kill is not swept in. An ended turn stays registered while its agent is
335
+ // stopped; its result is decided, so a cancel leaves it alone.
336
+ const targeted = [...handles].filter((handle) => !handle.ended);
337
+ if (targeted.length === 0) return cancelResult("not-running", sessionId);
302
338
  for (const handle of targeted) handle.cancelRequested = true;
303
339
  await Promise.all(targeted.map((handle) => handle.client.cancel(sessionId).catch(() => {})));
304
340
  if (!force) {
@@ -307,7 +343,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
307
343
  return cancelResult("cancelled", sessionId);
308
344
  }
309
345
  // Polled, not slept through: the turn often settles well inside the grace.
310
- const running = () => targeted.filter((handle) => inFlight.get(sessionId)?.has(handle));
346
+ const running = () => targeted.filter((handle) => !handle.ended && flights.get(sessionId)?.has(handle));
311
347
  const graceEnds = Date.now() + forceGraceMs;
312
348
  while (Date.now() < graceEnds && running().length) {
313
349
  await new Promise((r) => setTimeout(r, Math.min(50, Math.max(1, graceEnds - Date.now()))));
@@ -319,7 +355,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
319
355
  );
320
356
  // "killed" needs an observed exit; without one the handles stay and force can be retried.
321
357
  if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
322
- for (const handle of toKill) unregisterInFlight(inFlight, sessionId, handle);
358
+ for (const handle of toKill) unregisterInFlight(flights, sessionId, handle);
323
359
  return cancelResult("killed", sessionId);
324
360
  }
325
361
  );
@@ -329,12 +365,12 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
329
365
  {
330
366
  description:
331
367
  "Setup diagnostics: plugin version, MCP client capabilities, cursor-agent launcher resolution. Run when delegation fails or agent.found is false.",
332
- inputSchema: {
368
+ inputSchema: z.object({
333
369
  deep: z
334
370
  .boolean()
335
371
  .default(false)
336
372
  .describe("Run an ACP handshake (start → initialize → newSession) to verify the agent is usable; adds models, modes and the current model's options."),
337
- },
373
+ }),
338
374
  annotations: {
339
375
  title: "Diagnose Cursor delegation setup",
340
376
  readOnlyHint: true,
@@ -343,18 +379,15 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
343
379
  openWorldHint: false,
344
380
  },
345
381
  },
346
- async ({ deep }, extra) => {
382
+ async ({ deep }, ctx) => {
347
383
  // doctor's processes sit in pending while it runs, where shutdown already looks.
348
384
  const handles = [];
349
385
  try {
350
386
  const out = await runDoctor({
351
387
  deep,
352
- signal: extra?.signal,
388
+ signal: ctx?.mcpReq?.signal,
353
389
  onClientReady: (client) => { const handle = { client }; handles.push(handle); pending.add(handle); },
354
- getClientInfo: () => ({
355
- capabilities: server.server.getClientCapabilities(),
356
- version: server.server.getClientVersion(),
357
- }),
390
+ getClientInfo: () => clientInfoOf(server, ctx),
358
391
  });
359
392
  return { content: [{ type: "text", text: JSON.stringify(out) }] };
360
393
  } finally {
@@ -366,6 +399,17 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
366
399
  return server;
367
400
  }
368
401
 
402
+ // A 2025-era client sends its identity once, in initialize, which stays authoritative on that
403
+ // connection even if a request carries envelope keys; a 2026-07-28 one sends it with each request.
404
+ export function clientInfoOf(server, ctx) {
405
+ const envelope = ctx?.mcpReq?.envelope;
406
+ return {
407
+ capabilities: server.server.getClientCapabilities() ?? envelope?.[CLIENT_CAPABILITIES_META_KEY],
408
+ version: server.server.getClientVersion() ?? envelope?.[CLIENT_INFO_META_KEY],
409
+ protocolVersion: server.server.getNegotiatedProtocolVersion() ?? envelope?.[PROTOCOL_VERSION_META_KEY],
410
+ };
411
+ }
412
+
369
413
  const __filename = fileURLToPath(import.meta.url);
370
414
  let isMain = false;
371
415
  if (process.argv[1]) {
@@ -393,8 +437,10 @@ export function installSignalCleanup(map, {
393
437
  // Set now: the loop may run dry before the scheduled exit gets a turn.
394
438
  setExitCode(code);
395
439
  const stops = [];
440
+ // An unseen exit is not memoized, so a second stop dispatches a fresh kill before the exit.
441
+ const stopOnce = (handle) => Promise.resolve(handle.client.stop()).catch(() => false);
396
442
  const dispatch = (handle) => {
397
- try { stops.push(Promise.resolve(handle.client.stop()).catch(() => {})); } catch {}
443
+ try { stops.push(stopOnce(handle).then((exited) => (exited === false ? stopOnce(handle) : exited))); } catch {}
398
444
  };
399
445
  for (const handles of map.values()) for (const handle of handles) dispatch(handle);
400
446
  // Delegations still in their handshake: their agent runs, and only pending reaches it.
@@ -411,8 +457,8 @@ export function installSignalCleanup(map, {
411
457
  const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]);
412
458
  for (const [signal, code] of signals) process.on(signal, () => shutdown(code, true));
413
459
  }
414
- // A stdio host closes stdin before it resorts to a signal, and the SDK transport ignores EOF
415
- // (it listens for `data` and `error` only).
460
+ // A stdio host closes stdin before it resorts to a signal. The SDK aborts in-flight requests on
461
+ // EOF; this also stops their agents directly, waits for the kills, and exits.
416
462
  stdin.on("end", () => shutdown(0));
417
463
  }
418
464
 
@@ -423,8 +469,9 @@ if (isMain) {
423
469
  if (argv.includes("--version") || argv.includes("-v")) {
424
470
  console.log(readPackageVersion());
425
471
  } else {
426
- const server = buildServer();
427
472
  installSignalCleanup(inFlight, { pending: pendingDelegations });
428
- await server.connect(new StdioServerTransport());
473
+ // One factory serves both protocol eras: a 2025-era initialize pins a legacy instance, and only
474
+ // a modern one answers with tasks.
475
+ serveStdio(({ era }) => buildServer({ era }));
429
476
  }
430
477
  }
package/src/spawn.js CHANGED
@@ -54,6 +54,16 @@ function cmdQuote(value) {
54
54
  return `"${s.replace(/(\\+)$/, "$1$1")}"`;
55
55
  }
56
56
 
57
+ // Windows PowerShell 5.1 pastes each argument into the command line unescaped, drops an empty one,
58
+ // and quotes one only if it has whitespace outside an even count of ". Escaped for node's parser;
59
+ // with whitespace a quote goes as "", which keeps that count even and reads as " inside the quotes.
60
+ function escapeForPs51(arg) {
61
+ if (arg === "") return '""';
62
+ const spaced = /\s/.test(arg);
63
+ const s = arg.replace(/(\\*)"/g, (_, bs) => `${bs}${bs}${spaced ? '""' : '\\"'}`);
64
+ return spaced ? s.replace(/(\\+)$/, "$1$1") : s;
65
+ }
66
+
57
67
  /**
58
68
  * What to hand spawn() for a spec, at each spawn site so doctor reads the spec as configured.
59
69
  * @param {string} command @param {string[]} args
@@ -65,7 +75,8 @@ export function spawnArgv(command, args, options) {
65
75
  // cmd.exe opens a .ps1 with its file association, so a .ps1, or the one a forwarding .cmd runs,
66
76
  // goes to powershell.exe -File as cursor-agent.cmd does. Only x.ps1 itself: x.ps1.cmd stays cmd's.
67
77
  const name = String(command).replace(/^["']|["']$/g, "");
68
- const script = /\.ps1$/i.test(name) ? findCommand(name, env, true) : forwardedScript(findCommand(name, env), env);
78
+ const direct = /\.ps1$/i.test(name);
79
+ const script = direct ? findCommand(name, env, true) : forwardedScript(findCommand(name, env), env);
69
80
  if (script) {
70
81
  const rootKey = Object.keys(env).find((k) => k.toUpperCase() === "SYSTEMROOT");
71
82
  const powershell = rootKey && env[rootKey]
@@ -73,7 +84,8 @@ export function spawnArgv(command, args, options) {
73
84
  : "powershell.exe";
74
85
  return {
75
86
  command: powershell,
76
- args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script, ...args],
87
+ // cursor-agent.ps1 passes $args on to node; a .ps1 named directly may read them itself.
88
+ args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script, ...(direct ? args : args.map(escapeForPs51))],
77
89
  options: { ...options, shell: false },
78
90
  };
79
91
  }
package/src/tasks.js ADDED
@@ -0,0 +1,167 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { CLIENT_CAPABILITIES_META_KEY, MissingRequiredClientCapabilityError, ProtocolError, ProtocolErrorCode } from "@modelcontextprotocol/server";
4
+
5
+ // The MCP Tasks extension, 2026-07-28: https://modelcontextprotocol.io/extensions/tasks/overview
6
+ export const TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
7
+
8
+ const RETAIN_MS = 60 * 60 * 1000;
9
+ const MAX_FINISHED = 100;
10
+ const FAST_POLL_MS = 3000;
11
+ const SLOW_POLL_MS = 10000;
12
+ const FAST_POLL_FOR_MS = 60 * 1000;
13
+
14
+ // Claude Code lists the extension only on a call that can become a task: not from a subagent.
15
+ export function listsTasks(ctx) {
16
+ return ctx?.mcpReq?.envelope?.[CLIENT_CAPABILITIES_META_KEY]?.extensions?.[TASKS_EXTENSION] != null;
17
+ }
18
+
19
+ /**
20
+ * @typedef {{
21
+ * taskId: string, status: "working" | "completed" | "failed" | "cancelled",
22
+ * createdAt: number, lastUpdatedAt: number, endedAt?: number, statusMessage?: string,
23
+ * sessionId?: string, turnEnded: boolean, ac: AbortController,
24
+ * result?: any, error?: { code: number, message: string },
25
+ * }} Task
26
+ */
27
+
28
+ /** @param {{ now?: () => number, retainMs?: number, maxFinished?: number }} [opts] */
29
+ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinished = MAX_FINISHED } = {}) {
30
+ /** @type {Map<string, Task>} */
31
+ const tasks = new Map();
32
+ // A running task is never dropped: its id is the host's only handle on the run.
33
+ const prune = () => {
34
+ const t = now();
35
+ const finished = [...tasks.values()].filter((task) => task.endedAt !== undefined);
36
+ for (const task of finished) if (t - /** @type {number} */ (task.endedAt) > retainMs) tasks.delete(task.taskId);
37
+ const kept = finished.filter((task) => tasks.has(task.taskId))
38
+ .sort((a, b) => /** @type {number} */ (a.endedAt) - /** @type {number} */ (b.endedAt));
39
+ for (const task of kept.slice(0, Math.max(0, kept.length - maxFinished))) tasks.delete(task.taskId);
40
+ };
41
+ return {
42
+ now,
43
+ /** @returns {Task} */
44
+ create() {
45
+ const t = now();
46
+ return { taskId: randomUUID(), status: "working", createdAt: t, lastUpdatedAt: t, turnEnded: false, ac: new AbortController() };
47
+ },
48
+ /** @param {Task} task */
49
+ add(task) { prune(); tasks.set(task.taskId, task); },
50
+ /** @param {string} taskId */
51
+ get(taskId) { prune(); return tasks.get(taskId); },
52
+ /** @param {Task} task @param {{ result?: any, error?: any }} outcome */
53
+ finish(task, outcome) {
54
+ if (task.status === "working") {
55
+ task.endedAt = now();
56
+ if ("error" in outcome) {
57
+ task.status = "failed";
58
+ task.error = { code: ProtocolErrorCode.InternalError, message: String(outcome.error?.message ?? outcome.error) };
59
+ } else {
60
+ task.status = "completed";
61
+ task.result = outcome.result;
62
+ }
63
+ } else if (outcome.result?.isError) {
64
+ // A cancelled run's own error names its resume id and an agent the stop did not see exit.
65
+ task.statusMessage = outcome.result.content?.[0]?.text ?? task.statusMessage;
66
+ }
67
+ task.lastUpdatedAt = now();
68
+ prune();
69
+ },
70
+ // A turn that has ended has its result decided, so a cancel leaves it, as the cancel tool does.
71
+ /** @param {Task} task */
72
+ cancel(task) {
73
+ if (task.status !== "working" || task.turnEnded) return;
74
+ task.status = "cancelled";
75
+ task.statusMessage = task.sessionId ? `cancelled; resume with resumeSessionId ${task.sessionId}` : "cancelled";
76
+ task.endedAt = task.lastUpdatedAt = now();
77
+ task.ac.abort();
78
+ },
79
+ /** @param {Task} task */
80
+ view(task) {
81
+ const t = now();
82
+ /** @type {Record<string, any>} */
83
+ const view = {
84
+ taskId: task.taskId,
85
+ status: task.status,
86
+ createdAt: new Date(task.createdAt).toISOString(),
87
+ lastUpdatedAt: new Date(task.lastUpdatedAt).toISOString(),
88
+ ttlMs: task.endedAt === undefined ? null : task.endedAt - task.createdAt + retainMs,
89
+ pollIntervalMs: t - task.createdAt < FAST_POLL_FOR_MS ? FAST_POLL_MS : SLOW_POLL_MS,
90
+ };
91
+ if (task.statusMessage) view.statusMessage = task.statusMessage;
92
+ if (task.status === "completed") view.result = task.result;
93
+ if (task.status === "failed") view.error = task.error;
94
+ return view;
95
+ },
96
+ };
97
+ }
98
+
99
+ /**
100
+ * Runs a delegation that answers its request with a task once the prompt is sent. A run that
101
+ * settles before then, setup failures included, answers with its result as a blocking call does.
102
+ * @param {{
103
+ * run: (over: { signal: AbortSignal, onProgress: (m: string) => void, onPromptSent: (id: string) => void, onTurnEnd: () => void }) => Promise<any>,
104
+ * signal?: AbortSignal, notify?: (message: string) => void, store: ReturnType<typeof createTaskStore>,
105
+ * }} opts
106
+ */
107
+ export async function runAsTask({ run, signal, notify = () => {}, store }) {
108
+ const task = store.create();
109
+ let answered = false;
110
+ /** @type {() => void} */
111
+ let markSent = () => {};
112
+ const sent = new Promise((resolve) => { markSent = () => resolve(undefined); });
113
+ // Until the task is answered the request owns the run, so its cancellation stops the agent.
114
+ const forward = () => task.ac.abort();
115
+ if (signal?.aborted) forward();
116
+ else signal?.addEventListener("abort", forward, { once: true });
117
+ const outcome = run({
118
+ signal: task.ac.signal,
119
+ onProgress: (message) => {
120
+ if (task.status === "working") {
121
+ task.statusMessage = message;
122
+ task.lastUpdatedAt = store.now();
123
+ }
124
+ // Once the task is the answer, progress belongs to the task, not the request.
125
+ if (!answered) notify(message);
126
+ },
127
+ onPromptSent: (sessionId) => { task.sessionId = sessionId; markSent(); },
128
+ onTurnEnd: () => { task.turnEnded = true; },
129
+ }).then((result) => ({ result }), (error) => ({ error }));
130
+ const first = await Promise.race([sent, outcome]);
131
+ signal?.removeEventListener("abort", forward);
132
+ // An abort before the agent has a session sends no session/cancel, so setup can still reach the
133
+ // prompt; the request is gone by then and nobody would receive the task id.
134
+ const settled = first ?? (task.ac.signal.aborted ? await outcome : undefined);
135
+ if (settled) {
136
+ if ("error" in settled) throw settled.error;
137
+ return settled.result;
138
+ }
139
+ answered = true;
140
+ // In the store before the answer goes out: the host polls as soon as it reads the id.
141
+ store.add(task);
142
+ outcome.then((o) => store.finish(task, o));
143
+ return { resultType: "task", ...store.view(task) };
144
+ }
145
+
146
+ const TaskParams = z.object({ taskId: z.string() }).passthrough();
147
+ const AnyResult = z.object({}).passthrough();
148
+
149
+ /** @param {any} server @param {ReturnType<typeof createTaskStore>} store */
150
+ export function registerTaskHandlers(server, store) {
151
+ /** @param {string} taskId @param {any} ctx */
152
+ const find = (taskId, ctx) => {
153
+ if (!listsTasks(ctx)) {
154
+ throw new MissingRequiredClientCapabilityError({ requiredCapabilities: { extensions: { [TASKS_EXTENSION]: {} } } });
155
+ }
156
+ const task = store.get(taskId);
157
+ if (!task) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Unknown task: ${taskId}`);
158
+ return task;
159
+ };
160
+ server.server.setRequestHandler("tasks/get", { params: TaskParams, result: AnyResult },
161
+ async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => store.view(find(taskId, ctx)));
162
+ // A delegation never enters input_required: its questions come back in the result.
163
+ server.server.setRequestHandler("tasks/update", { params: TaskParams, result: AnyResult },
164
+ async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => { find(taskId, ctx); return {}; });
165
+ server.server.setRequestHandler("tasks/cancel", { params: TaskParams, result: AnyResult },
166
+ async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => { store.cancel(find(taskId, ctx)); return {}; });
167
+ }