cursor-delegate-mcp 1.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrei Lungeanu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,170 @@
1
+ # Cursor Delegate MCP
2
+
3
+ **Use Cursor from inside Claude Code.** Delegate a coding task to Cursor's agent, get structured results back, and let Claude stay in the driver's seat.
4
+
5
+ ![Demo](demo.gif)
6
+
7
+ An MCP server that connects your AI client to **cursor-agent** over the [Agent Client Protocol](https://cursor.com/docs/cli/acp). You describe the work; the client passes a structured brief and hands it off. Cursor edits your repo, and you review what changed.
8
+
9
+ Ships as a **Claude Code plugin** (skill, slash command, hooks) and as a standalone **MCP server** for any compatible client.
10
+
11
+ ## What you can do
12
+
13
+ - **Delegate implementation** — Send a task to Cursor; files are updated in your workspace.
14
+ - **Plan before you build** — Run in plan mode, review the plan, then resume the same session to implement.
15
+ - **Get structured output** — Session id, which files changed, stop reason, and optional plan payload — not just raw terminal text.
16
+ - **Ask questions mid-run** — If Cursor needs a clarification, it comes back through the client's normal prompt.
17
+ - **Check setup** — The `doctor` tool tells you if cursor-agent is missing or misconfigured.
18
+
19
+ > Delegation **auto-approves file writes** in the target workspace.
20
+
21
+ ## Requirements
22
+
23
+ - [Node.js 22+](https://nodejs.org/)
24
+ - [cursor-agent](https://cursor.com/docs/cli/overview) installed and logged in (`cursor-agent login`)
25
+
26
+ ## Claude Code plugin
27
+
28
+ Best if you use [Claude Code](https://code.claude.com) and want delegation wired in automatically — skill, slash command, and dependency hooks included.
29
+
30
+ ### Install
31
+
32
+ ```shell
33
+ /plugin marketplace add andreilungeanu/cursor-delegate-mcp
34
+ /plugin install cursor-delegate-mcp@cursor-delegate-mcp
35
+ ```
36
+
37
+ First launch installs plugin dependencies automatically.
38
+
39
+ ### Use it
40
+
41
+ Say what you want in plain language — for example:
42
+
43
+ > Use Cursor to add input validation to the signup form and a test for it.
44
+
45
+ Claude loads the **delegate** skill when you mention Cursor or handing off work. You don't need to know tool names or write a spec file.
46
+
47
+ Optional slash command for an explicit handoff:
48
+
49
+ ```shell
50
+ /cursor-delegate-mcp:delegate Add input validation to the signup form and a test for it
51
+ ```
52
+
53
+ **Something not working?** Ask Claude to run `doctor`. If `agent.found` is false, install or log in to cursor-agent.
54
+
55
+ ## MCP server
56
+
57
+ Use the same server in **any** MCP-compatible client via npx — no Claude Code plugin required:
58
+
59
+ ```shell
60
+ npx -y cursor-delegate-mcp
61
+ ```
62
+
63
+ **cursor-agent** must be installed and logged in (`cursor-agent login`).
64
+
65
+ Clarifying-question prompts are interactive only on elicitation-capable clients (Claude Code, Cursor, VS Code). On other clients the recommended option is auto-selected and reported in the delegate result's `autoAnswered`.
66
+
67
+ ### Client configuration
68
+
69
+ #### Antigravity 2.0
70
+
71
+ `~/.gemini/config/mcp_config.json`:
72
+
73
+ ```json
74
+ {
75
+ "mcpServers": {
76
+ "cursor-delegate-mcp": {
77
+ "command": "npx",
78
+ "args": ["-y", "cursor-delegate-mcp"]
79
+ }
80
+ }
81
+ }
82
+ ```
83
+
84
+ #### Cursor
85
+
86
+ `~/.cursor/mcp.json`:
87
+
88
+ ```json
89
+ {
90
+ "mcpServers": {
91
+ "cursor-delegate-mcp": {
92
+ "command": "npx",
93
+ "args": ["-y", "cursor-delegate-mcp"]
94
+ }
95
+ }
96
+ }
97
+ ```
98
+
99
+ #### VS Code
100
+
101
+ `.vscode/mcp.json`:
102
+
103
+ ```json
104
+ {
105
+ "servers": {
106
+ "cursor-delegate-mcp": {
107
+ "type": "stdio",
108
+ "command": "npx",
109
+ "args": ["-y", "cursor-delegate-mcp"]
110
+ }
111
+ }
112
+ }
113
+ ```
114
+
115
+ #### Codex CLI
116
+
117
+ `~/.codex/config.toml`:
118
+
119
+ ```toml
120
+ [mcp_servers.cursor-delegate-mcp]
121
+ command = "npx"
122
+ args = ["-y", "cursor-delegate-mcp"]
123
+ ```
124
+
125
+ #### Kiro
126
+
127
+ `~/.kiro/settings/mcp.json`:
128
+
129
+ ```json
130
+ {
131
+ "mcpServers": {
132
+ "cursor-delegate-mcp": {
133
+ "command": "npx",
134
+ "args": ["-y", "cursor-delegate-mcp"]
135
+ }
136
+ }
137
+ }
138
+ ```
139
+
140
+ #### Kilo Code
141
+
142
+ `~/.config/kilo/kilo.jsonc`:
143
+
144
+ ```jsonc
145
+ {
146
+ "mcp": {
147
+ "cursor-delegate-mcp": {
148
+ "type": "local",
149
+ "command": ["npx", "-y", "cursor-delegate-mcp"],
150
+ "enabled": true
151
+ }
152
+ }
153
+ }
154
+ ```
155
+
156
+ Call the **`delegate`** MCP tool with your task. Use **`doctor`** to verify cursor-agent is available.
157
+
158
+ ## Delegation modes
159
+
160
+ Applies to both the plugin and the MCP server:
161
+
162
+ - **Agent (default)** — Cursor implements in your workspace; you review the diff afterward.
163
+ - **Plan** — Cursor drafts a plan first; review it, then resume and implement.
164
+ - **Ask** — Read-only Q&A over the codebase; no file changes.
165
+
166
+ By default, delegation uses the **Composer 2.5** model (standard tier). Cursor includes a separate **Auto + Composer** usage pool with generous included quota, apart from the API pool other models draw from. For a different model, say so (for example, "use Opus" or "delegate with Codex").
167
+
168
+ ## License
169
+
170
+ MIT © Andrei Lungeanu
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "cursor-delegate-mcp",
3
+ "version": "1.1.0",
4
+ "type": "module",
5
+ "description": "MCP server bridging Claude Code to cursor-agent over the Agent Client Protocol (ACP).",
6
+ "license": "MIT",
7
+ "author": "Andrei Lungeanu <alungeanu@teramind.co>",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/andreilungeanu/cursor-delegate-mcp.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/andreilungeanu/cursor-delegate-mcp/issues"
14
+ },
15
+ "homepage": "https://github.com/andreilungeanu/cursor-delegate-mcp#readme",
16
+ "keywords": [
17
+ "mcp",
18
+ "cursor",
19
+ "cursor-agent",
20
+ "acp",
21
+ "agent-client-protocol",
22
+ "claude-code",
23
+ "composer"
24
+ ],
25
+ "main": "src/server.js",
26
+ "bin": {
27
+ "cursor-delegate-mcp": "src/server.js"
28
+ },
29
+ "engines": {
30
+ "node": ">=22"
31
+ },
32
+ "files": [
33
+ "src",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "scripts": {
38
+ "test": "node --test test/*.test.js",
39
+ "start": "node src/server.js"
40
+ },
41
+ "dependencies": {
42
+ "@modelcontextprotocol/sdk": "^1.12.0",
43
+ "zod": "^3.23.8"
44
+ }
45
+ }
@@ -0,0 +1,82 @@
1
+ import { spawn } from "node:child_process";
2
+ import { EventEmitter } from "node:events";
3
+ import { readFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { JsonRpcPeer } from "./jsonrpc.js";
7
+ import { createRequestRouter } from "./request-router.js";
8
+ import { resolveAcpSpawn } from "./spawn.js";
9
+
10
+ const STDERR_CAP = 64 * 1024;
11
+
12
+ const VERSION = JSON.parse(
13
+ readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8")
14
+ ).version;
15
+
16
+ export class AcpClient extends EventEmitter {
17
+ constructor({ spawnSpec, onElicit, mode, onCreatePlan } = {}) {
18
+ super();
19
+ this.spawnSpec = spawnSpec || resolveAcpSpawn();
20
+ this.onElicit = onElicit;
21
+ this.mode = mode;
22
+ this.onCreatePlan = onCreatePlan;
23
+ }
24
+
25
+ start() {
26
+ const { command, args, options } = this.spawnSpec;
27
+ this.stderrBuffer = "";
28
+ this._exitEmitted = false;
29
+ this.child = spawn(command, args, { ...options, stdio: ["pipe", "pipe", "pipe"] });
30
+ this.child.stderr.on("data", (chunk) => {
31
+ this.stderrBuffer = (this.stderrBuffer + chunk.toString()).slice(-STDERR_CAP);
32
+ this.emit("activity");
33
+ });
34
+ this.child.stderr.on("error", () => {});
35
+ const emitExit = (code, signal) => {
36
+ if (this._exitEmitted) return;
37
+ this._exitEmitted = true;
38
+ const stderr = this.stderrBuffer;
39
+ const err = new Error(
40
+ `agent exited (code=${code}${signal ? ", signal=" + signal : ""})${stderr ? ": " + String(stderr).slice(-2000) : ""}`
41
+ );
42
+ err.reason = "agent-exit";
43
+ // exit + rejectAllPending both settle the same Promise.race; second rejection is intentional.
44
+ this.peer?.rejectAllPending(err);
45
+ this.emit("exit", { code, signal, stderr });
46
+ };
47
+ this.child.once("exit", emitExit);
48
+ this.child.once("close", emitExit);
49
+ this.router = null; // set before first stdout line
50
+ this.peer = new JsonRpcPeer(this.child.stdout, this.child.stdin, {
51
+ onNotification: (method, params) => { if (method === "session/update") this.emit("update", params); },
52
+ onRequest: (id, method, params) => this.router && this.router(id, method, params),
53
+ onActivity: () => this.emit("activity"),
54
+ });
55
+ this.router = createRequestRouter({
56
+ respond: (id, r) => this.peer.respond(id, r),
57
+ respondError: (id, c, m) => this.peer.respondError(id, c, m),
58
+ onElicit: this.onElicit,
59
+ onCreatePlan: this.onCreatePlan,
60
+ mode: this.mode,
61
+ log: (e) => this.emit("ack", e),
62
+ });
63
+ return new Promise((resolve, reject) => {
64
+ this.child.once("error", (e) =>
65
+ reject(new Error(`Failed to spawn agent (${command}): ${e.message}. Install Cursor CLI and run 'agent login'.`)));
66
+ this.child.once("spawn", () => resolve());
67
+ });
68
+ }
69
+
70
+ initialize() { return this.peer.request("initialize", { protocolVersion: 1, clientInfo: { name: "cursor-delegate-mcp", version: VERSION }, clientCapabilities: { _meta: { parameterizedModelPicker: true } } }); }
71
+ newSession(cwd) { return this.peer.request("session/new", { cwd, mcpServers: [] }); }
72
+ loadSession(sessionId, cwd) { return this.peer.request("session/load", { sessionId, cwd, mcpServers: [] }); }
73
+ setModel(sessionId, modelId) { return this.peer.request("session/set_model", { sessionId, modelId }); }
74
+ setFast(sessionId, value) { return this.peer.request("session/set_config_option", { sessionId, configId: "fast", value }); } // configId, not optionId
75
+ setMode(sessionId, modeId) { return this.peer.request("session/set_mode", { sessionId, modeId }); }
76
+ prompt(sessionId, text) { return this.peer.request("session/prompt", { sessionId, prompt: [{ type: "text", text }] }); }
77
+ cancel(sessionId) { this.peer.notify("session/cancel", { sessionId }); return Promise.resolve(); }
78
+
79
+ getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
80
+
81
+ stop() { try { this.peer?.close(); } catch {} try { this.child?.kill(); } catch {} }
82
+ }
@@ -0,0 +1,161 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { AcpClient } from "./acp-client.js";
3
+ import { SessionSupervisor } from "./session-supervisor.js";
4
+ import { gitChangedSet as gitChangedSetReal, computeTouched } from "./touched-files.js";
5
+
6
+ function resolveSpec(spec) {
7
+ if (typeof spec !== "string") return spec;
8
+ const looksLikePath = !spec.includes("\n")
9
+ && (spec.includes("/") || spec.includes("\\") || spec.endsWith(".md") || spec.endsWith(".txt"));
10
+ if (!looksLikePath) return spec;
11
+ try {
12
+ if (statSync(spec).isFile()) return readFileSync(spec, "utf8");
13
+ } catch {}
14
+ return spec;
15
+ }
16
+
17
+ async function openSession(client, resumeSessionId, workspace) {
18
+ if (!resumeSessionId) return client.newSession(workspace);
19
+ try {
20
+ await client.loadSession(resumeSessionId, workspace);
21
+ return { sessionId: resumeSessionId }; // load does not echo sessionId
22
+ } catch {
23
+ // stale or unknown session — start fresh
24
+ }
25
+ return client.newSession(workspace);
26
+ }
27
+
28
+ // Composer bare ids (e.g. composer-2.5) expose standard vs fast via set_config_option.
29
+ // Other models use separate ids (e.g. gpt-5-fast) — see agent --list-models.
30
+ function composerFastToggleApplies(model) {
31
+ return /^composer-\d+(?:\.\d+)?$/i.test(model);
32
+ }
33
+
34
+ export async function runDelegate({
35
+ spec, mode = "agent", resumeSessionId, workspace,
36
+ model = "composer-2.5", fast = "false", clientFactory, onElicit,
37
+ idleMs = 90000, hardCapMs, timeoutMs, cancelGraceMs = 10000, killGraceMs = 5000,
38
+ onSessionReady, onProgress, gitChangedSet = gitChangedSetReal,
39
+ } = {}) {
40
+ const capMs = hardCapMs ?? timeoutMs ?? 3600000;
41
+ const MAX_OUTPUT = 10 * 1024 * 1024;
42
+ const TRUNCATION_MARKER = "\n\n[output truncated at 10MB]";
43
+ const questionsAsked = [];
44
+ const recordQuestions = (q) => {
45
+ if (q.kind !== "ask_question") return;
46
+ for (const question of q.questions || []) {
47
+ if (question?.prompt) questionsAsked.push(question.prompt);
48
+ }
49
+ };
50
+ const wrappedElicit = onElicit
51
+ ? async (q) => { recordQuestions(q); return onElicit(q); }
52
+ : async (q) => { recordQuestions(q); return null; };
53
+
54
+ let planEntries = [];
55
+ let planOverview;
56
+ let planDetail;
57
+ const recordCreatePlan = (body) => {
58
+ if (body?.overview !== undefined) planOverview = body.overview;
59
+ if (body?.plan !== undefined) planDetail = body.plan;
60
+ };
61
+
62
+ const make = clientFactory || ((opts) => new AcpClient(opts));
63
+ const client = make({ onElicit: wrappedElicit, mode, onCreatePlan: recordCreatePlan });
64
+ const supervisor = new SessionSupervisor(client, { idleMs, hardCapMs: capMs, cancelGraceMs, killGraceMs });
65
+
66
+ const textChunks = [];
67
+ let textLength = 0;
68
+ let truncated = false;
69
+ const touched = new Set();
70
+ client.on("update", (u) => {
71
+ const up = u?.update || {};
72
+ if (up.sessionUpdate === "plan") {
73
+ planEntries = up.entries || [];
74
+ }
75
+ if (up.sessionUpdate === "agent_thought_chunk" && up.content?.text) {
76
+ const text = up.content.text;
77
+ const tail = text.length > 200 ? text.slice(-200) : text;
78
+ try { onProgress?.("thinking: " + (tail.trim() || text.slice(0, 200))); } catch {}
79
+ }
80
+ if (up.sessionUpdate === "tool_call") {
81
+ const label = up.title || up.kind || "tool";
82
+ try { onProgress?.("running: " + String(label).slice(0, 200)); } catch {}
83
+ }
84
+ if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
85
+ const text = up.content.text;
86
+ if (!truncated) {
87
+ const remaining = MAX_OUTPUT - textLength;
88
+ if (text.length <= remaining) {
89
+ textChunks.push(text);
90
+ textLength += text.length;
91
+ } else if (remaining > 0) {
92
+ textChunks.push(text.slice(0, remaining));
93
+ textLength += remaining;
94
+ truncated = true;
95
+ } else {
96
+ truncated = true;
97
+ }
98
+ }
99
+ const tail = text.length > 200 ? text.slice(-200) : text;
100
+ try { onProgress?.(tail.trim() || text.slice(0, 200)); } catch {}
101
+ }
102
+ if (up.sessionUpdate === "tool_call_update") {
103
+ for (const c of up.content || []) {
104
+ if (c.type === "diff" && c.path) {
105
+ touched.add(c.path);
106
+ try { onProgress?.("editing " + c.path); } catch {}
107
+ }
108
+ }
109
+ }
110
+ });
111
+
112
+ try {
113
+ let sessionId;
114
+ const gitBefore = gitChangedSet(workspace); // before/after delta catches shell edits
115
+ const res = await supervisor.supervise(async () => {
116
+ await client.start();
117
+ await client.initialize();
118
+ const sess = await openSession(client, resumeSessionId, workspace);
119
+ sessionId = sess.sessionId;
120
+ supervisor.setSessionId(sessionId);
121
+ onSessionReady?.(sessionId, client);
122
+ await client.setModel(sessionId, model);
123
+ if (composerFastToggleApplies(model)) await client.setFast(sessionId, fast);
124
+ await client.setMode(sessionId, mode);
125
+ textChunks.length = 0;
126
+ textLength = 0;
127
+ truncated = false;
128
+ planEntries = [];
129
+ planOverview = undefined;
130
+ planDetail = undefined;
131
+ touched.clear();
132
+ return client.prompt(sessionId, resolveSpec(spec));
133
+ });
134
+ let result = textChunks.join("");
135
+ if (truncated) result += TRUNCATION_MARKER;
136
+ const gitAfter = gitChangedSet(workspace);
137
+ const touchedResult = computeTouched({ before: gitBefore, after: gitAfter, diffTouched: [...touched], workspace });
138
+ const out = {
139
+ result,
140
+ stopReason: res?.stopReason,
141
+ sessionId,
142
+ touchedFiles: touchedResult.files,
143
+ touchedFilesSource: touchedResult.source,
144
+ questionsAsked,
145
+ resumed: !!resumeSessionId && sessionId === resumeSessionId,
146
+ };
147
+ if (planEntries.length > 0 || planOverview !== undefined || planDetail !== undefined) {
148
+ out.plan = { entries: planEntries, overview: planOverview, detail: planDetail };
149
+ }
150
+ return out;
151
+ } catch (err) {
152
+ try {
153
+ const transcript = client.getTranscript?.(40);
154
+ if (transcript) err.message += "\n\n--- recent ACP transcript (last 40 frames) ---\n" + transcript;
155
+ } catch {}
156
+ throw err;
157
+ } finally {
158
+ try { supervisor.finish(); } catch {}
159
+ client.stop();
160
+ }
161
+ }
package/src/doctor.js ADDED
@@ -0,0 +1,108 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import process from "node:process";
5
+ import { spawn } from "node:child_process";
6
+ import { AcpClient } from "./acp-client.js";
7
+ import { resolveAcpSpawn } from "./spawn.js";
8
+
9
+ const HANDSHAKE_TIMEOUT_MS = 15_000;
10
+ const DEFAULT_LOG_SIZE = "2000";
11
+
12
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
13
+ const pluginVersion = JSON.parse(readFileSync(path.join(__dirname, "..", "package.json"), "utf8")).version;
14
+
15
+ function formatCommand({ command, args }) {
16
+ return args?.length ? `${command} ${args.join(" ")}` : command;
17
+ }
18
+
19
+ export function probeAgentVersion(spawnSpec) {
20
+ const { command, options } = spawnSpec;
21
+ const isJsScript = /\.js$/i.test(command);
22
+ const execCommand = isJsScript ? process.execPath : command;
23
+ const execArgs = isJsScript ? [command, "--version"] : ["--version"];
24
+ return new Promise((resolve) => {
25
+ let settled = false;
26
+ let stdout = "";
27
+ const finish = (result) => {
28
+ if (settled) return;
29
+ settled = true;
30
+ resolve(result);
31
+ };
32
+ const child = spawn(execCommand, execArgs, { ...options, stdio: ["ignore", "pipe", "pipe"] });
33
+ child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
34
+ child.on("error", () => finish({ found: false, version: null }));
35
+ child.on("close", (code) => {
36
+ finish({
37
+ found: true,
38
+ version: code === 0 ? stdout.trim() || null : null,
39
+ });
40
+ });
41
+ });
42
+ }
43
+
44
+ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs }) {
45
+ const client = clientFactory({ spawnSpec });
46
+ const workspaceDir = workspace || process.cwd();
47
+ let timer;
48
+ try {
49
+ const work = (async () => {
50
+ await client.start();
51
+ await client.initialize();
52
+ await client.newSession(workspaceDir);
53
+ })();
54
+ const timeout = new Promise((_, reject) => {
55
+ timer = setTimeout(() => {
56
+ try { client.stop(); } catch {}
57
+ reject(new Error(`Handshake timed out after ${timeoutMs}ms`));
58
+ }, timeoutMs);
59
+ });
60
+ await Promise.race([work, timeout]);
61
+ return { ok: true };
62
+ } catch (err) {
63
+ return { ok: false, error: err?.message || String(err) };
64
+ } finally {
65
+ clearTimeout(timer);
66
+ try { client.stop(); } catch {}
67
+ }
68
+ }
69
+
70
+ export async function runDoctor({
71
+ getClientInfo = () => ({ capabilities: {}, version: {} }),
72
+ deep = false,
73
+ spawnSpec = resolveAcpSpawn(),
74
+ clientFactory = (opts) => new AcpClient(opts),
75
+ workspace,
76
+ } = {}) {
77
+ const { capabilities, version } = getClientInfo();
78
+ const agentProbe = await probeAgentVersion(spawnSpec);
79
+
80
+ const out = {
81
+ plugin: { version: pluginVersion },
82
+ client: {
83
+ name: version?.name ?? null,
84
+ version: version?.version ?? null,
85
+ capabilities: capabilities ?? {},
86
+ supportsElicitation: !!capabilities?.elicitation,
87
+ },
88
+ agent: {
89
+ found: agentProbe.found,
90
+ command: formatCommand(spawnSpec),
91
+ version: agentProbe.version,
92
+ },
93
+ env: {
94
+ ACP_LOG_SIZE: process.env.ACP_LOG_SIZE !== undefined ? process.env.ACP_LOG_SIZE : DEFAULT_LOG_SIZE,
95
+ },
96
+ };
97
+
98
+ if (deep) {
99
+ out.agent.handshake = await runDeepHandshake({
100
+ spawnSpec,
101
+ clientFactory,
102
+ workspace,
103
+ timeoutMs: HANDSHAKE_TIMEOUT_MS,
104
+ });
105
+ }
106
+
107
+ return out;
108
+ }
package/src/jsonrpc.js ADDED
@@ -0,0 +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
+ }
@@ -0,0 +1,42 @@
1
+ const ACK_METHODS = new Set(["cursor/update_todos", "cursor/task", "cursor/generate_image"]);
2
+
3
+ export function createRequestRouter({ respond, respondError, onElicit, onCreatePlan, mode = "agent", log = () => {} }) {
4
+ return async function handle(id, method, params) {
5
+ try {
6
+ if (method === "session/request_permission") {
7
+ const opts = params?.options || [];
8
+ const pick =
9
+ opts.find((o) => o.kind === "allow_always") ||
10
+ opts.find((o) => o.kind === "allow_once") ||
11
+ opts[0];
12
+ return respond(id, { outcome: { outcome: "selected", optionId: pick?.optionId } });
13
+ }
14
+ if (method === "cursor/ask_question") {
15
+ const ans = onElicit
16
+ ? await onElicit({ kind: "ask_question", title: params?.title, questions: params?.questions || [], raw: params })
17
+ : null;
18
+ if (ans?.answers?.length) {
19
+ return respond(id, { outcome: { outcome: "answered", answers: ans.answers } });
20
+ }
21
+ return respond(id, { outcome: { outcome: "cancelled" } });
22
+ }
23
+ if (method === "cursor/create_plan") {
24
+ onCreatePlan?.({
25
+ overview: params?.overview,
26
+ plan: params?.plan,
27
+ name: params?.name,
28
+ raw: params,
29
+ });
30
+ const outcome = mode === "agent" ? "accepted" : "rejected";
31
+ return respond(id, { outcome: { outcome } });
32
+ }
33
+ if (ACK_METHODS.has(method)) {
34
+ log({ method, params });
35
+ return respond(id, {});
36
+ }
37
+ return respondError(id, -32601, `Unhandled method: ${method}`);
38
+ } catch (err) {
39
+ return respondError(id, -32000, `Router error: ${err?.message || err}`);
40
+ }
41
+ };
42
+ }
package/src/server.js ADDED
@@ -0,0 +1,184 @@
1
+ #!/usr/bin/env node
2
+ import process from "node:process";
3
+ import path from "node:path";
4
+ import { readFileSync } from "node:fs";
5
+ import { fileURLToPath } from "node:url";
6
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+ import { z } from "zod";
9
+ import { runDelegate as runDelegateDefault } from "./delegate.js";
10
+ import { runDoctor as runDoctorDefault } from "./doctor.js";
11
+
12
+ const pluginVersion = JSON.parse(
13
+ readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8")
14
+ ).version;
15
+
16
+ const inFlight = new Map();
17
+
18
+ export async function runDelegateTool({ args, extra, server, runDelegate, inFlight }) {
19
+ const { spec, mode, resumeSessionId, workspace, model, fast } = args;
20
+
21
+ const progressToken = extra?._meta?.progressToken;
22
+ let onProgress = () => {};
23
+ if (progressToken != null) {
24
+ let progress = 0;
25
+ let lastSent = 0;
26
+ onProgress = (message) => {
27
+ const now = Date.now();
28
+ if (progress > 0 && now - lastSent < 100) return;
29
+ lastSent = now;
30
+ try {
31
+ extra.sendNotification({
32
+ method: "notifications/progress",
33
+ params: { progressToken, progress: ++progress, message },
34
+ });
35
+ } catch {}
36
+ };
37
+ }
38
+
39
+ const supportsElicitation = !!server.server.getClientCapabilities?.()?.elicitation;
40
+ const autoAnswered = [];
41
+
42
+ const onElicit = async ({ title, questions }) => {
43
+ const answers = [];
44
+ for (const q of questions || []) {
45
+ const opts = q.options || [];
46
+ if (!supportsElicitation) {
47
+ const chosenOptionId = opts[0]?.id;
48
+ const chosen = opts.find((o) => o.id === chosenOptionId)?.label || chosenOptionId || "";
49
+ autoAnswered.push({ prompt: q.prompt, chosen });
50
+ answers.push({ questionId: q.id, selectedOptionIds: [chosenOptionId] });
51
+ continue;
52
+ }
53
+ const result = await server.server.elicitInput({
54
+ message: title ? `${title}: ${q.prompt}` : `cursor-agent asks: ${q.prompt}`,
55
+ requestedSchema: {
56
+ type: "object",
57
+ properties: {
58
+ choice: {
59
+ type: "string",
60
+ description: opts.length ? `Options: ${opts.map((o) => o.label || o.id).join(", ")}` : "your answer",
61
+ },
62
+ },
63
+ required: ["choice"],
64
+ },
65
+ });
66
+ if (result.action !== "accept") return null;
67
+ const choice = result.content?.choice || "";
68
+ let chosenOptionId = opts[0]?.id;
69
+ for (const o of opts) {
70
+ if (
71
+ choice.toLowerCase() === String(o.id || "").toLowerCase() ||
72
+ choice.toLowerCase() === String(o.label || "").toLowerCase()
73
+ ) {
74
+ chosenOptionId = o.id;
75
+ break;
76
+ }
77
+ }
78
+ answers.push({ questionId: q.id, selectedOptionIds: [chosenOptionId] });
79
+ }
80
+ return { answers };
81
+ };
82
+
83
+ let capturedSessionId;
84
+ try {
85
+ const out = await runDelegate({
86
+ spec,
87
+ mode,
88
+ resumeSessionId,
89
+ workspace: workspace || process.cwd(),
90
+ model,
91
+ fast,
92
+ onElicit,
93
+ onProgress,
94
+ onSessionReady: (sessionId, client) => {
95
+ capturedSessionId = sessionId;
96
+ inFlight.set(sessionId, client);
97
+ },
98
+ });
99
+ if (autoAnswered.length) out.autoAnswered = autoAnswered;
100
+ return {
101
+ content: [{ type: "text", text: JSON.stringify(out, null, 2) }],
102
+ structuredContent: out,
103
+ };
104
+ } catch (err) {
105
+ return {
106
+ content: [{ type: "text", text: "delegate failed: " + (err?.message || String(err)) }],
107
+ isError: true,
108
+ };
109
+ } finally {
110
+ if (capturedSessionId) inFlight.delete(capturedSessionId);
111
+ }
112
+ }
113
+
114
+ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected } = {}) {
115
+ const runDelegate = runDelegateInjected || runDelegateDefault;
116
+ const runDoctor = runDoctorInjected || runDoctorDefault;
117
+ const server = new McpServer({ name: "cursor-delegate-mcp", version: pluginVersion });
118
+
119
+ server.registerTool(
120
+ "delegate",
121
+ {
122
+ description:
123
+ "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.",
124
+ inputSchema: {
125
+ spec: z.string().describe("Inline task brief (default): goal, scope, acceptance criteria. Optional file path if the user wants a persisted spec."),
126
+ mode: z.enum(["agent", "plan", "ask"]).default("agent"),
127
+ resumeSessionId: z.string().optional().describe("Resume an existing ACP session instead of a new one"),
128
+ workspace: z.string().optional().describe("Working directory for the agent (defaults to cwd)"),
129
+ model: z.string().default("composer-2.5"),
130
+ fast: z.enum(["false", "true"]).default("false").describe("Speed tier override; defaults to standard (\"false\")"),
131
+ },
132
+ },
133
+ async (args, extra) => runDelegateTool({ args, extra, server, runDelegate, inFlight })
134
+ );
135
+
136
+ // cancel is best-effort: MCP tool calls are serialized, so delegate must finish first.
137
+ server.registerTool(
138
+ "cancel",
139
+ { description: "Cancel an in-flight ACP delegation by sessionId.", inputSchema: { sessionId: z.string() } },
140
+ async ({ sessionId }) => {
141
+ const client = inFlight.get(sessionId);
142
+ if (client) {
143
+ await client.cancel(sessionId).catch(() => {});
144
+ inFlight.delete(sessionId);
145
+ return { content: [{ type: "text", text: `cancelled ${sessionId}` }] };
146
+ }
147
+ return { content: [{ type: "text", text: `no in-flight session ${sessionId}` }] };
148
+ }
149
+ );
150
+
151
+ server.registerTool(
152
+ "doctor",
153
+ {
154
+ description:
155
+ "Report setup and health diagnostics: plugin version, MCP client capabilities (including elicitation support), cursor-agent launcher resolution, and optional deep ACP handshake. Use when delegation fails or agent.found is false.",
156
+ inputSchema: {
157
+ deep: z
158
+ .boolean()
159
+ .default(false)
160
+ .describe("When true, run a lightweight ACP handshake (start → initialize → newSession) to verify the agent is usable"),
161
+ },
162
+ },
163
+ async ({ deep }) => {
164
+ const out = await runDoctor({
165
+ deep,
166
+ getClientInfo: () => ({
167
+ capabilities: server.server.getClientCapabilities(),
168
+ version: server.server.getClientVersion(),
169
+ }),
170
+ });
171
+ return { content: [{ type: "text", text: JSON.stringify(out, null, 2) }] };
172
+ }
173
+ );
174
+
175
+ return server;
176
+ }
177
+
178
+ const __filename = fileURLToPath(import.meta.url);
179
+ const isMain = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(__filename);
180
+
181
+ if (isMain) {
182
+ const server = buildServer();
183
+ await server.connect(new StdioServerTransport());
184
+ }
@@ -0,0 +1,131 @@
1
+ import process from "node:process";
2
+ import { execFile } from "node:child_process";
3
+
4
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5
+
6
+ function makeError(reason, message) {
7
+ const err = new Error(message);
8
+ err.reason = reason;
9
+ return err;
10
+ }
11
+
12
+ function isChildAlive(child) {
13
+ return child && child.exitCode === null && child.signalCode === null;
14
+ }
15
+
16
+ async function treeKill(pid) {
17
+ if (process.platform === "win32") {
18
+ await new Promise((resolve) => {
19
+ execFile("taskkill", ["/PID", String(pid), "/T", "/F"], () => resolve());
20
+ });
21
+ return;
22
+ }
23
+ try { process.kill(pid, "SIGKILL"); } catch {}
24
+ }
25
+
26
+ export class SessionSupervisor {
27
+ constructor(client, {
28
+ idleMs = 90000,
29
+ hardCapMs = 3600000,
30
+ cancelGraceMs = 10000,
31
+ killGraceMs = 5000,
32
+ } = {}) {
33
+ this.client = client;
34
+ this.idleMs = idleMs;
35
+ this.hardCapMs = hardCapMs;
36
+ this.cancelGraceMs = cancelGraceMs;
37
+ this.killGraceMs = killGraceMs;
38
+ this.sessionId = null;
39
+ this._idleTimer = null;
40
+ this._hardCapTimer = null;
41
+ this._armed = false;
42
+ this._settled = false;
43
+ this._escalation = null;
44
+ this._guardReject = null;
45
+ this._onActivity = () => this._resetIdle();
46
+ this._onExit = (info) => {
47
+ this._trip(
48
+ "agent-exit",
49
+ `agent exited (code=${info.code}${info.signal ? ", signal=" + info.signal : ""})${info.stderr ? ": " + String(info.stderr).slice(-2000) : ""}`
50
+ );
51
+ };
52
+ }
53
+
54
+ setSessionId(sessionId) {
55
+ this.sessionId = sessionId;
56
+ }
57
+
58
+ arm() {
59
+ if (this._armed) return;
60
+ this._armed = true;
61
+ this.client.on("activity", this._onActivity);
62
+ this.client.on("exit", this._onExit);
63
+ this._hardCapTimer = setTimeout(() => {
64
+ this._trip("hard-cap", `Session hard-cap exceeded after ${this.hardCapMs}ms`);
65
+ }, this.hardCapMs);
66
+ this._resetIdle();
67
+ }
68
+
69
+ disarm() {
70
+ if (!this._armed) return;
71
+ this._armed = false;
72
+ this.client.off("activity", this._onActivity);
73
+ this.client.off("exit", this._onExit);
74
+ clearTimeout(this._idleTimer);
75
+ clearTimeout(this._hardCapTimer);
76
+ this._idleTimer = null;
77
+ this._hardCapTimer = null;
78
+ }
79
+
80
+ _resetIdle() {
81
+ clearTimeout(this._idleTimer);
82
+ if (!this._armed || this._settled) return;
83
+ this._idleTimer = setTimeout(() => {
84
+ this._trip("idle-timeout", `Session idle timeout after ${this.idleMs}ms`);
85
+ }, this.idleMs);
86
+ }
87
+
88
+ _trip(reason, message) {
89
+ if (this._settled) return;
90
+ this._settled = true;
91
+ this.disarm();
92
+ const err = makeError(reason, message);
93
+ if (reason === "idle-timeout" || reason === "hard-cap") {
94
+ if (!this._escalation) this._escalation = this._runEscalation();
95
+ }
96
+ this._guardReject?.(err);
97
+ }
98
+
99
+ async _runEscalation() {
100
+ const { client, sessionId } = this;
101
+ if (sessionId) {
102
+ try { await client.cancel(sessionId); } catch {}
103
+ await sleep(this.cancelGraceMs);
104
+ }
105
+ const child = client.child;
106
+ if (!isChildAlive(child)) return;
107
+ try { child.kill(); } catch {}
108
+ await sleep(this.killGraceMs);
109
+ if (!isChildAlive(child)) return;
110
+ const pid = child.pid;
111
+ if (pid) await treeKill(pid);
112
+ }
113
+
114
+ finish() {
115
+ this._escalation?.catch(() => {});
116
+ this.disarm();
117
+ }
118
+
119
+ supervise(work) {
120
+ this.arm();
121
+ const guard = new Promise((_, reject) => { this._guardReject = reject; });
122
+ const run = Promise.resolve().then(work);
123
+ return Promise.race([run, guard]).finally(() => {
124
+ this._guardReject = null;
125
+ if (!this._settled) {
126
+ this._settled = true;
127
+ this.disarm();
128
+ }
129
+ });
130
+ }
131
+ }
package/src/spawn.js ADDED
@@ -0,0 +1,9 @@
1
+ import process from "node:process";
2
+
3
+ export function resolveAcpSpawn() {
4
+ const command = process.env.ACP_AGENT_COMMAND || "agent";
5
+ const args = process.env.ACP_AGENT_ARGS
6
+ ? process.env.ACP_AGENT_ARGS.split(" ").filter(Boolean)
7
+ : ["acp"];
8
+ return { command, args, options: { shell: process.platform === "win32" } };
9
+ }
@@ -0,0 +1,59 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import path from "node:path";
3
+
4
+ // Diff blocks miss shell-driven edits; git before/after delta is the primary signal.
5
+
6
+ function defaultRun(cmd, args) {
7
+ return execFileSync(cmd, args, { encoding: "utf8", windowsHide: true });
8
+ }
9
+
10
+ export function parsePorcelain(stdout, repoRoot) {
11
+ const set = new Set();
12
+ for (const raw of String(stdout || "").split("\n")) {
13
+ if (!raw.trim()) continue;
14
+ const rest = raw.slice(3);
15
+ const arrow = rest.indexOf(" -> ");
16
+ const p = (arrow !== -1 ? rest.slice(arrow + 4) : rest).trim();
17
+ if (p) set.add(path.resolve(repoRoot, p));
18
+ }
19
+ return set;
20
+ }
21
+
22
+ export function gitChangedSet(workspace, run = defaultRun) {
23
+ if (!workspace) return null;
24
+ try {
25
+ const root = run("git", ["-C", workspace, "rev-parse", "--show-toplevel"]).trim();
26
+ const out = run("git", [
27
+ "-C", workspace, "-c", "core.quotepath=false",
28
+ "status", "--porcelain=v1", "--untracked-files=all",
29
+ ]);
30
+ return parsePorcelain(out, root);
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ function relativize(abs, workspace) {
37
+ if (!workspace) return abs;
38
+ const r = path.relative(workspace, abs);
39
+ if (!r || r.startsWith("..") || path.isAbsolute(r)) return abs;
40
+ return r.split(path.sep).join("/");
41
+ }
42
+
43
+ export function computeTouched({ before, after, diffTouched = [], workspace } = {}) {
44
+ const diffAbs = diffTouched.map((p) => (workspace ? path.resolve(workspace, p) : path.resolve(p)));
45
+ let files;
46
+ let source;
47
+ if (!after) {
48
+ files = [...new Set(diffAbs)];
49
+ source = "diff-only";
50
+ } else {
51
+ const beforeSet = before || new Set();
52
+ const out = new Set();
53
+ for (const f of after) if (!beforeSet.has(f)) out.add(f);
54
+ for (const f of diffAbs) if (after.has(f)) out.add(f);
55
+ files = [...out];
56
+ source = "git";
57
+ }
58
+ return { files: files.map((f) => relativize(f, workspace)), source };
59
+ }