forked from sailay1996/cursor-agent-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1170 lines (1054 loc) · 41.8 KB
/
server.js
File metadata and controls
1170 lines (1054 loc) · 41.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MCP wrapper server for cursor-agent CLI
// Exposes multiple tools (chat/edit/analyze/search/plan/raw + legacy run) for better discoverability.
// Start via MCP config (stdio). Requires Node 18+.
import { z } from 'zod';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { spawn } from 'node:child_process';
import process from 'node:process';
import path from 'node:path';
import fs from 'node:fs';
import os from 'node:os';
// Environment variable schemas and validation
// Helper to parse boolean-like env vars ('1', 'true', 'yes', 'on')
const booleanEnvSchema = z
.string()
.optional()
.transform((val) => {
if (!val) return false;
const lower = val.toLowerCase().trim();
return lower === '1' || lower === 'true' || lower === 'yes' || lower === 'on';
});
// Helper to parse positive integer milliseconds
const positiveIntMsSchema = z
.string()
.optional()
.transform((val) => {
if (!val) return undefined;
const parsed = Number.parseInt(val.trim(), 10);
if (!Number.isFinite(parsed) || parsed < 0) return undefined;
return parsed;
});
// Helper to validate executable path (security: no path traversal)
const executablePathSchema = z
.string()
.optional()
.transform((val) => {
if (!val || !val.trim()) return undefined;
const trimmed = val.trim();
const normalized = path.normalize(trimmed);
if (normalized.includes('..') || (!path.isAbsolute(normalized) && normalized.includes('/'))) {
throw new Error('CURSOR_AGENT_PATH contains invalid path traversal');
}
return path.isAbsolute(normalized) ? normalized : trimmed;
});
// Complete environment variable schema
const ENV_SCHEMA = z.object({
EXECUTING_CLIENT: z.enum(['cursor', 'clause']).optional(),
CURSOR_AGENT_PATH: executablePathSchema,
DEBUG_CURSOR_MCP: booleanEnvSchema,
CURSOR_AGENT_ECHO_PROMPT: booleanEnvSchema,
CURSOR_AGENT_MODEL: z.string().trim().min(1).optional(),
CURSOR_AGENT_FORCE: booleanEnvSchema,
CURSOR_AGENT_IDLE_EXIT_MS: positiveIntMsSchema,
CURSOR_AGENT_TIMEOUT_MS: positiveIntMsSchema,
});
// Validate and parse all environment variables (lazy validation with caching)
let validatedEnvCache = null;
let validatedEnvCacheKey = null;
let isStartup = true;
function getValidatedEnv() {
// Create a cache key from current env values
const cacheKey = JSON.stringify({
EXECUTING_CLIENT: process.env.EXECUTING_CLIENT,
CURSOR_AGENT_PATH: process.env.CURSOR_AGENT_PATH,
DEBUG_CURSOR_MCP: process.env.DEBUG_CURSOR_MCP,
CURSOR_AGENT_ECHO_PROMPT: process.env.CURSOR_AGENT_ECHO_PROMPT,
CURSOR_AGENT_MODEL: process.env.CURSOR_AGENT_MODEL,
CURSOR_AGENT_FORCE: process.env.CURSOR_AGENT_FORCE,
CURSOR_AGENT_IDLE_EXIT_MS: process.env.CURSOR_AGENT_IDLE_EXIT_MS,
CURSOR_AGENT_TIMEOUT_MS: process.env.CURSOR_AGENT_TIMEOUT_MS,
});
// Return cached result if env vars haven't changed
if (validatedEnvCache && validatedEnvCacheKey === cacheKey) {
return validatedEnvCache;
}
// Validate and cache
try {
validatedEnvCache = ENV_SCHEMA.parse({
EXECUTING_CLIENT: process.env.EXECUTING_CLIENT,
CURSOR_AGENT_PATH: process.env.CURSOR_AGENT_PATH,
DEBUG_CURSOR_MCP: process.env.DEBUG_CURSOR_MCP,
CURSOR_AGENT_ECHO_PROMPT: process.env.CURSOR_AGENT_ECHO_PROMPT,
CURSOR_AGENT_MODEL: process.env.CURSOR_AGENT_MODEL,
CURSOR_AGENT_FORCE: process.env.CURSOR_AGENT_FORCE,
CURSOR_AGENT_IDLE_EXIT_MS: process.env.CURSOR_AGENT_IDLE_EXIT_MS,
CURSOR_AGENT_TIMEOUT_MS: process.env.CURSOR_AGENT_TIMEOUT_MS,
});
validatedEnvCacheKey = cacheKey;
return validatedEnvCache;
} catch (error) {
// At startup, exit on invalid config. Otherwise, throw for tests/functions.
if (isStartup) {
console.error('Invalid environment variable configuration:', error.message);
if (error.errors) {
for (const err of error.errors) {
console.error(` - ${err.path.join('.')}: ${err.message}`);
}
}
process.exit(1);
}
// Re-throw the error for non-startup contexts (e.g., tests)
throw error;
}
}
// Validate at startup (will exit if invalid)
isStartup = true;
getValidatedEnv();
isStartup = false;
// Security validation utilities
/**
* Validates executable path to prevent arbitrary command execution.
* Only allows "cursor-agent" (for PATH lookup) or exact match to CURSOR_AGENT_PATH env var.
*/
function validateExecutablePath(explicit) {
const env = getValidatedEnv();
if (!explicit || !explicit.trim()) {
// No explicit path provided, check validated env var or default
const envPath = env.CURSOR_AGENT_PATH;
if (envPath) {
return envPath;
}
return 'cursor-agent';
}
const trimmed = explicit.trim();
// Allow "cursor-agent" for PATH lookup
if (trimmed === 'cursor-agent') {
return 'cursor-agent';
}
// Check if it matches CURSOR_AGENT_PATH exactly
const envPath = env.CURSOR_AGENT_PATH;
if (envPath && trimmed === envPath) {
return envPath;
}
// Reject all other paths (prevents arbitrary executable execution)
throw new Error(`Invalid executable path: "${trimmed}". Only "cursor-agent" or exact match to CURSOR_AGENT_PATH is allowed.`);
}
/**
* Validates working directory to prevent path traversal attacks.
* Ensures cwd is within process.cwd() or its subdirectories.
*/
function validateWorkingDirectory(cwd) {
if (!cwd || !cwd.trim()) {
return process.cwd();
}
const trimmed = cwd.trim();
const resolved = path.resolve(trimmed);
const baseDir = process.cwd();
const baseDirResolved = path.resolve(baseDir);
// Ensure resolved path is exactly the base directory or a subdirectory
// Use path.sep to prevent prefix attacks (e.g., "/home/user/repo-evil" should not pass)
if (resolved !== baseDirResolved && !resolved.startsWith(baseDirResolved + path.sep)) {
throw new Error(`Working directory "${trimmed}" is outside allowed path "${baseDir}"`);
}
// Check for path traversal attempts
const normalized = path.normalize(trimmed);
if (normalized.includes('..')) {
const normalizedResolved = path.resolve(normalized);
if (normalizedResolved !== baseDirResolved && !normalizedResolved.startsWith(baseDirResolved + path.sep)) {
throw new Error(`Working directory "${trimmed}" contains invalid path traversal`);
}
}
return resolved;
}
/**
* Validates file paths to prevent path traversal attacks.
* Ensures paths are within process.cwd() or its subdirectories.
*/
function validateFilePath(filePath) {
if (!filePath || !filePath.trim()) {
throw new Error('File path is required');
}
const trimmed = filePath.trim();
const resolved = path.resolve(trimmed);
const baseDir = process.cwd();
const baseDirResolved = path.resolve(baseDir);
// Ensure resolved path is exactly the base directory or a subdirectory
// Use path.sep to prevent prefix attacks (e.g., "/home/user/repo-evil" should not pass)
if (resolved !== baseDirResolved && !resolved.startsWith(baseDirResolved + path.sep)) {
throw new Error(`File path "${trimmed}" is outside allowed directory "${baseDir}"`);
}
// Check for path traversal attempts
const normalized = path.normalize(trimmed);
if (normalized.includes('..')) {
const normalizedResolved = path.resolve(normalized);
if (normalizedResolved !== baseDirResolved && !normalizedResolved.startsWith(baseDirResolved + path.sep)) {
throw new Error(`File path "${trimmed}" contains invalid path traversal`);
}
}
return resolved;
}
/**
* Creates a safe environment object with only whitelisted variables.
* Prevents leakage of sensitive credentials and secrets.
* Uses validated environment variables where applicable.
*/
function getSafeEnvironment() {
const whitelist = new Set([
// System variables
'PATH',
'HOME',
'USER',
'USERNAME',
'SHELL',
'TMPDIR',
'TEMP',
'TMP',
// Node.js variables
'NODE_VERSION',
// Locale variables
'LANG',
'LANGUAGE',
// MCP client identifier
'EXECUTING_CLIENT',
]);
// Add all CURSOR_AGENT_* variables
const cursorAgentPrefix = 'CURSOR_AGENT_';
// Add all NPM_CONFIG_* variables
const npmConfigPrefix = 'NPM_CONFIG_';
// Add all LC_* variables (locale categories)
const lcPrefix = 'LC_';
const safeEnv = {};
// Add validated environment variables (convert back to strings for env)
const env = getValidatedEnv();
if (env.EXECUTING_CLIENT) {
safeEnv.EXECUTING_CLIENT = env.EXECUTING_CLIENT;
}
if (env.CURSOR_AGENT_PATH) {
safeEnv.CURSOR_AGENT_PATH = env.CURSOR_AGENT_PATH;
}
// Preserve original string values for boolean env vars if they were valid
if (env.DEBUG_CURSOR_MCP) {
safeEnv.DEBUG_CURSOR_MCP = process.env.DEBUG_CURSOR_MCP || '1';
}
if (env.CURSOR_AGENT_ECHO_PROMPT) {
safeEnv.CURSOR_AGENT_ECHO_PROMPT = process.env.CURSOR_AGENT_ECHO_PROMPT || '1';
}
if (env.CURSOR_AGENT_MODEL) {
safeEnv.CURSOR_AGENT_MODEL = env.CURSOR_AGENT_MODEL;
}
if (env.CURSOR_AGENT_FORCE) {
safeEnv.CURSOR_AGENT_FORCE = process.env.CURSOR_AGENT_FORCE || '1';
}
if (env.CURSOR_AGENT_IDLE_EXIT_MS !== undefined) {
safeEnv.CURSOR_AGENT_IDLE_EXIT_MS = String(env.CURSOR_AGENT_IDLE_EXIT_MS);
}
if (env.CURSOR_AGENT_TIMEOUT_MS !== undefined) {
safeEnv.CURSOR_AGENT_TIMEOUT_MS = String(env.CURSOR_AGENT_TIMEOUT_MS);
}
// Add other whitelisted variables from process.env
for (const [key, value] of Object.entries(process.env)) {
if (
whitelist.has(key) ||
key.startsWith(cursorAgentPrefix) ||
key.startsWith(npmConfigPrefix) ||
key.startsWith(lcPrefix)
) {
// Only add if not already set from validated env
if (!(key in safeEnv)) {
safeEnv[key] = value;
}
}
}
return safeEnv;
}
// Export validation functions and core functions for testing
export {
validateExecutablePath,
validateWorkingDirectory,
validateFilePath,
getSafeEnvironment,
invokeCursorAgent,
runCursorAgent,
};
// Tool input schema
const RUN_SCHEMA = z.object({
prompt: z.string().min(1, 'prompt is required'),
output_format: z.enum(['text', 'json', 'markdown']).default('text'),
extra_args: z.array(z.string()).optional(),
cwd: z.string().optional(),
// Optional override for the executable path if not on PATH
executable: z.string().optional(),
// Optional model and force for parity with other tools/env overrides
model: z.string().optional(),
force: z.boolean().optional(),
});
// Resolve the executable path for cursor-agent
function resolveExecutable(explicit) {
return validateExecutablePath(explicit);
}
/**
* Internal executor that spawns cursor-agent with provided argv and common options.
* Adds --print and --output-format, handles env/model/force, timeouts and idle kill.
* Supports progress notifications when onProgress callback is provided.
* Supports cancellation via AbortSignal.
*/
async function invokeCursorAgent({ argv, output_format = 'text', cwd, executable, model, force, print = true, onProgress, signal }) {
const cmd = resolveExecutable(executable);
const validatedCwd = validateWorkingDirectory(cwd);
const safeEnv = getSafeEnvironment();
// Compute model/force from args/env
const env = getValidatedEnv();
const userArgs = [...(argv ?? [])];
const hasModelFlag = userArgs.some((a) => a === '-m' || a === '--model' || /^(?:-m=|--model=)/.test(String(a)));
const envModel = env.CURSOR_AGENT_MODEL;
const effectiveModel = model?.trim?.() || envModel;
const hasForceFlag = userArgs.some((a) => a === '-f' || a === '--force');
const envForce = env.CURSOR_AGENT_FORCE;
const effectiveForce = typeof force === 'boolean' ? force : envForce;
// Extract prompt (last non-flag argument) to ensure it's the final argument
let promptArg = null;
let argsWithoutPrompt = userArgs;
if (userArgs.length > 0) {
const lastArg = userArgs[userArgs.length - 1];
// If last argument doesn't start with '-', treat it as the prompt
if (lastArg && typeof lastArg === 'string' && !lastArg.startsWith('-')) {
promptArg = lastArg;
argsWithoutPrompt = userArgs.slice(0, -1);
}
}
// If progress is requested, use stream-json format for parsing
const useStreamJson = !!onProgress;
const finalOutputFormat = useStreamJson ? 'stream-json' : output_format;
const finalArgv = [
...(print ? ['--print', '--output-format', finalOutputFormat] : []),
...(useStreamJson && print ? ['--stream-partial-output'] : []), // Enable incremental deltas
...argsWithoutPrompt,
...(hasForceFlag || !effectiveForce ? [] : ['-f']),
...(hasModelFlag || !effectiveModel ? [] : ['--model', effectiveModel]),
...(promptArg ? [promptArg] : []),
];
return new Promise((resolve) => {
let settled = false;
let out = '';
let err = '';
let idleTimer = null;
let mainTimer = null;
let killedByIdle = false;
// State for stream-json parsing
let accumulatedText = '';
let toolCount = 0;
let partialLine = ''; // Buffer for incomplete JSON lines
let pendingAssistantProgress = false; // Track if we have unsent assistant progress
// Arrays to accumulate progress messages and events for logging
const progressMessages = [];
const events = [];
// Pre-compute log file path if we'll be using stream-json
let streamLogFilePath = null;
let streamLogFilename = null;
if (useStreamJson) {
// Generate filename once to ensure consistency
streamLogFilename = `cursor-agent-stream-${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
try {
const tempDir = os.tmpdir();
streamLogFilePath = path.join(tempDir, streamLogFilename);
console.info(`[cursor-mcp] Stream log file: ${streamLogFilePath}`);
} catch (e) {
// If we can't create the path now, writeStreamLog will handle it later
}
}
// Helper to write stream log to temp file (full JSON events for optional inspection)
const writeStreamLog = () => {
if (!useStreamJson || events.length === 0) return null;
try {
const filePath = streamLogFilePath || (() => {
const tempDir = os.tmpdir();
const filename = streamLogFilename || `cursor-agent-stream-${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
return path.join(tempDir, filename);
})();
const lines = events.map(e => JSON.stringify(e));
const content = lines.join('\n') + '\n';
fs.writeFileSync(filePath, content, 'utf8');
return {
path: filePath,
eventCount: events.length,
sizeBytes: Buffer.byteLength(content, 'utf8')
};
} catch (e) {
if (debugEnv2.DEBUG_CURSOR_MCP) {
try {
console.error('[cursor-mcp] failed to write stream log:', e);
} catch {}
}
return null;
}
};
// Format stream log reference with size info and optional warning
const formatStreamLogRef = (streamLog) => {
if (!streamLog) return '';
const sizeKB = (streamLog.sizeBytes / 1024).toFixed(1);
const isLarge = streamLog.eventCount > 50 || streamLog.sizeBytes > 50000;
let ref = `\n\n---\nFull stream log: ${streamLog.path} (${streamLog.eventCount} events, ${sizeKB}KB)`;
if (isLarge) {
ref += `\n⚠️ Large log - use semantic search or grep instead of reading entire file if more details are needed`;
}
return ref;
};
const debugEnv2 = getValidatedEnv();
if (debugEnv2.DEBUG_CURSOR_MCP) {
try {
console.info('[cursor-mcp] spawn:', cmd, ...finalArgv);
} catch {}
}
const child = spawn(cmd, finalArgv, {
shell: false, // safer across platforms; rely on PATH/PATHEXT
cwd: validatedCwd,
env: safeEnv,
});
try { child.stdin?.end(); } catch {}
// Abort handler for cancellation (defined after child is created)
const onAbort = () => {
if (settled) return;
settled = true;
cleanup();
try { child.kill('SIGKILL'); } catch {}
const streamLog = writeStreamLog();
const reason = signal?.reason || 'Request cancelled';
// Include any partial response accumulated before cancellation
const partialResponse = (useStreamJson && accumulatedText) ? `\nPartial response:\n${accumulatedText}` : '';
const baseText = `cursor-agent cancelled: ${reason}${partialResponse}`;
const finalText = baseText + formatStreamLogRef(streamLog);
resolve({
content: [{ type: 'text', text: finalText }],
isError: true,
...(streamLog && { streamLogFile: streamLog.path })
});
};
const cleanup = () => {
if (mainTimer) clearTimeout(mainTimer);
if (idleTimer) clearTimeout(idleTimer);
if (signal) {
signal.removeEventListener('abort', onAbort);
}
};
// Check if already aborted before setting up listener
if (signal?.aborted) {
onAbort();
return;
}
// Set up abort listener if signal is provided
if (signal) {
signal.addEventListener('abort', onAbort);
}
const idleEnv = getValidatedEnv();
const idleMs = idleEnv.CURSOR_AGENT_IDLE_EXIT_MS ?? 0;
const scheduleIdleKill = () => {
if (!idleMs || idleMs <= 0) return;
if (idleTimer) clearTimeout(idleTimer);
idleTimer = setTimeout(() => {
killedByIdle = true;
try { child.kill('SIGKILL'); } catch {}
}, idleMs);
};
// Helper to format events as human-readable messages
const formatEventMessage = (event) => {
if (!event || typeof event !== 'object') return 'Unknown event';
const { type, subtype } = event;
switch (type) {
case 'system':
if (subtype === 'init') {
const modelName = event.model || 'unknown';
return `System initialized with model: ${modelName}`;
}
return `System event: ${subtype || 'unknown'}`;
case 'assistant':
return 'Assistant message received';
case 'tool_call':
if (subtype === 'started') {
const toolCall = event.tool_call;
if (toolCall?.writeToolCall) {
const filePath = toolCall.writeToolCall?.args?.path || 'unknown';
return `Tool call started: writeToolCall(path: ${filePath})`;
} else if (toolCall?.readToolCall) {
const filePath = toolCall.readToolCall?.args?.path || 'unknown';
return `Tool call started: readToolCall(path: ${filePath})`;
} else {
return `Tool call started: ${toolCall?.name || 'unknown'}`;
}
} else if (subtype === 'completed') {
const toolCall = event.tool_call;
if (toolCall?.writeToolCall?.result?.success) {
const { linesCreated, fileSize } = toolCall.writeToolCall.result.success;
return `Tool call completed: writeToolCall (${linesCreated || 0} lines, ${fileSize || 0} bytes)`;
} else if (toolCall?.readToolCall?.result?.success) {
const { totalLines } = toolCall.readToolCall.result.success;
return `Tool call completed: readToolCall (${totalLines || 0} lines)`;
} else {
return `Tool call completed: ${toolCall?.name || 'unknown'}`;
}
}
return `Tool call: ${subtype || 'unknown'}`;
case 'result':
const duration = event.duration_ms || 0;
return `Result: completed in ${duration}ms`;
default:
return `Event: ${type}${subtype ? ` (${subtype})` : ''}`;
}
};
// Helper to flush pending assistant progress before sending other updates
const flushPendingAssistantProgress = () => {
if (pendingAssistantProgress && accumulatedText && onProgress) {
onProgress({
progress: accumulatedText.length,
message: `Response generated: (${accumulatedText.length} characters)`
});
pendingAssistantProgress = false;
}
};
// Helper to handle stream-json events
const handleStreamEvent = (event) => {
if (!event || typeof event !== 'object') return;
const { type, subtype } = event;
const timestamp = new Date().toISOString();
// Store raw event for logging
events.push(event);
try {
switch (type) {
case 'system':
if (subtype === 'init') {
const modelName = event.model || 'unknown';
const progressMsg = `Initializing cursor-agent (model: ${modelName})...`;
progressMessages.push({ timestamp, type: 'PROGRESS', message: progressMsg });
if (onProgress) {
onProgress({
progress: 0,
message: progressMsg
});
}
}
break;
case 'assistant':
// Accumulate text deltas from streaming output
const text = event.message?.content?.[0]?.text || '';
if (text) {
// Log the delta directly (not accumulated) for the log file
progressMessages.push({ timestamp, type: 'PROGRESS', message: text });
// Continue accumulating for onProgress callback
accumulatedText += text;
// Mark that we have pending progress, but don't send it yet
pendingAssistantProgress = true;
}
break;
case 'tool_call':
if (subtype === 'started') {
// Flush any pending assistant progress before tool call update
flushPendingAssistantProgress();
toolCount++;
const toolCall = event.tool_call;
// Log the stream log file location when the first tool call starts
if (toolCount === 1 && streamLogFilename) {
const logPath = streamLogFilePath || (() => {
try {
const tempDir = os.tmpdir();
return path.join(tempDir, streamLogFilename);
} catch (e) {
return streamLogFilename;
}
})();
console.log(`[cursor-mcp] Stream log file: ${logPath}`);
}
let progressMsg = '';
if (toolCall?.writeToolCall) {
const path = toolCall.writeToolCall?.args?.path || 'unknown';
progressMsg = `Writing file: ${path}`;
} else if (toolCall?.readToolCall) {
const path = toolCall.readToolCall?.args?.path || 'unknown';
progressMsg = `Reading file: ${path}`;
} else {
progressMsg = `Executing tool #${toolCount}...`;
}
progressMessages.push({ timestamp, type: 'PROGRESS', message: progressMsg });
if (onProgress) {
onProgress({
progress: toolCount,
message: progressMsg
});
}
} else if (subtype === 'completed') {
const toolCall = event.tool_call;
let progressMsg = '';
if (toolCall?.writeToolCall?.result?.success) {
const { linesCreated, fileSize } = toolCall.writeToolCall.result.success;
progressMsg = `✅ Created ${linesCreated || 0} lines (${fileSize || 0} bytes)`;
} else if (toolCall?.readToolCall?.result?.success) {
const { totalLines } = toolCall.readToolCall.result.success;
progressMsg = `✅ Read ${totalLines || 0} lines`;
} else if (toolCall?.writeToolCall?.result || toolCall?.readToolCall?.result) {
progressMsg = `✅ Tool #${toolCount} completed`;
}
if (progressMsg) {
progressMessages.push({ timestamp, type: 'PROGRESS', message: progressMsg });
if (onProgress) {
onProgress({
progress: toolCount,
message: progressMsg
});
}
}
}
break;
case 'result':
// Flush any pending assistant progress before result update
flushPendingAssistantProgress();
const duration = event.duration_ms || 0;
const resultProgressMsg = `Completed in ${duration}ms`;
progressMessages.push({ timestamp, type: 'PROGRESS', message: resultProgressMsg });
if (onProgress) {
onProgress({
progress: 100,
total: 100,
message: resultProgressMsg
});
}
break;
}
} catch (e) {
// Silently ignore errors in progress handling to avoid breaking the main flow
if (debugEnv2.DEBUG_CURSOR_MCP) {
try {
console.error('[cursor-mcp] progress error:', e);
} catch {}
}
}
};
child.stdout.on('data', (d) => {
const chunk = d.toString();
out += chunk;
scheduleIdleKill();
if (useStreamJson && onProgress) {
// Parse JSON lines from stream-json output
const data = partialLine + chunk;
const lines = data.split('\n');
// Keep the last line as it might be incomplete
partialLine = lines.pop() || '';
// Process complete lines
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
try {
const event = JSON.parse(trimmed);
handleStreamEvent(event);
} catch (e) {
// Not valid JSON - might be partial or malformed, skip it
if (debugEnv2.DEBUG_CURSOR_MCP) {
try {
const preview = trimmed.length > 200 ? trimmed.slice(0, 200) + '...' : trimmed;
const errorMsg = e instanceof Error ? e.message : String(e);
const stack = e instanceof Error ? e.stack : undefined;
console.error(`[cursor-mcp] Failed to parse JSON line (${errorMsg}):`, preview);
if (stack) {
console.error('[cursor-mcp] Stack trace:', stack);
}
} catch {}
}
}
}
} else if (onProgress) {
// Simple progress for non-streaming formats
const timestamp = new Date().toISOString();
const progressMsg = `Received ${out.length} bytes of output...`;
progressMessages.push({ timestamp, type: 'PROGRESS', message: progressMsg });
onProgress({
progress: out.length,
message: progressMsg
});
}
});
child.stderr.on('data', (d) => {
err += d.toString();
// Don't send progress notifications for stderr - just collect it
// It will be included in the final result if there's an error
});
child.on('error', (e) => {
if (settled) return;
settled = true;
cleanup();
const errorEnv = getValidatedEnv();
if (errorEnv.DEBUG_CURSOR_MCP) {
try { console.error('[cursor-mcp] error:', e); } catch {}
}
const msg =
`Failed to start "${cmd}": ${e?.message || e}\n` +
`Args: ${JSON.stringify(finalArgv)}\n` +
(safeEnv.CURSOR_AGENT_PATH ? `CURSOR_AGENT_PATH=${safeEnv.CURSOR_AGENT_PATH}\n` : '');
const streamLog = writeStreamLog();
const finalText = msg + formatStreamLogRef(streamLog);
resolve({
content: [{ type: 'text', text: finalText }],
isError: true,
...(streamLog && { streamLogFile: streamLog.path })
});
});
const defaultTimeout = 30000;
const timeoutEnv2 = getValidatedEnv();
const timeoutMs = timeoutEnv2.CURSOR_AGENT_TIMEOUT_MS ?? defaultTimeout;
mainTimer = setTimeout(() => {
try { child.kill('SIGKILL'); } catch {}
if (settled) return;
settled = true;
cleanup();
const streamLog = writeStreamLog();
// Include any partial response accumulated before timeout
const partialResponse = (useStreamJson && accumulatedText) ? `\nPartial response:\n${accumulatedText}` : '';
const baseText = `cursor-agent timed out after ${timeoutMs}ms${partialResponse}`;
const finalText = baseText + formatStreamLogRef(streamLog);
resolve({
content: [{ type: 'text', text: finalText }],
isError: true,
...(streamLog && { streamLogFile: streamLog.path })
});
}, timeoutMs);
child.on('close', (code) => {
if (settled) return;
settled = true;
cleanup();
// Process any remaining partial line
if (useStreamJson && onProgress && partialLine.trim()) {
try {
const event = JSON.parse(partialLine.trim());
handleStreamEvent(event);
} catch {}
}
// Flush any pending assistant progress before closing
flushPendingAssistantProgress();
const closeEnv = getValidatedEnv();
if (closeEnv.DEBUG_CURSOR_MCP) {
try { console.error('[cursor-mcp] exit:', code, 'stdout bytes=', out.length, 'stderr bytes=', err.length); } catch {}
}
const streamLog = writeStreamLog();
if (code === 0 || (killedByIdle && out)) {
// When using stream-json parsing, return only the accumulated final text
// The full stream is saved to a file for optional inspection
const baseText = (useStreamJson && accumulatedText)
? accumulatedText
: (out || '(no output)');
const finalText = baseText + formatStreamLogRef(streamLog);
resolve({
content: [{ type: 'text', text: finalText }],
...(streamLog && { streamLogFile: streamLog.path })
});
} else {
// On error, prefer accumulated text if available, otherwise raw output
const baseText = (useStreamJson && accumulatedText)
? `cursor-agent exited with code ${code}\n${accumulatedText}`
: `cursor-agent exited with code ${code}\n${err || out || '(no output)'}`;
const finalText = baseText + formatStreamLogRef(streamLog);
resolve({
content: [{ type: 'text', text: finalText }],
isError: true,
...(streamLog && { streamLogFile: streamLog.path })
});
}
});
});
}
// Back-compat: single-shot run by prompt as positional argument.
// Accepts either a flat args object or an object with an "arguments" field (some hosts).
async function runCursorAgent(input, onProgress, signal) {
const source = (input && typeof input === 'object' && input.arguments && typeof input.prompt === 'undefined')
? input.arguments
: input;
const {
prompt,
output_format = 'text',
extra_args,
cwd,
executable,
model,
force,
} = source || {};
const argv = [...(extra_args ?? []), String(prompt)];
const usedPrompt = argv.length ? String(argv[argv.length - 1]) : '';
// Optional prompt echo and debug diagnostics
const debugEnv = getValidatedEnv();
if (debugEnv.DEBUG_CURSOR_MCP) {
try {
const preview = usedPrompt.slice(0, 400).replace(/\n/g, '\\n');
console.debug('[cursor-mcp] prompt:', preview);
if (extra_args?.length) console.debug('[cursor-mcp] extra_args:', JSON.stringify(extra_args));
if (model) console.debug('[cursor-mcp] model:', model);
if (typeof force === 'boolean') console.debug('[cursor-mcp] force:', String(force));
} catch {}
}
const result = await invokeCursorAgent({ argv, output_format, cwd, executable, model, force, onProgress, signal });
// Echo prompt either when env is set or when caller provided echo_prompt: true (if host forwards unknown args it's fine)
const echoEnv = getValidatedEnv();
const echoEnabled = echoEnv.CURSOR_AGENT_ECHO_PROMPT || source?.echo_prompt === true;
if (echoEnabled) {
const text = `Prompt used:\n${usedPrompt}`;
const content = Array.isArray(result?.content) ? result.content : [];
return { ...result, content: [{ type: 'text', text }, ...content] };
}
return result;
}
// Helper to create progress callback from extra context
function createProgressCallback(extra) {
const progressToken = extra?._meta?.progressToken;
const sendNotification = extra?.sendNotification;
if (!progressToken || !sendNotification) {
return undefined;
}
return async (progress) => {
try {
await sendNotification({
method: 'notifications/progress',
params: {
progressToken,
progress: progress.progress,
total: progress.total,
message: progress.message
}
});
} catch (e) {
// Silently ignore progress notification errors
const debugEnv = getValidatedEnv();
if (debugEnv.DEBUG_CURSOR_MCP) {
try {
console.error('[cursor-mcp] progress notification error:', e);
} catch {}
}
}
};
}
// Use validated EXECUTING_CLIENT environment variable
const executingClient = getValidatedEnv().EXECUTING_CLIENT;
/**
* Create MCP server and register a suite of cursor-agent tools.
* We expose multiple verbs for better discoverability in hosts (chat/edit/analyze/search/plan),
* plus the legacy cursor_agent_run for back-compat and a raw escape hatch.
*/
const server = new McpServer(
{
name: 'cursor-agent',
version: '1.1.0',
description: 'MCP wrapper for cursor-agent CLI (multi-tool: chat/edit/analyze/search/plan/raw)',
},
{
instructions:
executingClient === 'cursor'
? [
'Tools:',
'- cursor_agent_chat: chat with a prompt; optional model/force/format.',
'- cursor_agent_raw: pass raw argv directly to cursor-agent; set print=false to avoid implicit --print.',
].join('\n')
: [
'Tools:',
'- cursor_agent_chat: chat with a prompt; optional model/force/format.',
'- cursor_agent_edit_file: prompt-based file edit wrapper; you provide file and instruction.',
'- cursor_agent_analyze_files: prompt-based analysis of one or more paths.',
'- cursor_agent_search_repo: prompt-based code search with include/exclude globs.',
'- cursor_agent_plan_task: prompt-based planning given a goal and optional constraints.',
'- cursor_agent_raw: pass raw argv directly to cursor-agent; set print=false to avoid implicit --print.',
'- cursor_agent_run: legacy single-shot chat (prompt as positional).',
].join('\n'),
},
);
// Common shape used by multiple schemas
const COMMON = {
output_format: z.enum(['text', 'json', 'markdown']).default('text'),
extra_args: z.array(z.string()).optional(),
cwd: z.string().optional(),
executable: z.string().optional(),
model: z.string().optional(),
force: z.boolean().optional(),
// When true, the server will prepend the effective prompt to the tool output (useful for Claude debugging)
echo_prompt: z.boolean().optional(),
};
// Schemas
const CHAT_SCHEMA = z.object({
prompt: z.string().min(1, 'prompt is required'),
...COMMON,
});
const EDIT_FILE_SCHEMA = z.object({
file: z.string().min(1, 'file is required'),
instruction: z.string().min(1, 'instruction is required'),
apply: z.boolean().optional(),
dry_run: z.boolean().optional(),
// optional free-form prompt to pass if the CLI supports one
prompt: z.string().optional(),
...COMMON,
});
const ANALYZE_FILES_SCHEMA = z.object({
paths: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]),
prompt: z.string().optional(),
...COMMON,
});
const SEARCH_REPO_SCHEMA = z.object({
query: z.string().min(1, 'query is required'),
include: z.union([z.string(), z.array(z.string())]).optional(),
exclude: z.union([z.string(), z.array(z.string())]).optional(),
...COMMON,
});
const PLAN_TASK_SCHEMA = z.object({
goal: z.string().min(1, 'goal is required'),
constraints: z.array(z.string()).optional(),
...COMMON,
});