cursor-delegate-mcp 3.1.0 → 3.2.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.
@@ -6,32 +6,24 @@ export class SessionSupervisor {
6
6
  constructor(client, {
7
7
  handshakeMs = 60000,
8
8
  hardCapMs = DEFAULT_HARD_CAP_MS,
9
- idleMs = 0,
10
9
  } = {}) {
11
10
  this.client = client;
12
11
  this.handshakeMs = handshakeMs;
13
12
  this.hardCapMs = hardCapMs;
14
- // Idle detection is opt-in: cursor-agent sends no frames while a shell command runs (26.9s of
15
- // silence measured for a healthy 20s command).
16
- this.idleMs = idleMs > 0 ? idleMs : 0;
17
13
  this.sessionId = null;
18
14
  this.lastActivityAt = Date.now();
19
- this._idleTimer = null;
20
15
  this._handshakeTimer = null;
21
16
  this._hardCapTimer = null;
22
17
  this._armed = false;
23
18
  this._settled = false;
24
19
  this._promptStarted = false;
25
20
  this._guardReject = null;
26
- this._onActivity = () => {
27
- this.lastActivityAt = Date.now();
28
- this._resetIdle();
29
- };
21
+ this._onActivity = () => { this.lastActivityAt = Date.now(); };
30
22
  this._onSetupCancel = () => this._trip("cancelled-in-setup", "cancelled before the prompt was sent");
31
23
  this._onExit = (info) => {
32
24
  this._trip(
33
25
  "agent-exit",
34
- // Kept whole, for the reason acp-client.js states where it builds the same message.
26
+ // stderr kept whole, as in acp-client.js.
35
27
  `agent exited (code=${info.code}${info.signal ? ", signal=" + info.signal : ""})${info.stderr ? ": " + String(info.stderr) : ""}`
36
28
  );
37
29
  };
@@ -41,6 +33,7 @@ export class SessionSupervisor {
41
33
  this.sessionId = sessionId;
42
34
  }
43
35
 
36
+ // True once decided (a trip or the work's end); work still running after a trip reads it to stop.
44
37
  get settled() {
45
38
  return this._settled;
46
39
  }
@@ -63,14 +56,12 @@ export class SessionSupervisor {
63
56
  }, this.handshakeMs);
64
57
  }
65
58
 
66
- // Silence in the request/response handshake means a wedged agent; once the prompt is in flight
67
- // it does not, so the deadline comes off.
59
+ // Silence in the request/response handshake means a wedged agent; during the prompt it does not.
68
60
  promptStarted() {
69
61
  if (this._promptStarted) return;
70
62
  this._promptStarted = true;
71
63
  clearTimeout(this._handshakeTimer);
72
64
  this._handshakeTimer = null;
73
- this._resetIdle();
74
65
  }
75
66
 
