cursor-delegate-mcp 1.15.0 โ†’ 1.17.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/README.md CHANGED
@@ -44,7 +44,7 @@ You โ†’ your agent (plans & reviews)
44
44
 
45
45
  - ๐Ÿค **Native plugins** โ€” install into Claude Code, ChatGPT/Codex, or GitHub Copilot CLI and just say *"delegate this to Cursor"*. The shared skill teaches your agent how to delegate well.
46
46
  - ๐Ÿ’ฌ **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.
47
- - ๐Ÿ“ฆ **Clean, typed results** โ€” final answer, changed files, session id, and the plan, returned as validated structured output. Nothing to parse, nothing to guess.
47
+ - ๐Ÿ“ฆ **Clean, named results** โ€” final answer, changed files, session id, and the plan, returned as one compact JSON payload. Nothing to scrape, nothing to guess.
48
48
  - ๐Ÿ“‹ **Plan first** โ€” `plan` mode: Cursor drafts a plan, you review it, then the same session implements it.
49
49
  - ๐Ÿ” **Ask anything** โ€” `ask` mode: read-only Q&A over your codebase, zero file changes.
50
50
  - ๐Ÿฉบ **Self-diagnosing** โ€” a `doctor` tool that tells you exactly what's missing if setup isn't right.
@@ -52,7 +52,7 @@ You โ†’ your agent (plans & reviews)
52
52
 
53
53
  ## Quick start
54
54
 
