cursor-delegate-mcp 1.3.0 → 1.5.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/PRIVACY.md ADDED
@@ -0,0 +1,11 @@
1
+ # Privacy
2
+
3
+ Cursor Delegate MCP runs as a local stdio MCP server. The project author does not operate a backend for the plugin and does not receive your code, prompts, workspace contents, session identifiers, diagnostics, or usage telemetry.
4
+
5
+ Claude Code installs run the server bundled in the plugin cache. On first session, the plugin may run `npm install --omit=dev` inside that cache to fetch its open-source runtime dependencies; it does not install them into your project. Codex, Copilot, VS Code, and standalone MCP configurations start the published package through `npx`, so npm may apply its own registry logging under npm's policies.
6
+
7
+ When you delegate, the local server starts `cursor-agent`. Task prompts, selected workspace content, model requests, and Cursor account usage are handled by Cursor under [Cursor's terms and privacy policy](https://cursor.com/terms). Your MCP host may separately process the prompt and tool results under its own terms.
8
+
9
+ The MCP response can contain file paths, agent output, plan text, diagnostic information, and session identifiers. Review that output before sharing logs or bug reports. The plugin does not redact secrets found in prompts, files, agent output, or diagnostics.
10
+
11
+ For security issues, see [SECURITY.md](SECURITY.md) or open a [GitHub Security Advisory](https://github.com/andreilungeanu/cursor-delegate-mcp/security/advisories/new).
package/README.md CHANGED
@@ -1,53 +1,57 @@
1
1
  # Cursor Delegate MCP
2
2
 
3
- **Let Claude think. Let Cursor build.**
3
+ **Stop rationing your smartest model.**
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/cursor-delegate-mcp)](https://www.npmjs.com/package/cursor-delegate-mcp)
6
6
  [![npm downloads](https://img.shields.io/npm/dt/cursor-delegate-mcp)](https://www.npmjs.com/package/cursor-delegate-mcp)
7
7
  [![node](https://img.shields.io/node/v/cursor-delegate-mcp)](https://nodejs.org)
8
8
  [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
9
9
 
10
- An MCP server that lets Claude Code (or any MCP client) delegate coding tasks to **Cursor's CLI agent** — and get structured results back, not a wall of terminal text.
10
+ <img src="assets/logo-light.png" alt="Cursor Delegate MCP logo" width="150" align="left" hspace="15">
11
+
12
+ You know the drill: **Fable**, **Sol**, or **Opus** starts grinding through a refactor, and you watch your subscription's 5-hour window melt — or your API bill climb. Here's the thing: most of what burns your quota isn't intelligence work. It's typing.
13
+
14
+ Cursor Delegate is an MCP bridge that lets Claude Code, ChatGPT/Codex, Copilot — or any MCP client — keep the thinking and hand the typing to **Cursor's CLI agent**.
15
+
16
+ <br clear="left">
11
17
 
12
18
  ![Demo](demo.gif)
13
19
 
14
- ## Why
20
+ ## 🧠 Frontier quality, kept
21
+
22
+ Your assistant does what frontier models are actually for: understands the task, writes a precise brief, reviews the finished diff. And **Composer 2.5** holds its own — a seriously capable coding model, just guided and checked by a smarter one. The result reads like frontier work, because a frontier model planned it and signed off on it.
23
+
24
+ ## ⚡ Done faster
15
25
 
16
- Frontier models like **Opus** and **Fable** are brilliant orchestrators — great at understanding intent, planning, and reviewing. Cursor's **Composer** is a fast, cheap workhorse for the actual edits, with its own generous usage pool.
26
+ Composer 2.5 is built for speed. It tears through multi-file edits while a frontier model would still be streaming the first file. You delegate, keep working with your assistant, and the diff shows up done.
17
27
 
18
- This bridge pairs them: the big brain writes the brief and reviews the diff; Cursor does the typing. Your Claude quota goes to thinking, not boilerplate.
28
+ ## 🔋 Your limits stop being the bottleneck
19
29
 
20
- ## How it works
30
+ Delegated work bills to Composer's **own usage pool** — separate from Cursor's API-priced main quota, and so generous most users never hit its ceiling. Your Claude or Codex subscription spends tokens only on the brief and the review, so the 5-hour window and weekly limits go a lot further. On API? That's the per-token grind moved off your bill.
21
31
 
22
32
  ```
23
- You → Claude (Opus / Fable — plans & reviews)
33
+ You → your agent (plans & reviews)
24
34
  │ MCP delegate tool
25
35
  ▼
26
36
  cursor-agent (Composer 2.5 — implements)
27
37
  │ edits your workspace
28
38
  ▼
29
- Structured result: files changed, session id, plan
39
+ Clean result: what changed, which files, the plan
30
40
  ```
31
41
 
32
- Delegation defaults to Cursor's **Composer 2.5**, which draws from the separate **Auto + Composer** usage pool — so implementation work doesn't eat into your API-model quota. Want a different model? Just say so: *"delegate with Opus"*.
33
-
34
- **Three modes:** `agent` (implement, default) · `plan` (draft a plan, review, resume to implement) · `ask` (read-only Q&A).
35
-
36
- > **Note:** delegation auto-approves file writes in the target workspace — review the diff afterward, like any teammate's work.
37
-
38
42
  ## Features
39
43
 
40
- - 🤝 **Perfect Claude Code integration** — ships as a plugin with a skill, slash command, and hooks. Just say *"delegate this to Cursor"* and it happens.
41
- - 💬 **Answers Cursor's questions** — when Cursor needs a clarification mid-run, the question surfaces in your client's normal prompt. No stalled sessions.
42
- - 📦 **Structured results** — session id, files changed, stop reason, and plan payload. Claude knows exactly what happened and what to review.
43
- - 📋 **Plan mode** — have Cursor draft a plan first, review it, then resume the same session to implement.
44
- - 🔍 **Ask mode** — read-only Q&A over the codebase, zero file changes.
45
- - 🩺 **Built-in diagnostics** — a `doctor` tool that tells you exactly what's missing if setup isn't right.
46
- - 🔌 **Works everywhere MCP does** — Claude Code, VS Code, Codex CLI, Kiro, Kilo Code, and more.
44
+ - 🤝 **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.
45
+ - 💬 **No stalled runs** — if Cursor asks a question mid-task, it pops up as a normal prompt in your client. In clients without that support, the recommended option is picked automatically and reported back, so nothing hangs.
46
+ - 📦 **Clean, typed results** — final answer, changed files, session id, and the plan, returned as validated structured output. Nothing to parse, nothing to guess.
47
+ - 📋 **Plan first** — `plan` mode: Cursor drafts a plan, you review it, then the same session implements it.
48
+ - 🔍 **Ask anything** — `ask` mode: read-only Q&A over your codebase, zero file changes.
49
+ - 🩺 **Self-diagnosing** — a `doctor` tool that tells you exactly what's missing if setup isn't right.
50
+ - 🔌 **Works everywhere MCP does** — VS Code, JetBrains, Windsurf, Visual Studio, and more.
47
51
 
48
52
  ## Quick start
49
53
 
50
- **Requirements:** [Node.js 22+](https://nodejs.org/) and [cursor-agent](https://cursor.com/docs/cli/overview) logged in (`cursor-agent login`).
54
+ You need [Node.js 22+](https://nodejs.org/) and the [Cursor CLI](https://cursor.com/docs/cli/overview), logged in (`cursor-agent login`).
51
55
 
52
56
  ### Claude Code (recommended)
53
57
 
@@ -60,8 +64,22 @@ Then just ask:
60
64
 
61
65
  > Delegate to Cursor: migrate src/api from callbacks to async/await and update the tests, then walk me through what changed.
62
66
 
63
- Claude writes the brief, Cursor grinds through the files, and Claude reviews the diff with you — that's the whole loop.
67
+ That's the whole loop — Claude writes the brief, Cursor grinds through the files, Claude walks you through the diff. Claude Code runs the server bundled with the plugin; dependencies install automatically on first session.
68
+
69
+ ### ChatGPT desktop / Codex
64
70
 
71
+ ```shell
72
+ codex plugin marketplace add andreilungeanu/cursor-delegate-mcp
73
+ codex plugin add cursor-delegate-mcp@cursor-delegate-mcp
74
+ ```
75
+
76
+ ### GitHub Copilot CLI
77
+
78
+ ```shell
79
+ copilot plugin install andreilungeanu/cursor-delegate-mcp
80
+ ```
81
+
82
+ Both plugins bundle the delegation skill and start the published npm release via `npx` — nothing else to set up.
65
83
 
66
84
  ### Any other MCP client
67
85
 
@@ -91,21 +109,19 @@ Claude writes the brief, Cursor grinds through the files, and Claude reviews the
91
109
  }
92
110
  ```
93
111
 
112
+ Or run **Chat: Install Plugin From Source** with this repository's URL.
113
+
94
114
  </details>
95
115
 
96
116
  <details>
97
- <summary><strong>Codex CLI</strong> — <code>~/.codex/config.toml</code></summary>
117
+ <summary><strong>JetBrains AI Assistant</strong> — Settings → Tools → AI Assistant → MCP</summary>
98
118
 
99
- ```toml
100
- [mcp_servers.cursor-delegate-mcp]
101
- command = "npx"
102
- args = ["-y", "cursor-delegate-mcp"]
103
- ```
119
+ Import the standard definition above via **Settings → Tools → AI Assistant → Model Context Protocol (MCP)**.
104
120
 
105
121
  </details>
106
122
 
107
123
  <details>
108
- <summary><strong>Kiro</strong> — <code>~/.kiro/settings/mcp.json</code></summary>
124
+ <summary><strong>Windsurf</strong> — <code>~/.codeium/windsurf/mcp_config.json</code></summary>
109
125
 
110
126
  ```json
111
127
  {
@@ -118,43 +134,40 @@ args = ["-y", "cursor-delegate-mcp"]
118
134
  }
119
135
  ```
120
136
 
137
+ Heads-up: Cascade caps you at 100 tools across all servers.
138
+
121
139
  </details>
122
140
 
123
141
  <details>
124
- <summary><strong>Kilo Code</strong> — <code>~/.config/kilo/kilo.jsonc</code></summary>
142
+ <summary><strong>Visual Studio 2022</strong> — <code>%USERPROFILE%\.mcp.json</code></summary>
125
143
 
126
- ```jsonc
144
+ ```json
127
145
  {
128
- "mcp": {
146
+ "servers": {
129
147
  "cursor-delegate-mcp": {
130
- "type": "local",
131
- "command": ["npx", "-y", "cursor-delegate-mcp"],
132
- "enabled": true
148
+ "type": "stdio",
149
+ "command": "npx",
150
+ "args": ["-y", "cursor-delegate-mcp"]
133
151
  }
134
152
  }
135
153
  }
136
154
  ```
137
155
 
156
+ Requires 17.14+. Note the top-level key is `servers`, not `mcpServers`.
157
+
138
158
  </details>
139
159
 
140
160
  <details>
141
- <summary><strong>Antigravity 2.0</strong> — <code>~/.gemini/config/mcp_config.json</code></summary>
161
+ <summary><strong>Kiro, Kilo Code, Zed, and friends</strong></summary>
142
162
 
143
- ```json
144
- {
145
- "mcpServers": {
146
- "cursor-delegate-mcp": {
147
- "command": "npx",
148
- "args": ["-y", "cursor-delegate-mcp"]
149
- }
150
- }
151
- }
152
- ```
163
+ Any MCP client works — drop the standard `npx` definition above into the client's MCP config.
153
164
 
154
165
  </details>
155
166
 
156
- Call the **`delegate`** tool with your task; run **`doctor`** if anything seems off.
167
+ Give the **`delegate`** tool a task. If anything seems off, run **`doctor`**.
157
168
 
158
169
  ## License
159
170
 
160
171
  MIT © [Andrei Lungeanu](https://github.com/andreilungeanu)
172
+
173
+ <sub>[Security](SECURITY.md) · [Privacy](PRIVACY.md) · [Terms](TERMS.md) · [Changelog](CHANGELOG.md)</sub>
package/SECURITY.md ADDED
@@ -0,0 +1,26 @@
1
+ # Security
2
+
3
+ ## What this plugin does
4
+
5
+ `cursor-delegate-mcp` spawns **cursor-agent** in your workspace and **auto-approves file
6
+ write and permission requests** over ACP (`allow-always`). Delegated tasks can modify,
7
+ create, or delete files under the chosen `workspace` directory.
8
+
9
+ Treat every `delegate` call like handing an engineer write access to that tree.
10
+
11
+ ## Recommendations
12
+
13
+ - Point `workspace` at the smallest directory that contains the task (not `$HOME` or `/`).
14
+ - Review `touchedFiles` and the git diff before committing.
15
+ - Use `mode: "plan"` when you only want a plan, not file changes.
16
+ - Run verification (tests, lint) after delegation — the delegate skill asks Claude to do
17
+ this, but automated gates in CI are still your backstop.
18
+ - Do not commit secrets (`.env`, credentials, tokens). The bridge does not redact them from
19
+ agent context.
20
+
21
+ ## Reporting vulnerabilities
22
+
23
+ If you find a security issue in this bridge (not in cursor-agent or an MCP host),
24
+ please open a [GitHub Security Advisory](https://github.com/andreilungeanu/cursor-delegate-mcp/security/advisories/new)
25
+ or email the maintainer listed in `package.json` instead of filing a public issue with
26
+ exploit details.
package/TERMS.md ADDED
@@ -0,0 +1,9 @@
1
+ # Terms of Use
2
+
3
+ Cursor Delegate MCP is provided under the MIT License on an "as is" basis, without warranties or guarantees.
4
+
5
+ The plugin runs locally and starts `cursor-agent` with access to the workspace selected for a delegation. Delegated agent-mode tasks may create, modify, or delete files. You are responsible for choosing an appropriate workspace, reviewing changes, protecting credentials, and complying with the terms that apply to Cursor, your MCP host, and any model you select.
6
+
7
+ The project author does not operate the Cursor service, receive delegated source code, or control the behavior of third-party models and clients. Do not use the plugin for unlawful activity or in a way that violates third-party rights or service terms.
8
+
9
+ For support, open a [GitHub issue](https://github.com/andreilungeanu/cursor-delegate-mcp/issues). For security reports, follow [SECURITY.md](SECURITY.md).
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "cursor-delegate-mcp",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
- "description": "MCP server bridging Claude Code to cursor-agent over the Agent Client Protocol (ACP).",
5
+ "description": "MCP server bridging AI coding hosts to cursor-agent over the Agent Client Protocol (ACP).",
6
6
  "license": "MIT",
7
7
  "author": "Andrei Lungeanu <andrei@lungeanu.ro>",
8
8
  "repository": {
@@ -20,6 +20,10 @@
20
20
  "acp",
21
21
  "agent-client-protocol",
22
22
  "claude-code",
23
+ "codex",
24
+ "chatgpt",
25
+ "github-copilot",
26
+ "vscode",
23
27
  "composer"
24
28
  ],
25
29
  "main": "src/server.js",
@@ -32,14 +36,18 @@
32
36
  "files": [
33
37
  "src",
34
38
  "README.md",
39
+ "PRIVACY.md",
40
+ "SECURITY.md",
41
+ "TERMS.md",
35
42
  "LICENSE"
36
43
  ],
37
44
  "scripts": {
38
45
  "test": "node --test test/*.test.js",
46
+ "test:pack": "node scripts/packed-smoke.mjs",
39
47
  "start": "node src/server.js"
40
48
  },
41
49
  "dependencies": {
42
- "@modelcontextprotocol/sdk": "^1.12.0",
50
+ "@modelcontextprotocol/sdk": "^1.22.0",
43
51
  "zod": "^3.23.8"
44
52
  }
45
53
  }
package/src/delegate.js CHANGED
@@ -44,7 +44,7 @@ export async function runDelegate({
44
44
  const recordQuestions = (q) => {
45
45
  if (q.kind !== "ask_question") return;
46
46
  for (const question of q.questions || []) {
47
- if (question?.prompt) questionsAsked.push(question.prompt);
47
+ if (typeof question?.prompt === "string" && question.prompt) questionsAsked.push(question.prompt);
48
48
  }
49
49
  };
50
50
  const wrappedElicit = onElicit
@@ -59,15 +59,102 @@ export async function runDelegate({
59
59
  if (body?.plan !== undefined) planDetail = body.plan;
60
60
  };
61
61
 
62
+ // ACP requires plan entry content to be a string and bounds priority/status to
63
+ // known values. Frames that violate that must not fail the MCP call after the
64
+ // work is done — drop the bad data and report it as a protocol diagnostic.
65
+ const PLAN_PRIORITIES = ["high", "medium", "low"];
66
+ const PLAN_STATUSES = ["pending", "in_progress", "completed"];
67
+ const sanitizePlan = (warnings) => {
68
+ const entries = [];
69
+ planEntries.forEach((raw, i) => {
70
+ if (typeof raw?.content !== "string") {
71
+ warnings.push(`plan entry ${i} dropped: ACP requires string content, got ${raw === null ? "null" : typeof raw?.content}`);
72
+ return;
73
+ }
74
+ const entry = { ...raw };
75
+ if (entry.priority !== undefined && !PLAN_PRIORITIES.includes(entry.priority)) {
76
+ warnings.push(`plan entry ${i}: non-ACP priority ${JSON.stringify(entry.priority)} removed`);
77
+ delete entry.priority;
78
+ }
79
+ if (entry.status !== undefined && !PLAN_STATUSES.includes(entry.status)) {
80
+ warnings.push(`plan entry ${i}: non-ACP status ${JSON.stringify(entry.status)} removed`);
81
+ delete entry.status;
82
+ }
83
+ entries.push(entry);
84
+ });
85
+ const plan = { entries };
86
+ if (planOverview !== undefined) {
87
+ if (typeof planOverview === "string") plan.overview = planOverview;
88
+ else warnings.push("plan overview dropped: expected string");
89
+ }
90
+ if (planDetail !== undefined) {
91
+ if (typeof planDetail === "string") plan.detail = planDetail;
92
+ else warnings.push("plan detail dropped: expected string");
93
+ }
94
+ return plan;
95
+ };
96
+
62
97
  const make = clientFactory || ((opts) => new AcpClient(opts));
63
98
  const client = make({ onElicit: wrappedElicit, mode, onCreatePlan: recordCreatePlan });
64
99
  const supervisor = new SessionSupervisor(client, { idleMs, hardCapMs: capMs, cancelGraceMs, killGraceMs });
65
100
 
66
- const textChunks = [];
67
- let textLength = 0;
101
+ const resultChunks = [];
102
+ let resultLength = 0;
68
103
  let truncated = false;
104
+ let sawToolCall = false;
105
+ let collectingPostToolResult = false;
106
+ const activeToolCalls = new Set();
69
107
  const touched = new Set();
70
108
 
109
+ const resetResult = () => {
110
+ resultChunks.length = 0;
111
+ resultLength = 0;
112
+ truncated = false;
113
+ };
114
+ const appendResult = (text) => {
115
+ if (truncated) return;
116
+ const remaining = MAX_OUTPUT - resultLength;
117
+ if (text.length <= remaining) {
118
+ resultChunks.push(text);
119
+ resultLength += text.length;
120
+ } else if (remaining > 0) {
121
+ resultChunks.push(text.slice(0, remaining));
122
+ resultLength += remaining;
123
+ truncated = true;
124
+ } else {
125
+ truncated = true;
126
+ }
127
+ };
128
+ const isTerminalToolStatus = (status) =>
129
+ status === "completed" || status === "failed" || status === "cancelled";
130
+ const startTool = (toolCallId, status) => {
131
+ sawToolCall = true;
132
+ collectingPostToolResult = false;
133
+ resetResult();
134
+ if (toolCallId != null && !isTerminalToolStatus(status)) activeToolCalls.add(toolCallId);
135
+ if (isTerminalToolStatus(status) && activeToolCalls.size === 0) collectingPostToolResult = true;
136
+ };
137
+ const updateToolStatus = (toolCallId, status) => {
138
+ if (!status) return;
139
+ if (!sawToolCall) {
140
+ sawToolCall = true;
141
+ resetResult();
142
+ }
143
+ if (isTerminalToolStatus(status)) {
144
+ if (toolCallId != null) activeToolCalls.delete(toolCallId);
145
+ if (activeToolCalls.size === 0 && !collectingPostToolResult) {
146
+ // Discard any message text emitted while tools were still running.
147
+ // A duplicate or late terminal update must not wipe an already-collected final message.
148
+ resetResult();
149
+ collectingPostToolResult = true;
150
+ }
151
+ } else {
152
+ collectingPostToolResult = false;
153
+ resetResult();
154
+ if (toolCallId != null) activeToolCalls.add(toolCallId);
155
+ }
156
+ };
157
+
71
158
  // Each stream reports its newest complete sentence, at most one per throttle window.
72
159
  // Capital-letter boundary: cursor-agent thoughts arrive as sentences with no separator.
73
160
  const SENTENCE_END = /[.!?](?=\s|[A-Z])|\n/;
@@ -109,6 +196,7 @@ export async function runDelegate({
109
196
  thoughtProgress.push(up.content.text);
110
197
  }
111
198
  if (up.sessionUpdate === "tool_call") {
199
+ startTool(up.toolCallId, up.status);
112
200
  const label = up.title || up.kind || "tool";
113
201
  const path = up.locations?.[0]?.path;
114
202
  const line = "running: " + String(label) + (path ? " — " + path : "");
@@ -116,22 +204,11 @@ export async function runDelegate({
116
204
  }
117
205
  if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
118
206
  const text = up.content.text;
119
- if (!truncated) {
120
- const remaining = MAX_OUTPUT - textLength;
121
- if (text.length <= remaining) {
122
- textChunks.push(text);
123
- textLength += text.length;
124
- } else if (remaining > 0) {
125
- textChunks.push(text.slice(0, remaining));
126
- textLength += remaining;
127
- truncated = true;
128
- } else {
129
- truncated = true;
130
- }
131
- }
207
+ if (!sawToolCall || (collectingPostToolResult && activeToolCalls.size === 0)) appendResult(text);
132
208
  messageProgress.push(text);
133
209
  }
134
210
  if (up.sessionUpdate === "tool_call_update") {
211
+ updateToolStatus(up.toolCallId, up.status);
135
212
  for (const c of up.content || []) {
136
213
  if (c.type === "diff" && c.path) {
137
214
  touched.add(c.path);
@@ -154,9 +231,10 @@ export async function runDelegate({
154
231
  await client.setModel(sessionId, model);
155
232
  if (composerFastToggleApplies(model)) await client.setFast(sessionId, fast);
156
233
  await client.setMode(sessionId, mode);
157
- textChunks.length = 0;
158
- textLength = 0;
159
- truncated = false;
234
+ resetResult();
235
+ sawToolCall = false;
236
+ collectingPostToolResult = false;
237
+ activeToolCalls.clear();
160
238
  thoughtProgress.reset();
161
239
  messageProgress.reset();
162
240
  planEntries = [];
@@ -167,13 +245,25 @@ export async function runDelegate({
167
245
  });
168
246
  thoughtProgress.end();
169
247
  messageProgress.end();
170
- let result = textChunks.join("");
248
+ let result = resultChunks.join("");
171
249
  if (truncated) result += TRUNCATION_MARKER;
250
+ const finalMessageAvailable = result.length > 0;
251
+ const resultSource = finalMessageAvailable
252
+ ? (sawToolCall ? "post-tool" : "tool-free-stream")
253
+ : "none";
172
254
  const gitAfter = gitChangedSet(workspace);
173
255
  const touchedResult = computeTouched({ before: gitBefore, after: gitAfter, diffTouched: [...touched], workspace });
256
+ const protocolWarnings = [];
257
+ let stopReason;
258
+ if (res?.stopReason !== undefined) {
259
+ if (typeof res.stopReason === "string") stopReason = res.stopReason;
260
+ else protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
261
+ }
174
262
  const out = {
175
263
  result,
176
- stopReason: res?.stopReason,
264
+ resultSource,
265
+ finalMessageAvailable,
266
+ stopReason,
177
267
  sessionId,
178
268
  touchedFiles: touchedResult.files,
179
269
  touchedFilesSource: touchedResult.source,
@@ -181,8 +271,9 @@ export async function runDelegate({
181
271
  resumed: !!resumeSessionId && sessionId === resumeSessionId,
182
272
  };
183
273
  if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
184
- out.plan = { entries: planEntries, overview: planOverview, detail: planDetail };
274
+ out.plan = sanitizePlan(protocolWarnings);
185
275
  }
276
+ if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
186
277
  return out;
187
278
  } catch (err) {
188
279
  try {
package/src/doctor.js CHANGED
@@ -86,6 +86,13 @@ export async function runDoctor({
86
86
  command: formatCommand(spawnSpec),
87
87
  version: agentProbe.version,
88
88
  },
89
+ runtime: {
90
+ node: process.versions.node,
91
+ platform: process.platform,
92
+ arch: process.arch,
93
+ cwd: process.cwd(),
94
+ transport: "stdio",
95
+ },
89
96
  env: {
90
97
  ACP_LOG_SIZE: process.env.ACP_LOG_SIZE !== undefined ? process.env.ACP_LOG_SIZE : DEFAULT_LOG_SIZE,
91
98
  },
package/src/jsonrpc.js CHANGED
@@ -1,81 +1,81 @@
1
- import readline from "node:readline";
2
-
3
- const FRAME_CAP = 2048;
4
-
5
- export class JsonRpcPeer {
6
- constructor(input, output, { onNotification, onRequest, onActivity } = {}) {
7
- this.output = output;
8
- this.onNotification = onNotification || (() => {});
9
- this.onRequest = onRequest || (() => {});
10
- this.onActivity = onActivity || (() => {});
11
- this.nextId = 1;
12
- this.pending = new Map();
13
- const rawSize = process.env.ACP_LOG_SIZE !== undefined ? Number(process.env.ACP_LOG_SIZE) : 2000;
14
- this._logSize = rawSize > 0 && !Number.isNaN(rawSize) ? rawSize : 0;
15
- this._log = [];
16
- this.rl = readline.createInterface({ input });
17
- this.rl.on("line", (line) => this._onLine(line));
18
- }
19
-
20
- _record(dir, line) {
21
- if (this._logSize <= 0) return;
22
- const truncated = line.length > FRAME_CAP ? line.slice(0, FRAME_CAP) : line;
23
- this._log.push({ t: Date.now(), dir, line: truncated });
24
- if (this._log.length > this._logSize) {
25
- this._log.splice(0, this._log.length - this._logSize);
26
- }
27
- }
28
-
29
- getLog() { return [...this._log]; }
30
-
31
- formatLog(n) {
32
- const entries = n !== undefined ? this._log.slice(-n) : this._log;
33
- return entries.map((e) => `${new Date(e.t).toISOString()} ${e.dir} ${e.line}`).join("\n");
34
- }
35
-
36
- _onLine(line) {
37
- this.onActivity();
38
- this._record("in", line);
39
- if (!line.trim()) return;
40
- let msg;
41
- try { msg = JSON.parse(line); } catch { return; }
42
- const hasId = msg.id !== undefined && msg.id !== null;
43
- if (hasId && (msg.result !== undefined || msg.error !== undefined)) {
44
- const p = this.pending.get(msg.id);
45
- if (p) {
46
- this.pending.delete(msg.id);
47
- if (msg.error) p.reject(new Error(msg.error.message || "rpc error"));
48
- else p.resolve(msg.result);
49
- }
50
- } else if (msg.method && hasId) {
51
- this.onRequest(msg.id, msg.method, msg.params);
52
- } else if (msg.method) {
53
- this.onNotification(msg.method, msg.params);
54
- }
55
- }
56
-
57
- _write(obj) {
58
- const serialized = JSON.stringify(obj) + "\n";
59
- this._record("out", serialized);
60
- this.output.write(serialized);
61
- }
62
-
63
- request(method, params) {
64
- const id = this.nextId++;
65
- return new Promise((resolve, reject) => {
66
- this.pending.set(id, { resolve, reject });
67
- this._write({ jsonrpc: "2.0", id, method, params });
68
- });
69
- }
70
-
71
- notify(method, params) { this._write({ jsonrpc: "2.0", method, params }); }
72
- respond(id, result) { this._write({ jsonrpc: "2.0", id, result }); }
73
- respondError(id, code, message) { this._write({ jsonrpc: "2.0", id, error: { code, message } }); }
74
-
75
- rejectAllPending(err) {
76
- for (const p of this.pending.values()) p.reject(err);
77
- this.pending.clear();
78
- }
79
-
80
- close() { this.rl.close(); }
81
- }
1
+ import readline from "node:readline";
2
+
3
+ const FRAME_CAP = 2048;
4
+
5
+ export class JsonRpcPeer {
6
+ constructor(input, output, { onNotification, onRequest, onActivity } = {}) {
7
+ this.output = output;
8
+ this.onNotification = onNotification || (() => {});
9
+ this.onRequest = onRequest || (() => {});
10
+ this.onActivity = onActivity || (() => {});
11
+ this.nextId = 1;
12
+ this.pending = new Map();
13
+ const rawSize = process.env.ACP_LOG_SIZE !== undefined ? Number(process.env.ACP_LOG_SIZE) : 2000;
14
+ this._logSize = rawSize > 0 && !Number.isNaN(rawSize) ? rawSize : 0;
15
+ this._log = [];
16
+ this.rl = readline.createInterface({ input });
17
+ this.rl.on("line", (line) => this._onLine(line));
18
+ }
19
+
20
+ _record(dir, line) {
21
+ if (this._logSize <= 0) return;
22
+ const truncated = line.length > FRAME_CAP ? line.slice(0, FRAME_CAP) : line;
23
+ this._log.push({ t: Date.now(), dir, line: truncated });
24
+ if (this._log.length > this._logSize) {
25
+ this._log.splice(0, this._log.length - this._logSize);
26
+ }
27
+ }
28
+
29
+ getLog() { return [...this._log]; }
30
+
31
+ formatLog(n) {
32
+ const entries = n !== undefined ? this._log.slice(-n) : this._log;
33
+ return entries.map((e) => `${new Date(e.t).toISOString()} ${e.dir} ${e.line}`).join("\n");
34
+ }
35
+
36
+ _onLine(line) {
37
+ this.onActivity();
38
+ this._record("in", line);
39
+ if (!line.trim()) return;
40
+ let msg;
41
+ try { msg = JSON.parse(line); } catch { return; }
42
+ const hasId = msg.id !== undefined && msg.id !== null;
43
+ if (hasId && (msg.result !== undefined || msg.error !== undefined)) {
44
+ const p = this.pending.get(msg.id);
45
+ if (p) {
46
+ this.pending.delete(msg.id);
47
+ if (msg.error) p.reject(new Error(msg.error.message || "rpc error"));
48
+ else p.resolve(msg.result);
49
+ }
50
+ } else if (msg.method && hasId) {
51
+ this.onRequest(msg.id, msg.method, msg.params);
52
+ } else if (msg.method) {
53
+ this.onNotification(msg.method, msg.params);
54
+ }
55
+ }
56
+
57
+ _write(obj) {
58
+ const serialized = JSON.stringify(obj) + "\n";
59
+ this._record("out", serialized);
60
+ this.output.write(serialized);
61
+ }
62
+
63
+ request(method, params) {
64
+ const id = this.nextId++;
65
+ return new Promise((resolve, reject) => {
66
+ this.pending.set(id, { resolve, reject });
67
+ this._write({ jsonrpc: "2.0", id, method, params });
68
+ });
69
+ }
70
+
71
+ notify(method, params) { this._write({ jsonrpc: "2.0", method, params }); }
72
+ respond(id, result) { this._write({ jsonrpc: "2.0", id, result }); }
73
+ respondError(id, code, message) { this._write({ jsonrpc: "2.0", id, error: { code, message } }); }
74
+
75
+ rejectAllPending(err) {
76
+ for (const p of this.pending.values()) p.reject(err);
77
+ this.pending.clear();
78
+ }
79
+
80
+ close() { this.rl.close(); }
81
+ }
package/src/server.js CHANGED
@@ -17,6 +17,53 @@ if (nodeMajor < 22) {
17
17
 
18
18
  const inFlight = new Map();
19
19
 
20
+ export const SERVER_INSTRUCTIONS = `Delegate coding work to Cursor through the delegate tool. The delegate tool can create, modify, or delete files in its workspace, so scope workspace to the smallest relevant directory and review touchedFiles plus the git diff after every write-capable run. For approval-gated work, call delegate with mode="plan", review the returned plan and sessionId, then resume with mode="agent" and resumeSessionId. Use mode="ask" for read-only questions and doctor for setup diagnostics.`;
21
+
22
+ const planEntrySchema = z.object({
23
+ content: z.string(),
24
+ priority: z.enum(["high", "medium", "low"]).optional(),
25
+ status: z.enum(["pending", "in_progress", "completed"]).optional(),
26
+ }).passthrough();
27
+
28
+ const delegateOutputSchema = z.object({
29
+ result: z.string(),
30
+ resultSource: z.enum(["tool-free-stream", "post-tool", "none"]).optional(),
31
+ finalMessageAvailable: z.boolean().optional(),
32
+ stopReason: z.string().optional(),
33
+ sessionId: z.string(),
34
+ touchedFiles: z.array(z.string()),
35
+ touchedFilesSource: z.enum(["git", "diff-only"]).optional(),
36
+ questionsAsked: z.array(z.string()).optional(),
37
+ resumed: z.boolean().optional(),
38
+ autoAnswered: z.array(z.object({ prompt: z.string(), chosen: z.string() })).optional(),
39
+ fallbackAnswers: z.array(z.object({ prompt: z.string(), given: z.string(), chosen: z.string() })).optional(),
40
+ protocolWarnings: z.array(z.string()).optional(),
41
+ plan: z.object({
42
+ entries: z.array(planEntrySchema),
43
+ overview: z.string().optional(),
44
+ detail: z.string().optional(),
45
+ }).optional(),
46
+ }).passthrough();
47
+
48
+ const doctorOutputSchema = z.object({
49
+ plugin: z.object({ version: z.string() }).passthrough(),
50
+ client: z.object({
51
+ name: z.string().nullable(),
52
+ version: z.string().nullable(),
53
+ capabilities: z.record(z.unknown()),
54
+ supportsElicitation: z.boolean(),
55
+ }).passthrough(),
56
+ agent: z.object({ found: z.boolean() }).passthrough(),
57
+ runtime: z.object({
58
+ node: z.string(),
59
+ platform: z.string(),
60
+ arch: z.string(),
61
+ cwd: z.string(),
62
+ transport: z.literal("stdio"),
63
+ }),
64
+ env: z.record(z.unknown()),
65
+ }).passthrough();
66
+
20
67
  export async function runDelegateTool({ args, extra, server, runDelegate, inFlight }) {
21
68
  const { spec, mode, resumeSessionId, workspace, model, fast } = args;
22
69
 
@@ -45,7 +92,7 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
45
92
  if (!supportsElicitation) {
46
93
  const chosenOptionId = opts[0]?.id;
47
94
  const chosen = opts.find((o) => o.id === chosenOptionId)?.label || chosenOptionId || "";
48
- autoAnswered.push({ prompt: q.prompt, chosen });
95
+ autoAnswered.push({ prompt: String(q.prompt ?? ""), chosen: String(chosen) });
49
96
  answers.push({ questionId: q.id, selectedOptionIds: [chosenOptionId] });
50
97
  continue;
51
98
  }
@@ -78,7 +125,7 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
78
125
  }
79
126
  if (!matched && opts.length) {
80
127
  const chosen = opts.find((o) => o.id === chosenOptionId)?.label || chosenOptionId || "";
81
- fallbackAnswers.push({ prompt: q.prompt, given: choice, chosen });
128
+ fallbackAnswers.push({ prompt: String(q.prompt ?? ""), given: String(choice), chosen: String(chosen) });
82
129
  }
83
130
  answers.push({ questionId: q.id, selectedOptionIds: [chosenOptionId] });
84
131
  }
@@ -120,13 +167,16 @@ export async function runDelegateTool({ args, extra, server, runDelegate, inFlig
120
167
  export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected } = {}) {
121
168
  const runDelegate = runDelegateInjected || runDelegateDefault;
122
169
  const runDoctor = runDoctorInjected || runDoctorDefault;
123
- const server = new McpServer({ name: "cursor-delegate-mcp", version: VERSION });
170
+ const server = new McpServer(
171
+ { name: "cursor-delegate-mcp", version: VERSION },
172
+ { instructions: SERVER_INSTRUCTIONS }
173
+ );
124
174
 
125
175
  server.registerTool(
126
176
  "delegate",
127
177
  {
128
178
  description:
129
- "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=composer-2.5, fast=false. Plan workflow: mode=plan, then resume with mode=agent and resumeSessionId. Auto-approves writes in workspace; surfaces clarifying questions via elicitation. Returns result, stopReason, sessionId, touchedFiles, and plan (in plan mode). See plugin delegate skill for orchestration.",
179
+ "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=composer-2.5, fast=false. Plan workflow: mode=plan, then resume with mode=agent and resumeSessionId. Auto-approves writes in workspace; uses MCP elicitation for clarifying questions and selects the first option when the client lacks elicitation. Returns the final result, selection source, stop reason, session ID, changed files, and optional plan. See the delegate skill for orchestration.",
130
180
  inputSchema: {
131
181
  spec: z.string().describe("Inline task brief (default): goal, scope, acceptance criteria. Optional file path if the user wants a persisted spec."),
132
182
  mode: z.enum(["agent", "plan", "ask"]).default("agent"),
@@ -135,6 +185,14 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
135
185
  model: z.string().default("composer-2.5"),
136
186
  fast: z.boolean().default(false).describe("Fast speed tier — higher cost; enable only when the user asks"),
137
187
  },
188
+ outputSchema: delegateOutputSchema,
189
+ annotations: {
190
+ title: "Delegate coding task to Cursor",
191
+ readOnlyHint: false,
192
+ destructiveHint: true,
193
+ idempotentHint: false,
194
+ openWorldHint: true,
195
+ },
138
196
  },
139
197
  async (args, extra) => runDelegateTool({ args, extra, server, runDelegate, inFlight })
140
198
  );
@@ -142,15 +200,32 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
142
200
  // cancel is best-effort: MCP tool calls are serialized, so delegate must finish first.
143
201
  server.registerTool(
144
202
  "cancel",
145
- { description: "Cancel an in-flight ACP delegation by sessionId.", inputSchema: { sessionId: z.string() } },
203
+ {
204
+ description: "Cancel an in-flight ACP delegation by sessionId.",
205
+ inputSchema: { sessionId: z.string() },
206
+ outputSchema: z.object({ status: z.enum(["cancelled", "not-found"]), sessionId: z.string() }),
207
+ annotations: {
208
+ title: "Cancel Cursor delegation",
209
+ readOnlyHint: false,
210
+ destructiveHint: true,
211
+ idempotentHint: true,
212
+ openWorldHint: false,
213
+ },
214
+ },
146
215
  async ({ sessionId }) => {
147
216
  const client = inFlight.get(sessionId);
148
217
  if (client) {
149
218
  await client.cancel(sessionId).catch(() => {});
150
219
  inFlight.delete(sessionId);
151
- return { content: [{ type: "text", text: `cancelled ${sessionId}` }] };
220
+ return {
221
+ content: [{ type: "text", text: `cancelled ${sessionId}` }],
222
+ structuredContent: { status: "cancelled", sessionId },
223
+ };
152
224
  }
153
- return { content: [{ type: "text", text: `no in-flight session ${sessionId}` }] };
225
+ return {
226
+ content: [{ type: "text", text: `no in-flight session ${sessionId}` }],
227
+ structuredContent: { status: "not-found", sessionId },
228
+ };
154
229
  }
155
230
  );
156
231
 
@@ -165,6 +240,14 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
165
240
  .default(false)
166
241
  .describe("When true, run a lightweight ACP handshake (start → initialize → newSession) to verify the agent is usable"),
167
242
  },
243
+ outputSchema: doctorOutputSchema,
244
+ annotations: {
245
+ title: "Diagnose Cursor delegation setup",
246
+ readOnlyHint: true,
247
+ destructiveHint: false,
248
+ idempotentHint: true,
249
+ openWorldHint: false,
250
+ },
168
251
  },
169
252
  async ({ deep }) => {
170
253
  const out = await runDoctor({
@@ -174,7 +257,10 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
174
257
  version: server.server.getClientVersion(),
175
258
  }),
176
259
  });
177
- return { content: [{ type: "text", text: JSON.stringify(out, null, 2) }] };
260
+ return {
261
+ content: [{ type: "text", text: JSON.stringify(out, null, 2) }],
262
+ structuredContent: out,
263
+ };
178
264
  }
179
265
  );
180
266