76
67
  disarm() {
@@ -79,23 +70,12 @@ export class SessionSupervisor {
79
70
  this.client.off("activity", this._onActivity);
80
71
  this.client.off("exit", this._onExit);
81
72
  this.client.off("cancelled-in-setup", this._onSetupCancel);
82
- clearTimeout(this._idleTimer);
83
73
  clearTimeout(this._handshakeTimer);
84
74
  clearTimeout(this._hardCapTimer);
85
- this._idleTimer = null;
86
75
  this._handshakeTimer = null;
87
76
  this._hardCapTimer = null;
88
77
  }
89
78
 
90
- _resetIdle() {
91
- clearTimeout(this._idleTimer);
92
- this._idleTimer = null;
93
- if (!this.idleMs || !this._promptStarted || !this._armed || this._settled) return;
94
- this._idleTimer = setTimeout(() => {
95
- this._trip("idle-timeout", `Session idle timeout after ${this.idleMs}ms`);
96
- }, this.idleMs);
97
- }
98
-
99
79
  abort() {
100
80
  this._trip("aborted", "delegation aborted by MCP host.");
101
81
  }
@@ -105,10 +85,10 @@ export class SessionSupervisor {
105
85
  this._settled = true;
106
86
  this.disarm();
107
87
  const err = makeError(reason, message);
108
- if (reason === "idle-timeout" || reason === "handshake-timeout" || reason === "hard-cap" || reason === "aborted") {
88
+ if (reason === "handshake-timeout" || reason === "hard-cap" || reason === "aborted") {
109
89
  if (this.sessionId) { try { this.client.cancel(this.sessionId); } catch {} }
110
90
  }
111
- // Ended whether or not a session opened, so setup orphaned by this trip sends nothing more.
91
+ // Closed whether or not a session opened, so setup orphaned by this trip cannot still prompt.
112
92
  try { this.client.endTurn?.(); } catch {}
113
93
  this._guardReject?.(err);
114
94
  }
@@ -0,0 +1,27 @@
1
+ import process from "node:process";
2
+
3
+ /**
4
+ * Runs stopAll once, then exits, on any way the host has of going away: SIGINT, SIGTERM, SIGHUP,
5
+ * stdin EOF, or the returned function. A later trigger waits for the same stop, so a host that
6
+ * follows SIGINT with SIGTERM does not cut the kills short. Every stop is bounded.
7
+ * @param {() => Promise<unknown>} stopAll
8
+ * @param {{ exit?: (code: number) => void, stdin?: NodeJS.EventEmitter }} [opts]
9
+ * @returns {() => void}
10
+ */
11
+ export function installSignalCleanup(stopAll, { exit = (code) => process.exit(code), stdin = process.stdin } = {}) {
12
+ let stopping = false;
13
+ /** @param {number} code */
14
+ const shutdown = (code) => {
15
+ if (stopping) return;
16
+ stopping = true;
17
+ // Waits for the kills: on Windows taskkill is a separate process, and exiting first leaves the
18
+ // agent running (measured).
19
+ Promise.resolve().then(stopAll).catch(() => {}).finally(() => exit(code));
20
+ };
21
+ // Replaces Node's default exit on a signal, which on POSIX never reaches agents in groups of their own.
22
+ for (const [signal, code] of /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]])) {
23
+ process.on(signal, () => shutdown(code));
24
+ }
25
+ stdin.on("end", () => shutdown(0));
26
+ return () => shutdown(0);
27
+ }
package/src/tasks.js CHANGED
@@ -6,7 +6,6 @@ import { CLIENT_CAPABILITIES_META_KEY, MissingRequiredClientCapabilityError, Pro
6
6
  export const TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
7
7
 
8
8
  const RETAIN_MS = 60 * 60 * 1000;
9
- const MAX_FINISHED = 100;
10
9
  const FAST_POLL_MS = 3000;
11
10
  const SLOW_POLL_MS = 10000;
12
11
  const FAST_POLL_FOR_MS = 60 * 1000;
@@ -25,30 +24,24 @@ export function listsTasks(ctx) {
25
24
  * }} Task
26
25
  */
27
26
 
