cursor-delegate-mcp 1.10.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "1.10.0",
3
+ "version": "1.11.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",
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,
@@ -568,27 +580,54 @@ export async function runDelegate({
568
580
  } else if (!finalMessageAvailable) {
569
581
  protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
570
582
  }
583
+ // A runaway reply comes back whole and can blow the caller's context (104K chars in one
584
+ // test). When the caller sets a ceiling, cut the result to it and say so, so the truncation
585
+ // is never mistaken for a complete answer.
586
+ if (Number.isFinite(maxResultChars) && maxResultChars > 0 && result.length > maxResultChars) {
587
+ const original = result.length;
588
+ result = result.slice(0, maxResultChars) + `\n\n[result truncated at ${maxResultChars} chars]`;
589
+ protocolWarnings.push(
590
+ `result was ${original} chars and exceeded maxResultChars ${maxResultChars}; it was truncated.`
591
+ + " Raise maxResultChars or narrow the task if you need the full output."
592
+ );
593
+ }
571
594
  let stopReason;
572
595
  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");
596
+ if (typeof res.stopReason !== "string") {
597
+ protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
598
+ } else if (res.stopReason !== "end_turn") {
599
+ // end_turn is the near-universal default and carries no signal — it was end_turn on
600
+ // every call across the stress test. Surface a stop reason only when it says something
601
+ // happened: a refusal, a cancel, an output cap. Absence means the ordinary end_turn.
602
+ stopReason = res.stopReason;
603
+ }
575
604
  }
576
605
  const out = {
577
606
  result,
578
607
  resultSource,
579
608
  finalMessageAvailable,
580
- stopReason,
581
609
  sessionId,
582
610
  filesReportedByAgent: normalizeAgentReportedFiles([...touched], workspace),
583
- questionsAsked,
584
611
  resumed: !!resumeSessionId && sessionId === resumeSessionId,
585
612
  };
613
+ if (stopReason !== undefined) out.stopReason = stopReason;
614
+ // Elicitation almost never fires (the agent tends to ask in prose and end the turn), so an
615
+ // always-empty array is steady noise. Report it only when a question actually came through.
616
+ if (questionsAsked.length) out.questionsAsked = questionsAsked;
586
617
  if (sessionTitle) out.sessionTitle = sessionTitle;
587
618
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
588
619
  for (const id of unsupportedOptions) protocolWarnings.push(`model ${model} has no ${id} option; the requested value was ignored`);
589
620
  protocolWarnings.push(...contextWarnings);
590
621
  if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
591
622
  out.plan = sanitizePlan(protocolWarnings);
623
+ // plan.detail duplicated the prose already in result on every observed plan turn — the
624
+ // same plan in two forms, ~2x the context for one answer. Drop it when result is at least
625
+ // as long (result is carrying the plan), but keep it when result is too terse to be the
626
+ // plan itself, so a plan that lived only in the detail is never lost. entries and overview
627
+ // are structured and unique, and always stay.
628
+ if (typeof out.plan.detail === "string" && result.length >= out.plan.detail.length) {
629
+ delete out.plan.detail;
630
+ }
592
631
  }
593
632
  // Most successful turns emit no todos at all, so an empty list would read as "nothing
594
633
  // 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
@@ -34,12 +44,16 @@ const delegateOutputSchema = z.object({
34
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."
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."
@@ -96,7 +110,7 @@ const doctorOutputSchema = z.object({
96
110
  }).passthrough();
97
111
 
98
112
  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."),
113
+ 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."),
100
114
  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."),
101
115
  resumeSessionId: z.string().optional().describe("Resume an existing ACP session instead of a new one"),
102
116
  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."),
@@ -107,6 +121,7 @@ export const delegateInputSchema = z.object({
107
121
  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
122
  context: z.string().trim().min(1).optional().describe("Context window size. Not offered by every model; gpt-5.x accepts 272k and 1m."),
109
123
  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."),
124
+ 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
125
  });
111
126
 
112
127
  // A cursor/ask_question question is multi-select when it sets allowMultiple, and the answer
@@ -124,8 +139,8 @@ function matchOptions(choice, opts = [], allowMultiple = false) {
124
139
  return ids;
125
140
  }
126
141
 
127
- export async function runDelegateTool({ args, extra, server, runDelegate, inFlight }) {
128
- const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context, contextFiles } = args;
142
+ export async function runDelegateTool({ args, extra, server, runDelegate, inFlight, seenSessions = new Set() }) {
143
+ const { spec, mode, resumeSessionId, workspace, model, fast, reasoning, context, contextFiles, maxResultChars } = args;
129
144
 
130
145
  const progressToken = extra?._meta?.progressToken;
131
146
  let onProgress = () => {};
@@ -205,6 +220,7 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
205
220
  reasoning,
206
221
  context,
207
222
  contextFiles,
223
+ maxResultChars,
208
224
  onElicit,
209
225
  onProgress,
210
226
  signal: extra?.signal,
@@ -212,6 +228,12 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
212
228
  capturedSessionId = sessionId;
213
229
  handle = { client, cancelRequested: false };
214
230
  inFlight.set(sessionId, handle);
231
+ rememberSession(seenSessions, sessionId);
232
+ // Emit the id the moment the session opens, before the turn finishes, so a host that
233
+ // can call tools concurrently has something to pass to cancel mid-run — otherwise the
234
+ // id only arrives when delegate returns, by which point there is nothing to cancel.
235
+ // (Hosts that serialize tool calls still cannot cancel in flight; that is a host limit.)
236
+ onProgress(`session ready: ${sessionId}`);
215
237
  },
216
238
  });
217
239
  if (autoAnswered.length) out.autoAnswered = autoAnswered;
@@ -256,19 +278,19 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
256
278
  openWorldHint: true,
257
279
  },
258
280
  },
259
- async (args, extra) => runDelegateTool({ args, extra, server, runDelegate, inFlight })
281
+ async (args, extra) => runDelegateTool({ args, extra, server, runDelegate, inFlight, seenSessions })
260
282
  );
261
283
 
262
284
  server.registerTool(
263
285
  "cancel",
264
286
  {
265
287
  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.",
288
+ "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
289
  inputSchema: {
268
290
  sessionId: z.string(),
269
291
  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
292
  },
271
- outputSchema: z.object({ status: z.enum(["cancelled", "killed", "not-found"]), sessionId: z.string() }),
293
+ outputSchema: z.object({ status: z.enum(["cancelled", "killed", "not-running", "not-found"]), sessionId: z.string() }),
272
294
  annotations: {
273
295
  title: "Cancel Cursor delegation",
274
296
  readOnlyHint: false,
@@ -280,9 +302,14 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
280
302
  async ({ sessionId, force }) => {
281
303
  const handle = inFlight.get(sessionId);
282
304
  if (!handle) {
305
+ // A finished session and a garbage id used to look identical (both not-found), which
306
+ // read as "bad id" for a session that in fact ran and is still resumable. Split them.
307
+ const known = seenSessions.has(sessionId);
283
308
  return {
284
- content: [{ type: "text", text: `no in-flight session ${sessionId}` }],
285
- structuredContent: { status: "not-found", sessionId },
309
+ content: [{ type: "text", text: known
310
+ ? `session ${sessionId} is not running; its turn already ended (still resumable via resumeSessionId)`
311
+ : `no in-flight session ${sessionId}` }],
312
+ structuredContent: { status: known ? "not-running" : "not-found", sessionId },
286
313
  };
287
314
  }
288
315
  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
+ }