cursor-delegate-mcp 1.10.0 → 1.11.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "1.10.0",
3
+ "version": "1.11.1",
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",
package/src/delegate.js CHANGED
@@ -36,6 +36,13 @@ const isBareSpecPath = (spec) => !/\s/.test(spec.trim());
36
36
 
37
37
  function resolveSpec(spec) {
38
38
  if (typeof spec !== "string") return spec;
39
+ // A blank spec spins up a live session that only replies "No prompt content provided" —
40
+ // a billed turn for nothing. Reject it here, before the spawn, like the other bad specs.
41
+ if (spec.trim() === "") {
42
+ const err = new Error("spec is empty. Provide a task brief inline, or a path to one.");
43
+ err.reason = "invalid-spec";
44
+ throw err;
45
+ }
39
46
  if (!looksLikeSpecPath(spec)) return spec;
40
47
  let stat;
41
48
  try {
@@ -94,9 +101,14 @@ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
94
101
  // - report anything skipped, since a dropped attachment is otherwise invisible.
95
102
  function buildContextBlocks(contextFiles, workspace, client, warnings) {
96
103
  const blocks = [];
104
+ // A glob plus an explicit path (or the same file named a few ways) resolves to one file;
105
+ // sending it several times just wastes prompt space. Collapse by resolved absolute path.
106
+ const seen = new Set();
97
107
  for (const entry of contextFiles || []) {
98
108
  if (typeof entry !== "string" || !entry.trim()) continue;
99
109
  const abs = path.resolve(workspace || process.cwd(), entry);
110
+ if (seen.has(abs)) continue;
111
+ seen.add(abs);
100
112
  let stat;
101
113
  try {
102
114
  stat = statSync(abs);
@@ -169,7 +181,7 @@ async function applyConfig(client, sessionId, configId, value) {
169
181
  }
170
182
 
171
183
  export async function runDelegate({
172
- spec, mode = "agent", resumeSessionId, workspace,
184
+ spec, mode = "agent", resumeSessionId, workspace, maxResultChars,
173
185
  model = DEFAULT_MODEL, fast = false, reasoning, context, contextFiles, clientFactory, onElicit,
174
186
  idleMs, handshakeMs, hardCapMs, timeoutMs,
175
187
  onSessionReady, onProgress, progressThrottleMs = 2000,
@@ -558,37 +570,79 @@ export async function runDelegate({
558
570
  ? (sawToolCall ? "post-tool" : "tool-free-stream")
559
571
  : "none";
560
572
  const protocolWarnings = [];
561
- if (!finalMessageAvailable && discardedResult) {
562
- result = discardedResult;
563
- resultSource = "pre-tool-fallback";
573
+ // plan.detail is the model restating — into chat's sibling channel — a plan it also filed via
574
+ // create_plan; cursor-agent narrates across the IDE's two surfaces and here they flatten into
575
+ // one ACP payload. The detail is never load-bearing: the plan lives in the agent's own session
576
+ // (which is what a resume-to-implement reads, not this field) and the orchestrator approves
577
+ // from result + plan.entries. So in plan/ask keep the plan in one prose channel — drop the
578
+ // detail as a duplicate when result already is a real plan message, fold it into result when
579
+ // the message is too terse (or a fallback preamble) to be the plan itself. In agent mode the
580
+ // plan was accepted and result is the implementation report, a separate artifact — both stay.
581
+ const PLAN_TERSE_FLOOR = 200;
582
+ let dropPlanDetail = false;
583
+ if (typeof planDetail === "string" && (mode === "plan" || mode === "ask")) {
584
+ dropPlanDetail = true;
585
+ if (!(finalMessageAvailable && result.length >= PLAN_TERSE_FLOOR)) {
586
+ result = planDetail;
587
+ resultSource = "plan-detail";
588
+ }
589
+ }
590
+ if (resultSource !== "plan-detail") {
591
+ if (!finalMessageAvailable && discardedResult) {
592
+ result = discardedResult;
593
+ resultSource = "pre-tool-fallback";
594
+ protocolWarnings.push(
595
+ "the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
596
+ + " result carries the last message before that tool call — it may be a preamble rather than the answer."
597
+ );
598
+ } else if (!finalMessageAvailable) {
599
+ protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
600
+ }
601
+ }
602
+ // A runaway reply comes back whole and can blow the caller's context (104K chars in one
603
+ // test). When the caller sets a ceiling, cut the result to it and say so, so the truncation
604
+ // is never mistaken for a complete answer.
605
+ if (Number.isFinite(maxResultChars) && maxResultChars > 0 && result.length > maxResultChars) {
606
+ const original = result.length;
607
+ result = result.slice(0, maxResultChars) + `\n\n[result truncated at ${maxResultChars} chars]`;
564
608
  protocolWarnings.push(
565
- "the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
566
- + " result carries the last message before that tool call — it may be a preamble rather than the answer."
609
+ `result was ${original} chars and exceeded maxResultChars ${maxResultChars}; it was truncated.`
610
+ + " Raise maxResultChars or narrow the task if you need the full output."
567
611
  );
568
- } else if (!finalMessageAvailable) {
569
- protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
570
612
  }
571
613
  let stopReason;
572
614
  if (res?.stopReason !== undefined) {
573
- if (typeof res.stopReason === "string") stopReason = res.stopReason;
574
- else protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
615
+ if (typeof res.stopReason !== "string") {
616
+ protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
617
+ } else if (res.stopReason !== "end_turn") {
618
+ // end_turn is the near-universal default and carries no signal — it was end_turn on
619
+ // every call across the stress test. Surface a stop reason only when it says something
620
+ // happened: a refusal, a cancel, an output cap. Absence means the ordinary end_turn.
621
+ stopReason = res.stopReason;
622
+ }
575
623
  }
576
624
  const out = {
577
625
  result,
578
626
  resultSource,
579
627
  finalMessageAvailable,
580
- stopReason,
581
628
  sessionId,
582
629
  filesReportedByAgent: normalizeAgentReportedFiles([...touched], workspace),
583
- questionsAsked,
584
630
  resumed: !!resumeSessionId && sessionId === resumeSessionId,
585
631
  };
632
+ if (stopReason !== undefined) out.stopReason = stopReason;
633
+ // Elicitation almost never fires (the agent tends to ask in prose and end the turn), so an
634
+ // always-empty array is steady noise. Report it only when a question actually came through.
635
+ if (questionsAsked.length) out.questionsAsked = questionsAsked;
586
636
  if (sessionTitle) out.sessionTitle = sessionTitle;
587
637
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
588
638
  for (const id of unsupportedOptions) protocolWarnings.push(`model ${model} has no ${id} option; the requested value was ignored`);
589
639
  protocolWarnings.push(...contextWarnings);
590
640
  if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
591
641
  out.plan = sanitizePlan(protocolWarnings);
642
+ // In plan/ask the plan is already carried by result (a real message, or folded in per the
643
+ // one-plan contract above), so the detail here is a duplicate — drop it. entries and
644
+ // overview are structured and unique, and always stay.
645
+ if (dropPlanDetail) delete out.plan.detail;
592
646
  }
593
647
  // Most successful turns emit no todos at all, so an empty list would read as "nothing
594
648
  // done" rather than "not tracked". Report only what the agent actually sent.
package/src/doctor.js CHANGED
@@ -2,7 +2,7 @@ import process from "node:process";
2
2
  import { spawn } from "node:child_process";
3
3
  import { AcpClient } from "./acp-client.js";
4
4
  import { resolveAcpSpawn } from "./spawn.js";
5
- import { VERSION } from "./version.js";
5
+ import { readPackageVersion } from "./version.js";
6
6
 
7
7
  const HANDSHAKE_TIMEOUT_MS = 15_000;
8
8
  const DEFAULT_LOG_SIZE = "2000";
@@ -75,12 +75,13 @@ export async function runDoctor({
75
75
  clientFactory = (opts) => new AcpClient(opts),
76
76
  workspace,
77
77
  handshakeTimeoutMs = HANDSHAKE_TIMEOUT_MS,
78
+ readVersion = readPackageVersion,
78
79
  } = {}) {
79
80
  const { capabilities, version } = getClientInfo();
80
81
  const agentProbe = await probeAgentVersion(spawnSpec);
81
82
 
82
83
  const out = {
83
- plugin: { version: VERSION },
84
+ plugin: { version: readVersion() },
84
85
  client: {
85
86
  name: version?.name ?? null,
86
87
  version: version?.version ?? null,
package/src/server.js CHANGED
@@ -16,6 +16,16 @@ if (nodeMajor < 22) {
16
16
  }
17
17
 
18
18
  const inFlight = new Map();
19
+ // Session ids seen this process, kept after the turn ends so cancel can tell a finished
20
+ // session (resumable, only the turn is over) from an id that never existed. Bounded so a
21
+ // long-lived server does not grow without limit.
22
+ const seenSessions = new Set();
23
+ const SEEN_SESSIONS_CAP = 500;
24
+ function rememberSession(set, id) {
25
+ if (id == null || set.has(id)) return;
26
+ set.add(id);
27
+ if (set.size > SEEN_SESSIONS_CAP) set.delete(set.values().next().value);
28
+ }
19
29
 
20
30
  // Loaded at connect, before any tool schema is, so this carries only pre-call facts: what a
21
31
  // caller needs to decide whether to delegate at all. Call-time facts belong on the parameter
@@ -30,16 +40,20 @@ const planEntrySchema = z.object({
30
40
 
31
41
  const delegateOutputSchema = z.object({
32
42
  result: z.string(),
33
- resultSource: z.enum(["tool-free-stream", "post-tool", "pre-tool-fallback", "none"]).optional().describe(
34
- "Where result came from. pre-tool-fallback means no final message closed the turn and result is the last message before the agent's final tool call — read protocolWarnings before trusting it as the answer."
43
+ resultSource: z.enum(["tool-free-stream", "post-tool", "pre-tool-fallback", "plan-detail", "none"]).optional().describe(
44
+ "Where result came from. pre-tool-fallback means no final message closed the turn and result is the last message before the agent's final tool call — read protocolWarnings before trusting it as the answer. plan-detail (plan/ask only) means the agent's chat message was too terse to be the plan, so result carries the plan it filed via create_plan."
35
45
  ),
36
46
  finalMessageAvailable: z.boolean().optional(),
37
- stopReason: z.string().optional(),
47
+ stopReason: z.string().optional().describe(
48
+ "Present only when it is not the ordinary end_turn — a refusal, a cancel, or an output cap. Absence means the turn ended normally."
49
+ ),
38
50
  sessionId: z.string(),
39
51
  filesReportedByAgent: z.array(z.string()).describe(
40
52
  "Files the agent reported editing via native ACP diff events (may omit shell-driven edits)."
41
53
  ),
42
- questionsAsked: z.array(z.string()).optional(),
54
+ questionsAsked: z.array(z.string()).optional().describe(
55
+ "Clarifying questions the agent raised through elicitation. Absent on most turns — the agent usually asks in prose and ends the turn, which this does not capture; read result for that."
56
+ ),
43
57
  resumed: z.boolean().optional(),
44
58
  sessionTitle: z.string().optional().describe(
45
59
  "Short title the agent gave this turn. Present on most turns; purely a label."
@@ -54,7 +68,9 @@ const delegateOutputSchema = z.object({
54
68
  entries: z.array(planEntrySchema),
55
69
  overview: z.string().optional(),
56
70
  detail: z.string().optional(),
57
- }).optional(),
71
+ }).optional().describe(
72
+ "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 plan — as the agent's own message, or folded in (resultSource plan-detail) when that message was too terse. To act on a plan, resume the sessionId rather than forwarding detail: the plan lives in the agent's session."
73
+ ),
58
74
  todos: z.array(z.object({
59
75
  id: z.string(),
60
76
  content: z.string(),
@@ -66,7 +82,7 @@ const delegateOutputSchema = z.object({
66
82
  "Set when the agent switched itself out of the requested mode mid-session. Absence does not mean the mode was honored — an agent can write while staying in plan."
67
83
  ),
68
84
  writeCapableActivity: z.array(z.object({ kind: z.string(), detail: z.string(), path: z.string().optional() })).optional().describe(
69
- "Write-capable tool calls (edit/delete/move/execute) the agent ran during a plan or ask turn, which are expected to change nothing. Records what ran, not what changed — a shell command is not a change list. Only populated for mode plan and ask."
85
+ "Write-capable tool calls (edit/delete/move/execute) the agent ran during a plan or ask turn, which are expected to change nothing. Records what ran, not what changed — kind is what the tool could do, not proof it wrote: an execute entry may be a read-only command like `ls -la`. Read detail for the evidence and the git diff for the truth. Only populated for mode plan and ask."
70
86
  ),
71
87
  todoProgress: z.object({
72
88
  total: z.number(),
@@ -96,8 +112,8 @@ const doctorOutputSchema = z.object({
96
112
  }).passthrough();
97
113
 
98
114
  export const delegateInputSchema = z.object({
99
- spec: z.string().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."),
100
- 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; modeChanged reports it if it switched."),
115
+ 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."),
116
+ 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; modeChanged reports it if it switched. ask held on every model tested while plan compliance varies by model, so prefer ask when you need the stricter read-only instruction."),
101
117
  resumeSessionId: z.string().optional().describe("Resume an existing ACP session instead of a new one"),
102
118
  workspace: z.string().optional().describe("Working directory for the agent (defaults to cwd). Must be an existing directory; the call fails rather than creating it."),
103
119
  model: z.string().trim().min(1, "model must be a non-empty string").default(DEFAULT_MODEL),
@@ -107,6 +123,7 @@ export const delegateInputSchema = z.object({
107
123
  reasoning: z.string().trim().min(1).optional().describe("Reasoning effort. Not offered by every model; gpt-5.x accepts none, low, medium, high, extra-high."),
108
124
  context: z.string().trim().min(1).optional().describe("Context window size. Not offered by every model; gpt-5.x accepts 272k and 1m."),
109
125
  contextFiles: z.array(z.string()).optional().describe("Paths to attach instead of pasting file contents into spec. Text files are passed as references the agent may open; images (png, jpg, gif, webp, under 5MB) are sent inline. Relative paths resolve against workspace, and paths outside it are allowed — attach only files the agent should read. Anything skipped is reported in protocolWarnings, never fatal."),
126
+ maxResultChars: z.number().int().positive().optional().describe("Cap the returned result to this many characters. A longer result is truncated with a marker and a protocolWarning, so a runaway agent reply cannot blow up your context; the truncation is never reported as a complete answer."),
110
127
  });
111
128
 
112
129
  // A cursor/ask_question question is multi-select when it sets allowMultiple, and the answer
@@ -124,8 +141,8 @@ function matchOptions(choice, opts = [], allowMultiple = false) {
124
141
  return ids;
125
142
  }
126
143
 
127
- export async function runDelegateTool({ args, extra, server, runDelegate, inFlight }) {
128
- const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context, contextFiles } = args;
144
+ export async function runDelegateTool({ args, extra, server, runDelegate, inFlight, seenSessions = new Set() }) {
145
+ const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context, contextFiles, maxResultChars } = args;
129
146
 
130
147
  const progressToken = extra?._meta?.progressToken;
131
148
  let onProgress = () => {};
@@ -205,6 +222,7 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
205
222
  reasoning,
206
223
  context,
207
224
  contextFiles,
225
+ maxResultChars,
208
226
  onElicit,
209
227
  onProgress,
210
228
  signal: extra?.signal,
@@ -212,6 +230,12 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
212
230
  capturedSessionId = sessionId;
213
231
  handle = { client, cancelRequested: false };
214
232
  inFlight.set(sessionId, handle);
233
+ rememberSession(seenSessions, sessionId);
234
+ // Emit the id the moment the session opens, before the turn finishes, so a host that
235
+ // can call tools concurrently has something to pass to cancel mid-run — otherwise the
236
+ // id only arrives when delegate returns, by which point there is nothing to cancel.
237
+ // (Hosts that serialize tool calls still cannot cancel in flight; that is a host limit.)
238
+ onProgress(`session ready: ${sessionId}`);
215
239
  },
216
240
  });
217
241
  if (autoAnswered.length) out.autoAnswered = autoAnswered;
@@ -256,19 +280,19 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
256
280
  openWorldHint: true,
257
281
  },
258
282
  },
259
- async (args, extra) => runDelegateTool({ args, extra, server, runDelegate, inFlight })
283
+ async (args, extra) => runDelegateTool({ args, extra, server, runDelegate, inFlight, seenSessions })
260
284
  );
261
285
 
262
286
  server.registerTool(
263
287
  "cancel",
264
288
  {
265
289
  description:
266
- "Best-effort cancel of an in-flight ACP delegation by sessionId. Sends session/cancel; the agent may finish the turn anyway. The delegate result carries cancelRequested: true when the turn was cancelled mid-run. MCP hosts that serialize tool calls cannot run this while delegate is in flight. With force: true, the agent process is killed if the turn is still running after a short grace period.",
290
+ "Best-effort cancel of an in-flight ACP delegation by sessionId. Sends session/cancel; the agent may finish the turn anyway. The delegate result carries cancelRequested: true when the turn was cancelled mid-run. MCP hosts that serialize tool calls cannot run this while delegate is in flight. With force: true, the agent process is killed if the turn is still running after a short grace period. Returns not-running for a session whose turn already ended (it is still resumable), and not-found for an id never seen this process.",
267
291
  inputSchema: {
268
292
  sessionId: z.string(),
269
293
  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"),
270
294
  },
271
- outputSchema: z.object({ status: z.enum(["cancelled", "killed", "not-found"]), sessionId: z.string() }),
295
+ outputSchema: z.object({ status: z.enum(["cancelled", "killed", "not-running", "not-found"]), sessionId: z.string() }),
272
296
  annotations: {
273
297
  title: "Cancel Cursor delegation",
274
298
  readOnlyHint: false,
@@ -280,9 +304,14 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
280
304
  async ({ sessionId, force }) => {
281
305
  const handle = inFlight.get(sessionId);
282
306
  if (!handle) {
307
+ // A finished session and a garbage id used to look identical (both not-found), which
308
+ // read as "bad id" for a session that in fact ran and is still resumable. Split them.
309
+ const known = seenSessions.has(sessionId);
283
310
  return {
284
- content: [{ type: "text", text: `no in-flight session ${sessionId}` }],
285
- structuredContent: { status: "not-found", sessionId },
311
+ content: [{ type: "text", text: known
312
+ ? `session ${sessionId} is not running; its turn already ended (still resumable via resumeSessionId)`
313
+ : `no in-flight session ${sessionId}` }],
314
+ structuredContent: { status: known ? "not-running" : "not-found", sessionId },
286
315
  };
287
316
  }
288
317
  handle.cancelRequested = true;
package/src/version.js CHANGED
@@ -2,6 +2,24 @@ import { readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
 
5
- export const VERSION = JSON.parse(
6
- readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8")
7
- ).version;
5
+ const PKG_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json");
6
+
7
+ function readVersion() {
8
+ return JSON.parse(readFileSync(PKG_PATH, "utf8")).version;
9
+ }
10
+
11
+ // Captured once, for the ACP/MCP identity handshake that is sent at connect and never re-read.
12
+ export const VERSION = readVersion();
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.
19
+ export function readPackageVersion() {
20
+ try {
21
+ return readVersion();
22
+ } catch {
23
+ return VERSION;
24
+ }
25
+ }