28
- /** @param {{ now?: () => number, retainMs?: number, maxFinished?: number }} [opts] */
29
- export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinished = MAX_FINISHED } = {}) {
27
+ /** @param {{ now?: () => number, retainMs?: number }} [opts] */
28
+ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS } = {}) {
30
29
  /** @type {Map<string, Task>} */
31
30
  const tasks = new Map();
31
+ // A dropped task's session, so its id still resumes it: the host shows the model only the task id.
32
+ /** @type {Map<string, string>} */
33
+ const sessions = new Map();
32
34
  // A running task is never dropped: its id is the host's only handle on the run.
33
35
  const prune = () => {
34
36
  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
- // A fact that changes what to do after a cancel, such as an agent the stop did not see exit.
42
- /** @param {Task} task @param {string} text */
43
- const note = (task, text) => {
44
- if (task.status !== "cancelled") return;
45
- const base = task.statusMessage ?? "cancelled";
46
- task.statusMessage = `${base}${base.endsWith(".") ? "" : "."} Note: ${text}`;
47
- task.lastUpdatedAt = now();
37
+ for (const task of tasks.values()) {
38
+ if (task.endedAt === undefined || t - task.endedAt <= retainMs) continue;
39
+ tasks.delete(task.taskId);
40
+ if (task.sessionId) sessions.set(task.taskId, task.sessionId);
41
+ }
48
42
  };
49
43
  return {
50
44
  now,
51
- note,
52
45
  /** @returns {Task} */
53
46
  create() {
54
47
  const t = now();
@@ -58,18 +51,28 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinis
58
51
  add(task) { prune(); tasks.set(task.taskId, task); },
59
52
  /** @param {string} taskId */
60
53
  get(taskId) { prune(); return tasks.get(taskId); },
54
+ /** @param {string | undefined} taskId */
55
+ sessionOf(taskId) {
56
+ if (taskId === undefined) return undefined;
57
+ prune();
58
+ return tasks.get(taskId)?.sessionId ?? sessions.get(taskId);
59
+ },
61
60
  // A cancelled task keeps its own status message: the run's error names the abort, a reason no
62
61
  // blocking call returns.
63
62
  /** @param {Task} task @param {{ result?: any, error?: any }} outcome */
64
63
  finish(task, outcome) {
65
64
  if (task.status === "working") {
66
65
  task.endedAt = task.lastUpdatedAt = now();
66
+ // The last progress line is stale once the run is over; a failure says why instead.
67
67
  if ("error" in outcome) {
68
68
  task.status = "failed";
69
69
  task.error = { code: ProtocolErrorCode.InternalError, message: String(outcome.error?.message ?? outcome.error) };
70
+ task.statusMessage = task.error.message;
70
71
  } else {
71
72
  task.status = "completed";
72
- task.result = outcome.result;
73
+ // The tools/call result a 2026-07-28 host would have read, marked as one.
74
+ task.result = { ...outcome.result, resultType: "complete" };
75
+ task.statusMessage = undefined;
73
76
  }
74
77
  }
75
78
  prune();
@@ -79,8 +82,9 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinis
79
82
  cancel(task) {
80
83
  if (task.status !== "working" || task.turnEnded) return;
81
84
  task.status = "cancelled";
82
- task.statusMessage = task.sessionId ? `cancelled; resume with resumeSessionId ${task.sessionId}` : "cancelled";
83
- if (task.resumeNote) note(task, task.resumeNote);
85
+ const resume = task.sessionId ? `cancelled; resume with resumeSessionId ${task.sessionId}` : "cancelled";
86
+ // A resume that fell back changes what to do next, so it stays on the cancelled task.
87
+ task.statusMessage = task.resumeNote ? `${resume}. Note: ${task.resumeNote}` : resume;
84
88
  task.endedAt = task.lastUpdatedAt = now();
85
89
  task.ac.abort();
86
90
  },
@@ -108,7 +112,7 @@ export function createTaskStore({ now = Date.now, retainMs = RETAIN_MS, maxFinis
108
112
  * Runs a delegation that answers its request with a task once the prompt is sent. A run that
109
113
  * settles before then, setup failures included, answers with its result as a blocking call does.
110
114
  * @param {{
111
- * run: (over: { signal: AbortSignal, onProgress: (m: string) => void, onPromptSent: (id: string, handle?: any, resumeNote?: string) => void, onUnseenExit: (note: string) => void, onTurnEnd: () => void }) => Promise<any>,
115
+ * run: (over: { signal: AbortSignal, onProgress: (m: string) => void, onPromptSent: (id: string, handle?: any, resumeNote?: string) => void, onTurnEnd: () => void }) => Promise<any>,
112
116
  * signal?: AbortSignal, notify?: (message: string) => void, store: ReturnType<typeof createTaskStore>,
113
117
  * }} opts
114
118
  */
@@ -133,7 +137,6 @@ export async function runAsTask({ run, signal, notify = () => {}, store }) {
133
137
  if (!answered) notify(message);
134
138
  },
135
139
  onPromptSent: (sessionId, handle, resumeNote) => { task.sessionId = sessionId; task.handle = handle; task.resumeNote = resumeNote; markSent(); },
136
- onUnseenExit: (note) => store.note(task, note),
137
140
  onTurnEnd: () => { task.turnEnded = true; },
138
141
  }).then((result) => ({ result }), (error) => ({ error }));
139
142
  const first = await Promise.race([sent, outcome]);
@@ -168,8 +171,15 @@ export function registerTaskHandlers(server, store) {
168
171
  server.server.setRequestHandler("tasks/get", { params: TaskParams, result: AnyResult },
169
172
  async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => store.view(find(taskId, ctx)));
170
173
  // A delegation never enters input_required: its questions come back in the result.
174
+ // The SDK lifts inputResponses into ctx before validation, and reads a non-object as an empty map.
171
175
  server.server.setRequestHandler("tasks/update", { params: TaskParams, result: AnyResult },
172
- async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => { find(taskId, ctx); return {}; });
176
+ async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => {
177
+ find(taskId, ctx);
178
+ if (ctx?.mcpReq?.inputResponses === undefined) {
179
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, "tasks/update needs inputResponses");
180
+ }
181
+ return {};
182
+ });
173
183
  server.server.setRequestHandler("tasks/cancel", { params: TaskParams, result: AnyResult },
174
184
  async (/** @type {any} */ { taskId }, /** @type {any} */ ctx) => { store.cancel(find(taskId, ctx)); return {}; });
175
185
  }