55
- You need [Node.js 22+](https://nodejs.org/) and the [Cursor CLI](https://cursor.com/docs/cli/overview), logged in (`cursor-agent login`).
55
+ You need [Node.js 20+](https://nodejs.org/) and the [Cursor CLI](https://cursor.com/docs/cli/overview), logged in (`cursor-agent login`).
56
56
 
57
57
  ### Claude Code
58
58
 
@@ -164,4 +164,4 @@ Add the following server to the client's MCP config:
164
164
 
165
165
  MIT ยฉ [Andrei Lungeanu](https://github.com/andreilungeanu)
166
166
 
167
- <sub>[Security](SECURITY.md) ยท [Privacy](PRIVACY.md) ยท [Terms](TERMS.md) ยท [Changelog](CHANGELOG.md)</sub>
167
+ <sub>[Technical reference](TECHNICAL.md) ยท [Security](SECURITY.md) ยท [Privacy](PRIVACY.md) ยท [Terms](TERMS.md) ยท [Changelog](CHANGELOG.md)</sub>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "1.15.0",
3
+ "version": "1.17.0",
4
4
  "type": "module",
5
5
  "description": "MCP server bridging AI coding hosts to cursor-agent over the Agent Client Protocol (ACP).",
6
6
  "license": "MIT",
@@ -31,7 +31,7 @@
31
31
  "cursor-delegate-mcp": "src/server.js"
32
32
  },
33
33
  "engines": {
34
- "node": ">=22"
34
+ "node": ">=20"
35
35
  },
36
36
  "files": [
37
37
  "src",
package/src/acp-enums.js CHANGED
@@ -1,12 +1,10 @@
1
- // The value sets ACP allows for plan and todo fields. They live here because two layers read
2
- // them: the sanitizers in delegate.js, which strip anything else off an agent frame, and the
3
- // zod schemas in server.js, which advertise them to hosts. Kept in four hand-synced copies
4
- // before, where a drift would have meant stripping a value the tool documents, or documenting
5
- // one it strips.
1
+ // The value sets ACP allows for plan and todo fields, shared by the two layers that read them:
2
+ // the sanitizers in delegate.js, which strip anything else off an agent frame, and the zod
3
+ // schemas in server.js, which advertise them to hosts. A drift between the two would strip a
4
+ // value the tool documents, or document one it strips.
6
5
  //
7
- // Plan status and todo status happen to carry the same three values today. They stay separate
8
- // constants because ACP treats them as separate enums, and collapsing them would silently
9
- // couple two things that are free to diverge.
6
+ // Plan status and todo status carry the same three values today but stay separate constants:
7
+ // ACP treats them as separate enums and they are free to diverge.
10
8
 
11
9
  export const PLAN_PRIORITIES = /** @type {const} */ (["high", "medium", "low"]);
12
10
 
package/src/delegate.js CHANGED
@@ -2,9 +2,9 @@ import process from "node:process";
2
2
  import path from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { statSync } from "node:fs";
5
- // Reads happen on the server's only thread, where a synchronous one stalls every other
6
- // delegation in flight and the progress notifications they are streaming. The stats stay
7
- // synchronous: they are argument validation, and they run before the spawn.
5
+ // Async: a sync read on the server's only thread stalls every other in-flight delegation and
6
+ // its progress stream. The statSync calls below stay sync โ€” they are argument validation and
7
+ // run before the spawn.
8
8
  import { readFile } from "node:fs/promises";
9
9
  import { AcpClient } from "./acp-client.js";
10
10
  import { SessionSupervisor } from "./session-supervisor.js";
@@ -17,11 +17,9 @@ export const DEFAULT_MODEL = "composer-2.5";
17
17
  export const DEFAULT_HANDSHAKE_MS = 60000;
18
18
  export const DEFAULT_HEARTBEAT_MS = 30000;
19
19
 
20
- // Malformed values fall back to the default rather than failing the call. Only a positive
21
- // value counts: zero used to be taken literally, so CURSOR_DELEGATE_HARD_CAP_MS=0 โ€” or an
22
- // accidentally blank one, since Number("") is 0 โ€” armed a zero-length deadline that failed
23
- // every call instantly. Falling back keeps the one documented meaning of 0, the idle guard's,
24
- // which gets it from its own fallback being 0.
20
+ // Malformed values fall back to the default rather than failing the call. Only a positive value
21
+ // counts, so a blank var (Number("") is 0) cannot arm a zero-length deadline. The idle guard's
22
+ // documented 0 comes from its own fallback being 0, not from an env value.
25
23
  function envMs(name, fallback) {
26
24
  const raw = process.env[name];
27
25
  if (raw === undefined) return fallback;
@@ -34,11 +32,9 @@ function fmtDuration(ms) {
34
32
  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
35
33
  }
36
34
 
37
- // Two different questions, and conflating them is what made a typo'd brief cost a live turn.
38
- // "Could this be a path?" is deliberately loose โ€” a one-line brief ending in .md is worth a
39
- // stat. "Was a path clearly intended?" has to be strict, because an ordinary inline spec
40
- // mentions files ("fix the bug in src/api.js") and must never be rejected for it. Whitespace
41
- // is the discriminator: a path argument has none, a sentence about a path does.
35
+ // Two separate questions. "Could this be a path?" is loose โ€” worth a stat. "Was a path clearly
36
+ // intended?" must be strict, since ordinary prose names files ("fix the bug in src/api.js") and
37
+ // must never be rejected for it. Whitespace discriminates: a path argument has none.
42
38
  function looksLikeSpecPath(spec) {
43
39
  return !spec.includes("\n")
44
40
  && (spec.includes("/") || spec.includes("\\") || spec.endsWith(".md") || spec.endsWith(".txt"));
@@ -69,9 +65,8 @@ async function resolveSpec(spec) {
69
65
  return spec;
70
66
  }
71
67
 
72
- // A nonexistent workspace was accepted, then created by the agent's first write โ€” a typo
73
- // silently spawned a parallel empty tree and every layer reported success. contextFiles has
74
- // always rejected the same mistakes; this is that check, applied to its sibling.
68
+ // Without this, the agent's first write creates the directory: a typo'd workspace spawns a
69
+ // parallel empty tree and every layer reports success. Same check contextFiles applies.
75
70
  function assertWorkspace(workspace) {
76
71
  if (workspace === undefined || workspace === null) return;
77
72
  let stat;
@@ -92,19 +87,21 @@ const IMAGE_MIME = {
92
87
  // Base64 inflates by a third and every byte lands in the prompt, unlike a link.
93
88
  const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
94
89
 
95
- // A resource_link hands the agent a path instead of the file's bytes, so a large brief costs
96
- // prompt space only for what the agent decides to open. Images cannot work that way โ€” they
97
- // are sent inline. Both are measured working, including links to files outside the
98
- // workspace. Two rules follow from the probe:
99
- // - gate images on the advertised capability, because cursor-agent accepts blocks it does
100
- // not support without any error (embeddedContext:false raises nothing), so an ungated
101
- // image would silently vanish;
102
- // - report anything skipped, since a dropped attachment is otherwise invisible.
90
+ // A resource_link hands the agent a path, not the file's bytes, so a large brief costs prompt
91
+ // space only for what the agent opens. Images have no such form โ€” they go inline. Both are
92
+ // measured working, including links outside the workspace. Two rules from that probe:
93
+ // - gate images on the advertised capability: cursor-agent accepts unsupported blocks without
94
+ // error (embeddedContext:false raises nothing), so an ungated image vanishes silently;
95
+ // - report anything skipped โ€” a dropped attachment is otherwise invisible.
103
96
  async function buildContextBlocks(contextFiles, workspace, client, warnings) {
104
97
  const blocks = [];
105
- // A glob plus an explicit path (or the same file named a few ways) resolves to one file;
106
- // sending it several times just wastes prompt space. Collapse by resolved absolute path.
98
+ // A glob plus an explicit path can resolve to one file; sending it twice wastes prompt space.
107
99
  const seen = new Set();
100
+ // Grouped, not one warning per file: a wrong workspace misses every attachment at once, and a
101
+ // line each would repeat the same root N times for one root cause. The other skip reasons stay
102
+ // per-entry โ€” they are individually distinct and never arrive in bulk.
103
+ const notFound = [];
104
+ const root = path.resolve(workspace || process.cwd());
108
105
  for (const entry of contextFiles || []) {
109
106
  if (typeof entry !== "string" || !entry.trim()) continue;
110
107
  const abs = path.resolve(workspace || process.cwd(), entry);
@@ -114,7 +111,7 @@ async function buildContextBlocks(contextFiles, workspace, client, warnings) {
114
111
  try {
115
112
  stat = statSync(abs);
116
113
  } catch {
117
- warnings.push(`contextFile ${entry} skipped: not found at ${abs}`);
114
+ notFound.push(entry);
118
115
  continue;
119
116
  }
120
117
  if (!stat.isFile()) {
@@ -136,6 +133,12 @@ async function buildContextBlocks(contextFiles, workspace, client, warnings) {
136
133
  }
137
134
  blocks.push({ type: "resource_link", uri: pathToFileURL(abs).href, name: path.basename(abs) });
138
135
  }
136
+ if (notFound.length) {
137
+ warnings.push(
138
+ `contextFile${notFound.length > 1 ? "s" : ""} skipped: ${notFound.length} not found under ${root}`
139
+ + ` โ€” ${notFound.join(", ")}`
140
+ );
141
+ }
139
142
  return blocks;
140
143
  }
141
144
 
@@ -163,14 +166,11 @@ function assertKnownModel(client, model) {
163
166
  throw makeError("unknown-model", `Unknown model ${JSON.stringify(model)}. This agent offers: ${ids.join(", ")}.`);
164
167
  }
165
168
 
166
- // Which config options a model carries is not discoverable up front: session/new reports
167
- // configOptions for the default model and set_model returns nothing. So ask, and read the
168
- // rejection as the answer. Two distinct -32602s, both measured: "Unknown model config
169
- // option: X" means this model has no such knob โ€” report it and carry on. "Invalid value
170
- // for X: Y" means the caller named a value the model rejects, which must not be swallowed.
171
- // Returns { unsupported, res }: unsupported is true when the model has no such knob; res is the
172
- // set_config_option reply, which echoes the now-current model's configOptions (incl. the served
173
- // model id) โ€” the only place the agent reports what model actually took after set_model.
169
+ // A model's config options are not discoverable up front (session/new reports only the default
170
+ // model's; set_model returns nothing), so probe by asking and read the rejection. Both -32602s
171
+ // are measured: "Unknown model config option: X" means no such knob โ€” report and carry on;
172
+ // "Invalid value for X: Y" is a caller error and must propagate.
173
+ // res echoes the now-current model's configOptions โ€” the only place the served model id appears.
174
174
  async function applyConfig(client, sessionId, configId, value) {
175
175
  try {
176
176
  const res = await client.setConfigOption(sessionId, configId, value);
@@ -181,9 +181,8 @@ async function applyConfig(client, sessionId, configId, value) {
181
181
  }
182
182
  }
183
183
 
184
- // The agent reports the resolved model only inside a set_config_option reply's configOptions
185
- // (set_model itself returns nothing). Read it there when present; absent for models that reject
186
- // every option we send, which is fine โ€” the field then stays off.
184
+ // The resolved model appears only in a set_config_option reply's configOptions (set_model
185
+ // returns nothing). Absent for models that reject every option sent โ€” the field then stays off.
187
186
  function servedModelFrom(res) {
188
187
  const opts = res?.configOptions;
189
188
  if (!Array.isArray(opts)) return undefined;
@@ -213,8 +212,7 @@ export async function runDelegate({
213
212
  if (signal?.aborted) {
214
213
  throw makeError("aborted", "delegation aborted by MCP host");
215
214
  }
216
- // Before the spawn: a bad path is the caller's to fix, and finding out costs a process,
217
- // a handshake and a billed turn if it waits until the prompt is assembled.
215
+ // Before the spawn: validating later costs a process, a handshake and a billed turn.
218
216
  assertWorkspace(workspace);
219
217
  const promptText = await resolveSpec(spec);
220
218
  const capMs = hardCapMs ?? timeoutMs ?? envMs("CURSOR_DELEGATE_HARD_CAP_MS", 3600000);
@@ -222,9 +220,8 @@ export async function runDelegate({
222
220
  const turnIdleMs = idleMs ?? envMs("CURSOR_DELEGATE_IDLE_MS", 0);
223
221
  const state = makeTurnState({ onProgress, progressThrottleMs });
224
222
 
225
- // ACP requires plan entry content to be a string and bounds priority/status to
226
- // known values. Frames that violate that must not fail the MCP call after the
227
- // work is done โ€” drop the bad data and report it as a protocol diagnostic.
223
+ // ACP requires string plan content and bounds priority/status. A frame that violates that must
224
+ // not fail the MCP call after the work is done โ€” drop the bad data, report it as a diagnostic.
228
225
  const sanitizePlan = (warnings) => {
229
226
  const entries = [];
230
227
  state.planEntries.forEach((raw, i) => {
@@ -308,20 +305,19 @@ export async function runDelegate({
308
305
  heartbeat.unref?.();
309
306
  };
310
307
 
311
- // session/load replays the previous turn as ordinary session/update frames, including
312
- // tool_call and diff blocks. The reset before the prompt clears the state they touch,
313
- // but it cannot unsend the progress notifications they already emitted โ€” a resume
314
- // otherwise reports the previous turn's tool calls and edits as if they were happening.
308
+ // session/load replays the previous turn as ordinary update frames, tool_call and diff blocks
309
+ // included. state.reset() clears what they touch but cannot unsend a progress notification, so
310
+ // the guard below is what stops a resume reporting last turn's edits as if they were happening.
315
311
  client.on("update", (u) => {
316
312
  if (!promptInFlight) return;
317
313
  const up = u?.update || {};
318
314
  if (up.sessionUpdate === "plan") {
319
315
  state.planEntries = up.entries || [];
320
316
  }
321
- // The agent names the turn a beat after the prompt lands ("File Creator"). Useful as an
322
- // ephemeral label while several delegations run, and in timeout forensics โ€” but not in
323
- // the result, where it arrives after there is nothing left to tell apart and has been
324
- // measured contradicting the answer ("No Image Detected" on a turn describing an image).
317
+ // The agent titles the turn a beat after the prompt lands ("File Creator") โ€” useful live,
318
+ // when several delegations run, and in timeout forensics. Kept out of the result: there it
319
+ // arrives too late to tell anything apart, and was measured contradicting the answer
320
+ // ("No Image Detected" on a turn describing an image).
325
321
  if (up.sessionUpdate === "session_info_update" && typeof up.title === "string" && up.title) {
326
322
  if (up.title !== state.sessionTitle) { try { onProgress?.(`turn titled: ${up.title}`.slice(0, 200)); } catch {} }
327
323
  state.sessionTitle = up.title;
@@ -368,9 +364,9 @@ export async function runDelegate({
368
364
  onSessionReady?.(sessionId, client);
369
365
  assertKnownModel(client, model);
370
366
  await client.setModel(sessionId, model);
371
- // fast is always sent: a resumed session may already have it on, so false is a real
372
- // instruction. reasoning and context are only sent when the caller named one. Each reply
373
- // reports the now-current model; keep the last one seen as the served model.
367
+ // fast is always sent โ€” a resumed session may already have it on, so false is a real
368
+ // instruction. reasoning and context go only when the caller named one. Each reply reports
369
+ // the now-current model; the last one seen wins.
374
370
  const fastResult = await applyConfig(client, sessionId, "fast", fast);
375
371
  if (fastResult.unsupported && fast) unsupportedOptions.push("fast");
376
372
  else servedModel = servedModelFrom(fastResult.res) ?? servedModel;
@@ -390,9 +386,8 @@ export async function runDelegate({
390
386
  const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
391
387
  return await client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
392
388
  } finally {
393
- // The result is assembled across awaits below, so frames that trail the settled turn
394
- // would otherwise still be folded into it โ€” the same reason the flag exists for the
395
- // frames session/load replays before it.
389
+ // The result is assembled across awaits below, so without this a frame trailing the
390
+ // settled turn is still folded into it.
396
391
  promptInFlight = false;
397
392
  }
398
393
  });
@@ -404,13 +399,8 @@ export async function runDelegate({
404
399
  ? (state.sawToolCall ? "post-tool" : "tool-free-stream")
405
400
  : "none";
406
401
  const protocolWarnings = [];
407
- // plan.detail is the model restating โ€” into chat's sibling channel โ€” a plan it also filed via
408
- // create_plan. The detail is never load-bearing: the plan lives in the agent's own session
409
- // (which is what a resume-to-implement reads, not this field) and the orchestrator approves
410
- // from result + plan.entries. So in plan/ask drop the detail and let result be the agent's own
411
- // message verbatim โ€” no bridge-side guess at whether that message "is really the plan". In
412
- // agent mode the plan was accepted and result is the implementation report โ€” both stay.
413
- const dropPlanDetail = typeof state.planDetail === "string" && (mode === "plan" || mode === "ask");
402
+ // The mode alone decides this โ€” no bridge-side comparison of prose against entries.
403
+ const dropPlan = mode === "plan" || mode === "ask";
414
404
  if (!finalMessageAvailable && state.discardedResult) {
415
405
  result = state.discardedResult;
416
406
  resultSource = "pre-tool-fallback";
@@ -426,9 +416,8 @@ export async function runDelegate({
426
416
  if (typeof res.stopReason !== "string") {
427
417
  protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
428
418
  } else if (res.stopReason !== "end_turn") {
429
- // end_turn is the near-universal default and carries no signal โ€” it was end_turn on
430
- // every call across the stress test. Surface a stop reason only when it says something
431
- // happened: a refusal, a cancel, an output cap. Absence means the ordinary end_turn.
419
+ // end_turn carries no signal (it was end_turn on every stress-test call). Surface a stop
420
+ // reason only when something happened: a refusal, a cancel, an output cap.
432
421
  stopReason = res.stopReason;
433
422
  }
434
423
  }
@@ -436,16 +425,13 @@ export async function runDelegate({
436
425
  result,
437
426
  sessionId,
438
427
  };
439
- // Like every other collection here, absence means "nothing reported": an empty list on
440
- // every read-only turn read as a claim that nothing changed, which this field cannot make
441
- // (shell-driven edits leave no diff event).
428
+ // Absence means "nothing reported", not "nothing changed" โ€” a claim this field cannot make,
429
+ // since shell-driven edits leave no diff event.
442
430
  const filesReported = normalizeAgentReportedFiles([...state.touched], workspace);
443
431
  if (filesReported.length) out.filesReportedByEditTools = filesReported;
444
- // resultSource is a caveat, not a fact worth stating on every turn: on the happy path
445
- // (post-tool / tool-free-stream) result is simply the answer, so say nothing. Surface it only
446
- // when it warns โ€” pre-tool-fallback, none. finalMessageAvailable is dropped outright: it
447
- // stated the same thing in a second boolean. resumed is emitted only when a resume actually
448
- // took; a fresh session or a failed resume (which carries its own warning) leaves it absent.
432
+ // resultSource is a caveat, not a fact: on the happy path (post-tool / tool-free-stream)
433
+ // result is just the answer. Emit it only when it warns. resumed likewise appears only when a
434
+ // resume took โ€” a fresh session or a failed one (which carries its own warning) leaves it off.
449
435
  if (resultSource !== "post-tool" && resultSource !== "tool-free-stream") out.resultSource = resultSource;
450
436
  if (!!resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
451
437
  // Only when the agent served a different model than asked โ€” e.g. "default" routing to a
@@ -458,15 +444,19 @@ export async function runDelegate({
458
444
  for (const id of unsupportedOptions) protocolWarnings.push(`model ${model} has no ${id} option; the requested value was ignored`);
459
445
  protocolWarnings.push(...contextWarnings);
460
446
  if (state.planEntries.length > 0 || state.planOverview !== undefined || state.planDetail !== undefined) {
461
- out.plan = sanitizePlan(protocolWarnings);
462
- // In plan/ask result already carries the agent's own plan message, so the detail here is a
463
- // duplicate โ€” drop it. entries and overview are structured and unique, and always stay.
464
- if (dropPlanDetail) delete out.plan.detail;
447
+ // Sanitize even when the plan is discarded: the warnings it raises report malformed ACP
448
+ // frames, which the caller needs whatever mode it asked for.
449
+ const plan = sanitizePlan(protocolWarnings);
450
+ // In plan/ask, result IS the plan โ€” the agent's own message, already prose and already
451
+ // what gets shown to the user for approval. Returning entries alongside it puts the same
452
+ // steps in the orchestrator's context twice, and nothing consumes them: the resume that
453
+ // implements reads the agent's own session, not this field. In agent mode result is the
454
+ // implementation report, a separate artifact from the plan, so the whole object stays.
455
+ if (!dropPlan) out.plan = plan;
465
456
  }
466
- // Most successful turns emit no todos at all, so an empty list would read as "nothing
467
- // done" rather than "not tracked". Report only what the agent actually sent โ€” and of
468
- // that, the full list only when it says something todoProgress cannot: which items
469
- // remain. On a fully-completed turn the list restates the counts entry by entry.
457
+ // Most turns emit no todos, so an empty list would read as "nothing done" rather than "not
458
+ // tracked". The full list is carried only when it says what todoProgress cannot โ€” which items
459
+ // remain; on a fully-completed turn it just restates the counts.
470
460
  if (state.sawTodoFrame) {
471
461
  const { todos: todoList, todoProgress } = sanitizeTodos(protocolWarnings);
472
462
  out.todoProgress = todoProgress;
@@ -475,17 +465,15 @@ export async function runDelegate({
475
465
  if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
476
466
  return out;
477
467
  } catch (err) {
478
- // A JSON-RPC code means the agent rejected something rather than the bridge breaking.
479
- // Classifying it here is what lets the caller tell "fix your arguments" from "retry".
468
+ // A JSON-RPC code means the agent rejected something rather than the bridge breaking โ€” the
469
+ // distinction a caller needs to tell "fix your arguments" from "retry".
480
470
  if (!err?.reason && typeof err?.code === "number") err.reason = "agent-error";
481
- // A bare duration says nothing about whether the agent wedged or a command was just
482
- // slow. Name what was outstanding so the caller can tell the two apart, and so a
483
- // retry can resume from the work already done instead of restarting blind.
471
+ // A bare duration cannot distinguish a wedged agent from a slow command, so name what was
472
+ // outstanding โ€” it also lets a retry resume the work already done.
484
473
  const isTimeout = err?.reason === "hard-cap" || err?.reason === "idle-timeout";
485
- // A handshake timeout gets the forensics but not the long-command advice below: the
486
- // session exists by then โ€” it is set before set_model, set_config_option and set_mode,
487
- // any of which can hang โ€” so the resume hint is what the caller needs. No prompt was
488
- // ever sent, so no shell command can be the reason for the silence.
474
+ // A handshake timeout gets the forensics but not the long-command advice: no prompt was sent,
475
+ // so no shell command explains the silence. The session may still exist (it is set before
476
+ // set_model/set_config_option/set_mode, any of which can hang), so the resume hint applies.
489
477
  const isStall = isTimeout || err?.reason === "handshake-timeout";
490
478
  if (isStall || err?.reason === "aborted" || err?.reason === "agent-exit") {
491
479
  const age = fmtDuration(supervisor.msSinceActivity());
@@ -500,7 +488,7 @@ export async function runDelegate({
500
488
  const files = normalizeAgentReportedFiles([...state.touched], workspace);
501
489
  if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
502
490
  // Without this the resume hint below reads as "carry on from where you were", when the
503
- // requested session was never loaded and this turn started from nothing.
491
+ // requested session was never loaded.
504
492
  if (resumeError) {
505
493
  err.message += ` Note: resuming ${resumeSessionId} had already failed (${resumeError}),`
506
494
  + ` so this ran as a fresh session and none of that earlier work was in context.`;
@@ -514,10 +502,8 @@ export async function runDelegate({
514
502
  + ` nothing until it exits. Split the command, run it in the background and poll, or raise ${knob}.`;
515
503
  }
516
504
  }
517
- // Opt-in, because the frames land in the caller's context and nothing there is
518
- // actionable: the forensics above already carry everything a caller can act on. Raw
519
- // frames only help someone debugging the bridge, and that has always been done with a
520
- // protocol probe, never with an error dump.
505
+ // Opt-in: the frames land in the caller's context and nothing there is actionable โ€” the
506
+ // forensics above already carry that. Raw frames only help someone debugging the bridge.
521
507
  const frames = Number(process.env.CURSOR_DELEGATE_TRANSCRIPT);
522
508
  if (frames > 0) {
523
509
  try {
package/src/doctor.js CHANGED
@@ -13,10 +13,9 @@ function formatCommand({ command, args }) {
13
13
  return args?.length ? `${command} ${args.join(" ")}` : command;
14
14
  }
15
15
 
16
- // A launcher that accepts --version and then never answers used to hang doctor forever โ€” and
17
- // doctor is the tool you run when delegation is already broken, so a wedged agent is exactly
18
- // the case it has to survive. Deep handshakes have always been time-boxed; this is that guard
19
- // applied to the shallow probe that runs on every call.
16
+ // Time-boxed because a launcher that accepts --version and then never answers would hang doctor
17
+ // forever โ€” and doctor is what you run when delegation is already broken, so a wedged agent is
18
+ // exactly the case it must survive. Same guard the deep handshake has.
20
19
  export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_MS) {
21
20
  const { command, options } = spawnSpec;
22
21
  const isJsScript = /\.js$/i.test(command);
package/src/server.js CHANGED
@@ -11,8 +11,8 @@ import { VERSION } from "./version.js";
11
11
  import { PLAN_PRIORITIES, PLAN_STATUSES, TODO_STATUSES } from "./acp-enums.js";
12
12
 
13
13
  const nodeMajor = Number(process.versions.node.split(".")[0]);
14
- if (nodeMajor < 22) {
15
- console.error(`cursor-delegate-mcp requires Node 22+ (found ${process.versions.node})`);
14
+ if (nodeMajor < 20) {
15
+ console.error(`cursor-delegate-mcp requires Node 20+ (found ${process.versions.node})`);
16
16
  process.exit(1);
17
17
  }
18
18
 
@@ -26,6 +26,10 @@ function registerInFlight(map, sessionId, handle) {
26
26
  if (handles) handles.add(handle);
27
27
  else map.set(sessionId, new Set([handle]));
28
28
  }
29
+ /** @returns {import("@modelcontextprotocol/sdk/types.js").CallToolResult} */
30
+ function cancelResult(status, sessionId) {
31
+ return { content: [{ type: "text", text: JSON.stringify({ status, sessionId }) }] };
32
+ }
29
33
  function unregisterInFlight(map, sessionId, handle) {
30
34
  const handles = map.get(sessionId);
31
35
  if (!handles) return;
@@ -54,46 +58,35 @@ const planEntrySchema = z.object({
54
58
  status: z.enum(PLAN_STATUSES).optional(),
55
59
  }).passthrough();
56
60
 
57
- // Exported as a plain shape so tests can build a .strict() copy of it. Production stays
58
- // passthrough โ€” a field the agent adds must not fail a finished call โ€” but that same
59
- // tolerance means a field added in delegate.js and forgotten here would never be advertised
60
- // to hosts, and nothing would complain. The strict copy is what complains.
61
+ // No tool declares an outputSchema: declaring one obliges the server to also return
62
+ // structuredContent, and a host that reads both it and the text block โ€” Codex does โ€” puts the
63
+ // payload in the model's context twice. Every tool returns one compact JSON text block instead.
64
+ // So this is an in-repo contract, enforced by the .strict() copy in delegate.test.js, which
65
+ // fails when a field added in delegate.js is forgotten here. cancel's status vocabulary is
66
+ // published in its tool description, which is now its only schema.
67
+ //
68
+ // Types only. What each field means, and what its absence means, is documented once in
69
+ // skills/delegate/reference.md.
61
70
  export const delegateOutputShape = {
62
71
  result: z.string(),
63
- resultSource: z.enum(["pre-tool-fallback", "none"]).optional().describe(
64
- "Present only as a caveat on result; absent on the happy path, where result is simply the agent's answer. pre-tool-fallback: no final message closed the turn and result is the last message before the agent's final tool call โ€” read protocolWarnings before trusting it. none: the turn produced no message and result is empty."
65
- ),
66
- effectiveModel: z.string().optional().describe(
67
- "The model id the agent reported serving, present only when it differs from the model you requested โ€” e.g. \"default\" resolving to a concrete id, or a cross-model resume. Read from the agent's post-set_model config report; absent when the agent confirmed the requested id or reported no model (some models report none)."
68
- ),
69
- stopReason: z.string().optional().describe(
70
- "Present only when it is not the ordinary end_turn โ€” a refusal, a cancel, or an output cap. Absence means the turn ended normally."
71
- ),
72
+ resultSource: z.enum(["pre-tool-fallback", "none"]).optional(),
73
+ effectiveModel: z.string().optional(),
74
+ stopReason: z.string().optional(),
72
75
  sessionId: z.string(),
73
- filesReportedByEditTools: z.array(z.string()).optional().describe(
74
- "Files the agent's edit tools reported changing, via native ACP diff events. Absent when they reported none โ€” which is not proof nothing changed: shell-driven edits leave no diff event; the git diff is authoritative."
75
- ),
76
- resumed: z.boolean().optional().describe(
77
- "Present and true only when a requested resume took (the returned session id matched resumeSessionId). Absent for a fresh session, or when a resume failed โ€” a failed resume is reported in protocolWarnings."
78
- ),
76
+ filesReportedByEditTools: z.array(z.string()).optional(),
77
+ resumed: z.boolean().optional(),
79
78
  cancelRequested: z.boolean().optional(),
80
- protocolWarnings: z.array(z.string()).optional().describe(
81
- "Non-fatal diagnostics that did not justify failing the call โ€” dropped or sanitized ACP fields, a failed resume, ignored model options, skipped contextFiles. Read whenever present."
82
- ),
79
+ protocolWarnings: z.array(z.string()).optional(),
83
80
  plan: z.object({
84
81
  entries: z.array(planEntrySchema),
85
82
  overview: z.string().optional(),
86
83
  detail: z.string().optional(),
87
- }).optional().describe(
88
- "The agent's plan. entries and overview are the structured plan and always present when a plan exists. detail (a prose rendition the agent also filed) is kept only in agent mode; in plan/ask it is dropped because result already carries the agent's own plan message. To act on a plan, resume the sessionId rather than forwarding detail: the plan lives in the agent's session."
89
- ),
84
+ }).optional(),
90
85
  todos: z.array(z.object({
91
86
  id: z.string(),
92
87
  content: z.string(),
93
88
  status: z.enum(TODO_STATUSES).optional(),
94
- })).optional().describe(
95
- "Todo items the agent left unfinished, present only when todoProgress shows completed < total โ€” read it to see what remains before resuming. Absent both when the agent tracked no todos (common on short tasks) and when everything tracked was completed; todoProgress tells those apart."
96
- ),
89
+ })).optional(),
97
90
  todoProgress: z.object({
98
91
  total: z.number(),
99
92
  completed: z.number(),
@@ -102,32 +95,28 @@ export const delegateOutputShape = {
102
95
  }).optional(),
103
96
  };
104
97
 
105
- const delegateOutputSchema = z.object(delegateOutputShape).passthrough();
106
-
107
- // What doctor reports about the launcher. Only `found` was advertised before, so `command`,
108
- // `version`, `error` and the whole deep handshake reached hosts undeclared โ€” the same drift
109
- // delegateOutputShape exists to prevent, one level further down.
98
+ // What doctor reports about the launcher โ€” the same in-repo contract as delegateOutputShape.
99
+ //
100
+ // Fields this bridge computes are typed; fields relayed verbatim from the agent are left unknown
101
+ // on purpose. doctor runs when the agent is already misbehaving, so a schema tight enough to
102
+ // reject a weird protocolVersion would fail on the agent's output rather than on ours.
103
+ // doctor.test.js parses every result against a strict copy of this shape.
110
104
  //
111
- // Fields this bridge computes are typed; fields relayed verbatim from the agent are left
112
- // unknown on purpose. The SDK validates structuredContent against this schema and throws when
113
- // it does not fit, and doctor is what you run when the agent is already misbehaving: a schema
114
- // tight enough to reject a weird protocolVersion would turn the diagnostic into a crash.
105
+ // Types only; what the fields mean is documented once, in TECHNICAL.md.
115
106
  export const doctorAgentShape = {
116
- found: z.boolean().describe("Whether the launcher command could be spawned at all."),
117
- command: z.string().describe("The resolved launcher command line, with ACP_AGENT_COMMAND/ACP_AGENT_ARGS applied."),
118
- version: z.string().nullable().describe(
119
- "The launcher's --version output, or null when it could not be read. found:false means it is not installed; found:true with a null version means it exists but did not answer โ€” error says why."
120
- ),
121
- error: z.string().optional().describe("Why version is null on a launcher that does exist, e.g. the probe timed out."),
107
+ found: z.boolean(),
108
+ command: z.string(),
109
+ version: z.string().nullable(),
110
+ error: z.string().optional(),
122
111
  handshake: z.object({
123
112
  ok: z.boolean(),
124
- error: z.string().optional().describe("Present when ok is false: what the handshake failed on, e.g. not logged in, or a timeout."),
125
- protocolVersion: z.unknown().optional().describe("As reported by the agent; null when it reported none."),
113
+ error: z.string().optional(),
114
+ protocolVersion: z.unknown().optional(),
126
115
  agentCapabilities: z.unknown().optional(),
127
- models: z.array(z.unknown()).optional().describe("Model ids the agent offers for a new session."),
116
+ models: z.array(z.unknown()).optional(),
128
117
  currentModel: z.unknown().optional(),
129
- modes: z.array(z.unknown()).optional().describe("Session mode ids the agent offers."),
130
- }).passthrough().optional().describe("Present only when deep is true. Everything past ok and error is absent when ok is false."),
118
+ modes: z.array(z.unknown()).optional(),
119
+ }).passthrough().optional(),
131
120
  };
132
121
 
133
122
  // Exported as a shape for the same reason as delegateOutputShape, and with agent split out
@@ -151,8 +140,6 @@ export const doctorOutputShape = {
151
140
  env: z.record(z.unknown()),
152
141
  };
153
142
 
154
- const doctorOutputSchema = z.object(doctorOutputShape).passthrough();
155
-
156
143
  export const delegateInputSchema = z.object({
157
144
  spec: z.string().trim().min(1, "spec must not be blank").describe("Inline task brief (default): goal, scope, decisions already made (constraints and fixed choices โ€” quote the user's exact values verbatim), acceptance criteria. Point at files to read or mimic rather than pasting code. Optional file path if the user wants a persisted spec."),
158
145
  mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("Requested agent mode. plan and ask are passed to the agent as instructions, not enforced by the bridge โ€” the agent may write in any of them, so review the git diff after every run. ask held on every model tested while plan compliance varies by model, so prefer ask when you need the stricter read-only instruction."),
@@ -222,10 +209,7 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, seen
222
209
  },
223
210
  });
224
211
  if (handle?.cancelRequested) out.cancelRequested = true;
225
- return {
226
- content: [{ type: "text", text: JSON.stringify(out, null, 2) }],
227
- structuredContent: out,
228
- };
212
+ return { content: [{ type: "text", text: JSON.stringify(out) }] };
229
213
  } catch (err) {
230
214
  return {
231
215
  // The reason is already decided upstream; naming it here saves the caller parsing
@@ -261,7 +245,6 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
261
245
  description:
262
246
  `Delegate a coding task to cursor-agent over ACP. Never shell out to cursor-agent โ€” use this tool only. Pass structured task text inline in spec (default); a file path is optional when the user wants a persisted brief. Defaults: mode=agent, model=${DEFAULT_MODEL}, fast=false. Plan workflow: mode=plan, then resume with mode=agent and resumeSessionId. Auto-approves every permission the agent requests, in any mode and anywhere on disk. Clarifying questions arrive as prose in result โ€” resume with resumeSessionId to answer. Returns the final result, selection source, stop reason, session ID, agent-reported files, and optional plan. See the delegate skill for orchestration.`,
263
247
  inputSchema: delegateInputSchema,
264
- outputSchema: delegateOutputSchema,
265
248
  annotations: {
266
249
  title: "Delegate coding task to Cursor",
267
250
  readOnlyHint: false,
@@ -282,7 +265,6 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
282
265
  sessionId: z.string(),
283
266
  force: z.boolean().default(false).describe("After the cancel notify, wait a short grace period and kill the agent process if the delegation is still running"),
284
267
  },
285
- outputSchema: z.object({ status: z.enum(["cancelled", "killed", "not-running", "not-found"]), sessionId: z.string() }),
286
268
  annotations: {
287
269
  title: "Cancel Cursor delegation",
288
270
  readOnlyHint: false,
@@ -294,15 +276,10 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
294
276
  async ({ sessionId, force }) => {
295
277
  const handles = inFlight.get(sessionId);
296
278
  if (!handles || handles.size === 0) {
297
- // A finished session and a garbage id used to look identical (both not-found), which
298
- // read as "bad id" for a session that in fact ran and is still resumable. Split them.
279
+ // A finished session and a garbage id are both "not in flight". Reporting them alike
280
+ // would read as "bad id" for a session that ran and is still resumable.
299
281
  const known = seenSessions.has(sessionId);
300
- return {
301
- content: [{ type: "text", text: known
302
- ? `session ${sessionId} is not running; its turn already ended (still resumable via resumeSessionId)`
303
- : `no in-flight session ${sessionId}` }],
304
- structuredContent: { status: known ? "not-running" : "not-found", sessionId },
305
- };
282
+ return cancelResult(known ? "not-running" : "not-found", sessionId);
306
283
  }
307
284
  // Cancel every turn running on the id: the caller named a session, not one of the
308
285
  // turns that happen to share it.
@@ -313,25 +290,14 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
313
290
  // be running. Dropping them here made the natural escalation โ€” cancel, wait, cancel
314
291
  // with force โ€” report not-found while the agent was alive. Each delegation's own
315
292
  // finally removes its handle when the turn actually settles.
316
- return {
317
- content: [{ type: "text", text: `cancelled ${sessionId}` }],
318
- structuredContent: { status: "cancelled", sessionId },
319
- };
293
+ return cancelResult("cancelled", sessionId);
320
294
  }
321
295
  await new Promise((r) => setTimeout(r, forceGraceMs));
322
296
  const stillRunning = inFlight.get(sessionId);
323
- if (!stillRunning || stillRunning.size === 0) {
324
- return {
325
- content: [{ type: "text", text: `cancelled ${sessionId}` }],
326
- structuredContent: { status: "cancelled", sessionId },
327
- };
328
- }
297
+ if (!stillRunning || stillRunning.size === 0) return cancelResult("cancelled", sessionId);
329
298
  for (const handle of stillRunning) handle.client.stop();
330
299
  inFlight.delete(sessionId);
331
- return {
332
- content: [{ type: "text", text: `killed ${sessionId}` }],
333
- structuredContent: { status: "killed", sessionId },
334
- };
300
+ return cancelResult("killed", sessionId);
335
301
  }
336
302
  );
337
303
 
@@ -346,7 +312,6 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
346
312
  .default(false)
347
313
  .describe("When true, run a lightweight ACP handshake (start โ†’ initialize โ†’ newSession) to verify the agent is usable"),
348
314
  },
349
- outputSchema: doctorOutputSchema,
350
315
  annotations: {
351
316
  title: "Diagnose Cursor delegation setup",
352
317
  readOnlyHint: true,
@@ -363,10 +328,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
363
328
  version: server.server.getClientVersion(),
364
329
  }),
365
330
  });
366
- return {
367
- content: [{ type: "text", text: JSON.stringify(out, null, 2) }],
368
- structuredContent: out,
369
- };
331
+ return { content: [{ type: "text", text: JSON.stringify(out) }] };
370
332
  }
371
333
  );
372
334
 
package/src/turn-state.js CHANGED
@@ -1,9 +1,8 @@
1
- // Everything that describes the turn in progress, in one object because it has to be wiped as
2
- // one: session/load replays the previous turn as ordinary update frames, so anything left
3
- // behind leaks into the next result. This used to be a dozen loose variables cleared by a
4
- // hand-written block before each prompt, where forgetting a line was a silent stale-data bug
5
- // on resume โ€” and the list grew every time a field was added. Fields are declared in exactly
6
- // one place now, freshFields(), which is also what reset() applies.
1
+ // Everything describing the turn in progress, in one object because it has to be wiped as one:
2
+ // session/load replays the previous turn as ordinary update frames, so anything left behind
3
+ // leaks into the next result. Fields are declared in exactly one place, freshFields(), which is
4
+ // also what reset() applies โ€” a field added there is reset for free, and one that is missed is a
5
+ // silent stale-data bug on resume.
7
6
 
8
7
  const MAX_OUTPUT = 10 * 1024 * 1024;
9
8
  const TRUNCATION_MARKER = "\n\n[output truncated at 10MB]";
@@ -55,18 +54,17 @@ function progressStream(prefix, onProgress, throttleMs) {
55
54
  };
56
55
  }
57
56
 
58
- // The single declaration of what a turn accumulates. Anything added here is reset for free.
57
+ // The single declaration of what a turn accumulates.
59
58
  function freshFields() {
60
59
  return {
61
60
  resultChunks: [],
62
61
  resultLength: 0,
63
62
  truncated: false,
64
63
  // Text superseded by a later tool call is normally a preamble ("Inspecting the
65
- // implementation.") and returning it would be inventing a summary. But the rule cannot
66
- // tell a preamble from the whole answer: an agent that replies and then runs one more
67
- // command has its entire reply discarded, and the caller gets "" with stopReason end_turn
68
- // and no error. So keep the last discarded segment and hand it back only when nothing
69
- // survived โ€” labelled, never blended with a real final message.
64
+ // implementation."), but the rule cannot tell a preamble from the whole answer: an agent
65
+ // that replies and then runs one more command has its entire reply discarded, leaving the
66
+ // caller "" with stopReason end_turn and no error. Kept so it can be handed back when
67
+ // nothing survived โ€” labelled, never blended with a real final message.
70
68
  discardedResult: "",
71
69
  sawToolCall: false,
72
70
  collectingPostToolResult: false,
package/src/version.js CHANGED
@@ -11,11 +11,10 @@ function readVersion() {
11
11
  // Captured once, for the ACP/MCP identity handshake that is sent at connect and never re-read.
12
12
  export const VERSION = readVersion();
13
13
 
14
- // doctor calls this instead of the constant. The MCP child is long-lived and /reload-plugins
15
- // does not restart it, so a version captured at process start goes stale after an in-place
16
- // upgrade โ€” exactly when someone runs doctor to confirm the new version shipped. Reading fresh
17
- // is truthful whenever the process was restarted (the normal case); the one residual gap is an
18
- // un-restarted child running old code, where no in-process value can be authoritative anyway.
14
+ // doctor reads fresh rather than using the constant: the MCP child is long-lived and
15
+ // /reload-plugins does not restart it, so a version captured at process start goes stale after
16
+ // an in-place upgrade โ€” exactly when doctor is run to confirm the new version shipped. An
17
+ // un-restarted child running old code stays a gap, but no in-process value can close that.
19
18
  export function readPackageVersion() {
20
19
  try {
21
20
  return readVersion();