Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
1545 lines (1317 loc) · 74.8 KB
/
Copy pathserver.ts
File metadata and controls
1545 lines (1317 loc) · 74.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
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
ListResourcesRequestSchema,
ReadResourceRequestSchema,
ListResourceTemplatesRequestSchema,
ListPromptsRequestSchema,
InitializeRequestSchema,
LATEST_PROTOCOL_VERSION,
SUPPORTED_PROTOCOL_VERSIONS,
type CallToolRequest,
type InitializeRequest,
} from "@modelcontextprotocol/sdk/types.js";
import { zodToJsonSchema } from "zod-to-json-schema";
import { getSystemInfo, getOSSpecificGuidance, getPathGuidance, getDevelopmentToolGuidance } from './utils/system-info.js';
// Get system information once at startup
const SYSTEM_INFO = getSystemInfo();
const OS_GUIDANCE = getOSSpecificGuidance(SYSTEM_INFO);
const DEV_TOOL_GUIDANCE = getDevelopmentToolGuidance(SYSTEM_INFO);
const PATH_GUIDANCE = `IMPORTANT: ${getPathGuidance(SYSTEM_INFO)} Relative paths may fail as they depend on the current working directory. Tilde paths (~/...) might not work in all contexts. Unless the user explicitly asks for relative paths, use absolute paths.`;
const CMD_PREFIX_DESCRIPTION = `This command can be referenced as "DC: ..." or "use Desktop Commander to ..." in your instructions.`;
import {
StartProcessArgsSchema,
ReadProcessOutputArgsSchema,
InteractWithProcessArgsSchema,
ForceTerminateArgsSchema,
ListSessionsArgsSchema,
KillProcessArgsSchema,
ReadFileArgsSchema,
ReadMultipleFilesArgsSchema,
WriteFileArgsSchema,
CreateDirectoryArgsSchema,
ListDirectoryArgsSchema,
MoveFileArgsSchema,
GetFileInfoArgsSchema,
GetConfigArgsSchema,
SetConfigValueArgsSchema,
ListProcessesArgsSchema,
EditBlockArgsSchema,
GetUsageStatsArgsSchema,
GiveFeedbackArgsSchema,
StartSearchArgsSchema,
GetMoreSearchResultsArgsSchema,
StopSearchArgsSchema,
ListSearchesArgsSchema,
GetPromptsArgsSchema,
GetRecentToolCallsArgsSchema,
WritePdfArgsSchema,
} from './tools/schemas.js';
import { getConfig, setConfigValue } from './tools/config.js';
import { getUsageStats } from './tools/usage.js';
import { giveFeedbackToDesktopCommander } from './tools/feedback.js';
import { getPrompts } from './tools/prompts.js';
import { trackToolCall } from './utils/trackTools.js';
import { usageTracker } from './utils/usageTracker.js';
import { processDockerPrompt } from './utils/dockerPrompt.js';
import { toolHistory } from './utils/toolHistory.js';
import { handleWelcomePageOnboarding } from './utils/welcome-onboarding.js';
import { VERSION } from './version.js';
import { capture, capture_call_tool } from "./utils/capture.js";
import { logToStderr, logger } from './utils/logger.js';
import {
buildUiToolMeta,
FILE_PREVIEW_RESOURCE_URI
} from './ui/contracts.js';
import { listUiResources, readUiResource } from './ui/resources.js';
// Store startup messages to send after initialization
const deferredMessages: Array<{ level: string, message: string }> = [];
function deferLog(level: string, message: string) {
deferredMessages.push({ level, message });
}
// Function to flush deferred messages after initialization
export function flushDeferredMessages() {
while (deferredMessages.length > 0) {
const msg = deferredMessages.shift()!;
logger.info(msg.message);
}
}
deferLog('info', 'Loading server.ts');
export const server = new Server(
{
name: "desktop-commander",
version: VERSION,
},
{
capabilities: {
tools: {},
resources: {}, // Add empty resources capability
prompts: {}, // Add empty prompts capability
logging: {}, // Add logging capability for console redirection
},
},
);
// Add handler for resources/list method
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: listUiResources(),
};
});
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const { uri } = request.params;
const response = await readUiResource(uri);
if (response) {
return response;
}
throw new Error(`Unknown resource URI: ${uri}`);
});
// Add handler for prompts/list method
server.setRequestHandler(ListPromptsRequestSchema, async () => {
// Return an empty list of prompts
return {
prompts: [],
};
});
// Store current client info (simple variable)
let currentClient = { name: 'uninitialized', version: 'uninitialized' };
/**
* Unified way to update client information
*/
async function updateCurrentClient(clientInfo: { name?: string, version?: string }) {
if (clientInfo.name !== currentClient.name || clientInfo.version !== currentClient.version) {
const nameChanged = clientInfo.name !== currentClient.name;
currentClient = {
name: clientInfo.name || currentClient.name,
version: clientInfo.version || currentClient.version
};
// Configure transport for client-specific behavior only if name changed
if (nameChanged) {
const transport = (global as any).mcpTransport;
if (transport && typeof transport.configureForClient === 'function') {
transport.configureForClient(currentClient.name);
}
}
return true;
}
return false;
}
// Add handler for initialization method - capture client info
server.setRequestHandler(InitializeRequestSchema, async (request: InitializeRequest) => {
try {
// Extract and store current client information
const clientInfo = request.params?.clientInfo;
if (clientInfo) {
await updateCurrentClient(clientInfo);
// Welcome page for new claude-ai users (A/B test controlled)
// Also matches 'local-agent-mode-*' which is how Claude.ai connectors report themselves
if ((currentClient.name === 'claude-ai' || currentClient.name?.startsWith('local-agent-mode')) && !(global as any).disableOnboarding) {
await handleWelcomePageOnboarding();
}
}
capture('run_server_mcp_initialized');
// Negotiate protocol version with client
const requestedVersion = request.params?.protocolVersion;
const protocolVersion = (requestedVersion && SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion))
? requestedVersion
: LATEST_PROTOCOL_VERSION;
// Return standard initialization response
return {
protocolVersion,
capabilities: {
tools: {},
resources: {},
prompts: {},
logging: {},
},
serverInfo: {
name: "desktop-commander",
version: VERSION,
},
};
} catch (error) {
logToStderr('error', `Error in initialization handler: ${error}`);
throw error;
}
});
// Export current client info for access by other modules
export { currentClient };
deferLog('info', 'Setting up request handlers...');
/**
* Check if a tool should be included based on current client
*/
function shouldIncludeTool(toolName: string): boolean {
// Exclude give_feedback_to_desktop_commander for desktop-commander client
if (toolName === 'give_feedback_to_desktop_commander' && currentClient?.name === 'desktop-commander') {
return false;
}
// Add more conditional tool logic here as needed
// Example: if (toolName === 'some_tool' && currentClient?.name === 'some_client') return false;
return true;
}
server.setRequestHandler(ListToolsRequestSchema, async () => {
try {
// logToStderr('debug', 'Generating tools list...');
// Build complete tools array
const allTools = [
// Configuration tools
{
name: "get_config",
description: `
Get the complete server configuration as JSON. Config includes fields for:
- blockedCommands (array of blocked shell commands)
- defaultShell (shell to use for commands)
- allowedDirectories (paths the server can access)
- fileReadLineLimit (max lines for read_file, default 1000)
- fileWriteLineLimit (max lines per write_file call, default 50)
- telemetryEnabled (boolean for telemetry opt-in/out)
- currentClient (information about the currently connected MCP client)
- clientHistory (history of all clients that have connected)
- version (version of the DesktopCommander)
- systemInfo (operating system and environment details)
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(GetConfigArgsSchema),
annotations: {
title: "Get Configuration",
readOnlyHint: true,
},
},
{
name: "set_config_value",
description: `
Set a specific configuration value by key.
WARNING: Should be used in a separate chat from file operations and
command execution to prevent security issues.
Config keys include:
- blockedCommands (array)
- defaultShell (string)
- allowedDirectories (array of paths)
- fileReadLineLimit (number, max lines for read_file)
- fileWriteLineLimit (number, max lines per write_file call)
- telemetryEnabled (boolean)
IMPORTANT: Setting allowedDirectories to an empty array ([]) allows full access
to the entire file system, regardless of the operating system.
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(SetConfigValueArgsSchema),
annotations: {
title: "Set Configuration Value",
readOnlyHint: false,
destructiveHint: true,
openWorldHint: false,
},
},
// Filesystem tools
{
name: "read_file",
description: `
Read contents from files and URLs.
Read PDF files and extract content as markdown and images.
Prefer this over 'execute_command' with cat/type for viewing files.
Supports partial file reading with:
- 'offset' (start line, default: 0)
* Positive: Start from line N (0-based indexing)
* Negative: Read last N lines from end (tail behavior)
- 'length' (max lines to read, default: configurable via 'fileReadLineLimit' setting, initially 1000)
* Used with positive offsets for range reading
* Ignored when offset is negative (reads all requested tail lines)
Examples:
- offset: 0, length: 10 → First 10 lines
- offset: 100, length: 5 → Lines 100-104
- offset: -20 → Last 20 lines
- offset: -5, length: 10 → Last 5 lines (length ignored)
Performance optimizations:
- Large files with negative offsets use reverse reading for efficiency
- Large files with deep positive offsets use byte estimation
- Small files use fast readline streaming
When reading from the file system, only works within allowed directories.
Can fetch content from URLs when isUrl parameter is set to true
(URLs are always read in full regardless of offset/length).
FORMAT HANDLING (by extension):
- Text: Uses offset/length for line-based pagination
- Excel (.xlsx, .xls, .xlsm): Returns JSON 2D array
* sheet: "Sheet1" (name) or "0" (index as string, 0-based)
* range: ALWAYS use FROM:TO format (e.g., "A1:D100", "C1:C1", "B2:B50")
* offset/length work as row pagination (optional fallback)
- Images (PNG, JPEG, GIF, WebP): Base64 encoded viewable content
- PDF: Extracts text content as markdown with page structure
* offset/length work as page pagination (0-based)
* Includes embedded images when available
- DOCX (.docx): Two modes depending on parameters:
* DEFAULT (no offset/length): Returns a text-bearing outline — shows paragraphs with text,
tables with cell content, styles, image refs. Skips shapes/drawings/SVG noise.
Each element shows its body index [0], [1], etc.
* WITH offset/length: Returns raw pretty-printed XML with line pagination.
Use this to drill into specific sections or see the actual XML for editing.
* EDITING WORKFLOW: 1) read_file to get outline, 2) read_file with offset/length
to see raw XML around what you want to edit, 3) edit_block with old_string/new_string
using XML fragments copied from the read output.
* IMPORTANT: offset MUST be non-zero to get raw XML (use offset=1 to start from line 1).
offset=0 always returns the outline regardless of length.
* For BULK changes (translation, mass replacements): use start_process with Python
zipfile module to find/replace all <w:t> elements at once.
${PATH_GUIDANCE}
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(ReadFileArgsSchema),
_meta: buildUiToolMeta(FILE_PREVIEW_RESOURCE_URI, true),
annotations: {
title: "Read File or URL",
readOnlyHint: true,
openWorldHint: true,
},
},
{
name: "read_multiple_files",
description: `
Read the contents of multiple files simultaneously.
Each file's content is returned with its path as a reference.
Handles text files normally and renders images as viewable content.
Recognized image types: PNG, JPEG, GIF, WebP.
Failed reads for individual files won't stop the entire operation.
Only works within allowed directories.
${PATH_GUIDANCE}
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(ReadMultipleFilesArgsSchema),
annotations: {
title: "Read Multiple Files",
readOnlyHint: true,
},
},
{
name: "write_file",
description: `
Write or append to file contents.
IMPORTANT: DO NOT use this tool to create PDF files. Use 'write_pdf' for all PDF creation tasks.
DO NOT use this tool to edit DOCX files. Use 'edit_block' with old_string/new_string instead.
To CREATE a new DOCX, use write_file with .docx extension — text content with markdown headings (#, ##, ###) is converted to styled DOCX paragraphs.
CHUNKING IS STANDARD PRACTICE: Always write files in chunks of 25-30 lines maximum.
This is the normal, recommended way to write files - not an emergency measure.
STANDARD PROCESS FOR ANY FILE:
1. FIRST → write_file(filePath, firstChunk, {mode: 'rewrite'}) [≤30 lines]
2. THEN → write_file(filePath, secondChunk, {mode: 'append'}) [≤30 lines]
3. CONTINUE → write_file(filePath, nextChunk, {mode: 'append'}) [≤30 lines]
ALWAYS CHUNK PROACTIVELY - don't wait for performance warnings!
WHEN TO CHUNK (always be proactive):
1. Any file expected to be longer than 25-30 lines
2. When writing multiple files in sequence
3. When creating documentation, code files, or configuration files
HANDLING CONTINUATION ("Continue" prompts):
If user asks to "Continue" after an incomplete operation:
1. Read the file to see what was successfully written
2. Continue writing ONLY the remaining content using {mode: 'append'}
3. Keep chunks to 25-30 lines each
FORMAT HANDLING (by extension):
- Text files: String content
- Excel (.xlsx, .xls, .xlsm): JSON 2D array or {"SheetName": [[...]]}
Example: '[["Name","Age"],["Alice",30]]'
Files over 50 lines will generate performance notes but are still written successfully.
Only works within allowed directories.
${PATH_GUIDANCE}
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(WriteFileArgsSchema),
annotations: {
title: "Write File",
readOnlyHint: false,
destructiveHint: true,
openWorldHint: false,
},
},
{
name: "write_pdf",
description: `
Create a new PDF file or modify an existing one.
THIS IS THE ONLY TOOL FOR CREATING AND MODIFYING PDF FILES.
RULES ABOUT FILENAMES:
- When creating a new PDF, 'outputPath' MUST be provided and MUST use a new unique filename (e.g., "result_01.pdf", "analysis_2025_01.pdf", etc.).
MODES:
1. CREATE NEW PDF:
- Pass a markdown string as 'content'.
write_pdf(path="doc.pdf", content="# Title\\n\\nBody text...")
2. MODIFY EXISTING PDF:
- Pass array of operations as 'content'.
- NEVER overwrite the original file.
- ALWAYS provide a new filename in 'outputPath'.
- After modifying, show original file path and new file path to user.
write_pdf(path="doc.pdf", content=[
{ type: "delete", pageIndexes: [0, 2] },
{ type: "insert", pageIndex: 1, markdown: "# New Page" }
])
OPERATIONS:
- delete: Remove pages by 0-based index.
{ type: "delete", pageIndexes: [0, 1, 5] }
- insert: Add pages at a specific 0-based index.
{ type: "insert", pageIndex: 0, markdown: "..." }
{ type: "insert", pageIndex: 5, sourcePdfPath: "/path/to/source.pdf" }
PAGE BREAKS:
To force a page break, use this HTML element:
<div style="page-break-before: always;"></div>
Example:
"# Page 1\\n\\n<div style=\\"page-break-before: always;\\"></div>\\n\\n# Page 2"
ADVANCED STYLING:
HTML/CSS and inline SVG are supported for:
- Text styling: colors, sizes, alignment, highlights
- Boxes: borders, backgrounds, padding, rounded corners
- SVG graphics: charts, diagrams, icons, shapes
- Images: <img src="/absolute/path/image.jpg" width="300" /> or 
Supports standard markdown features including headers, lists, code blocks, tables, and basic formatting.
Only works within allowed directories.
${PATH_GUIDANCE}
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(WritePdfArgsSchema),
annotations: {
title: "Write/Modify PDF",
readOnlyHint: false,
destructiveHint: true,
openWorldHint: false,
},
},
{
name: "create_directory",
description: `
Create a new directory or ensure a directory exists.
Can create multiple nested directories in one operation.
Only works within allowed directories.
${PATH_GUIDANCE}
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(CreateDirectoryArgsSchema),
annotations: {
title: "Create Directory",
readOnlyHint: false,
destructiveHint: false,
},
},
{
name: "list_directory",
description: `
Get a detailed listing of all files and directories in a specified path.
Use this instead of 'execute_command' with ls/dir commands.
Results distinguish between files and directories with [FILE] and [DIR] prefixes.
Supports recursive listing with the 'depth' parameter (default: 2):
- depth=1: Only direct contents of the directory
- depth=2: Contents plus one level of subdirectories
- depth=3+: Multiple levels deep
CONTEXT OVERFLOW PROTECTION:
- Top-level directory shows ALL items
- Nested directories are limited to 100 items maximum per directory
- When a nested directory has more than 100 items, you'll see a warning like:
[WARNING] node_modules: 500 items hidden (showing first 100 of 600 total)
- This prevents overwhelming the context with large directories like node_modules
Results show full relative paths from the root directory being listed.
Example output with depth=2:
[DIR] src
[FILE] src/index.ts
[DIR] src/tools
[FILE] src/tools/filesystem.ts
If a directory cannot be accessed, it will show [DENIED] instead.
Only works within allowed directories.
${PATH_GUIDANCE}
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(ListDirectoryArgsSchema),
annotations: {
title: "List Directory Contents",
readOnlyHint: true,
},
},
{
name: "move_file",
description: `
Move or rename files and directories.
Can move files between directories and rename them in a single operation.
Both source and destination must be within allowed directories.
${PATH_GUIDANCE}
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(MoveFileArgsSchema),
annotations: {
title: "Move/Rename File",
readOnlyHint: false,
destructiveHint: true,
openWorldHint: false,
},
},
{
name: "start_search",
description: `
Start a streaming search that can return results progressively.
SEARCH STRATEGY GUIDE:
Choose the right search type based on what the user is looking for:
USE searchType="files" WHEN:
- User asks for specific files: "find package.json", "locate config files"
- Pattern looks like a filename: "*.js", "README.md", "test-*.tsx"
- User wants to find files by name/extension: "all TypeScript files", "Python scripts"
- Looking for configuration/setup files: ".env", "dockerfile", "tsconfig.json"
USE searchType="content" WHEN:
- User asks about code/logic: "authentication logic", "error handling", "API calls"
- Looking for functions/variables: "getUserData function", "useState hook"
- Searching for text/comments: "TODO items", "FIXME comments", "documentation"
- Finding patterns in code: "console.log statements", "import statements"
- User describes functionality: "components that handle login", "files with database queries"
WHEN UNSURE OR USER REQUEST IS AMBIGUOUS:
Run TWO searches in parallel - one for files and one for content:
Example approach for ambiguous queries like "find authentication stuff":
1. Start file search: searchType="files", pattern="auth"
2. Simultaneously start content search: searchType="content", pattern="authentication"
3. Present combined results: "Found 3 auth-related files and 8 files containing authentication code"
SEARCH TYPES:
- searchType="files": Find files by name (pattern matches file names)
- searchType="content": Search inside files for text patterns
PATTERN MATCHING MODES:
- Default (literalSearch=false): Patterns are treated as regular expressions
- Literal (literalSearch=true): Patterns are treated as exact strings
WHEN TO USE literalSearch=true:
Use literal search when searching for code patterns with special characters:
- Function calls with parentheses and quotes
- Array access with brackets
- Object methods with dots and parentheses
- File paths with backslashes
- Any pattern containing: . * + ? ^ $ { } [ ] | \\ ( )
IMPORTANT PARAMETERS:
- pattern: What to search for (file names OR content text)
- literalSearch: Use exact string matching instead of regex (default: false)
- filePattern: Optional filter to limit search to specific file types (e.g., "*.js", "package.json")
- ignoreCase: Case-insensitive search (default: true). Works for both file names and content.
- earlyTermination: Stop search early when exact filename match is found (optional: defaults to true for file searches, false for content searches)
DECISION EXAMPLES:
- "find package.json" → searchType="files", pattern="package.json" (specific file)
- "find authentication components" → searchType="content", pattern="authentication" (looking for functionality)
- "locate all React components" → searchType="files", pattern="*.tsx" or "*.jsx" (file pattern)
- "find TODO comments" → searchType="content", pattern="TODO" (text in files)
- "show me login files" → AMBIGUOUS → run both: files with "login" AND content with "login"
- "find config" → AMBIGUOUS → run both: config files AND files containing config code
COMPREHENSIVE SEARCH EXAMPLES:
- Find package.json files: searchType="files", pattern="package.json"
- Find all JS files: searchType="files", pattern="*.js"
- Search for TODO in code: searchType="content", pattern="TODO", filePattern="*.js|*.ts"
- Search for exact code: searchType="content", pattern="toast.error('test')", literalSearch=true
- Ambiguous request "find auth stuff": Run two searches:
1. searchType="files", pattern="auth"
2. searchType="content", pattern="authentication"
PRO TIP: When user requests are ambiguous about whether they want files or content,
run both searches concurrently and combine results for comprehensive coverage.
Unlike regular search tools, this starts a background search process and returns
immediately with a session ID. Use get_more_search_results to get results as they
come in, and stop_search to stop the search early if needed.
Perfect for large directories where you want to see results immediately and
have the option to cancel if the search takes too long or you find what you need.
${PATH_GUIDANCE}
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(StartSearchArgsSchema),
annotations: {
title: "Start Search",
readOnlyHint: true,
},
},
{
name: "get_more_search_results",
description: `
Get more results from an active search with offset-based pagination.
Supports partial result reading with:
- 'offset' (start result index, default: 0)
* Positive: Start from result N (0-based indexing)
* Negative: Read last N results from end (tail behavior)
- 'length' (max results to read, default: 100)
* Used with positive offsets for range reading
* Ignored when offset is negative (reads all requested tail results)
Examples:
- offset: 0, length: 100 → First 100 results
- offset: 200, length: 50 → Results 200-249
- offset: -20 → Last 20 results
- offset: -5, length: 10 → Last 5 results (length ignored)
Returns only results in the specified range, along with search status.
Works like read_process_output - call this repeatedly to get progressive
results from a search started with start_search.
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(GetMoreSearchResultsArgsSchema),
annotations: {
title: "Get Search Results",
readOnlyHint: true,
},
},
{
name: "stop_search",
description: `
Stop an active search.
Stops the background search process gracefully. Use this when you've found
what you need or if a search is taking too long. Similar to force_terminate
for terminal processes.
The search will still be available for reading final results until it's
automatically cleaned up after 5 minutes.
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(StopSearchArgsSchema),
annotations: {
title: "Stop Search",
readOnlyHint: false,
destructiveHint: false,
},
},
{
name: "list_searches",
description: `
List all active searches.
Shows search IDs, search types, patterns, status, and runtime.
Similar to list_sessions for terminal processes. Useful for managing
multiple concurrent searches.
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(ListSearchesArgsSchema),
annotations: {
title: "List Active Searches",
readOnlyHint: true,
},
},
{
name: "get_file_info",
description: `
Retrieve detailed metadata about a file or directory including:
- size
- creation time
- last modified time
- permissions
- type
- lineCount (for text files)
- lastLine (zero-indexed number of last line, for text files)
- appendPosition (line number for appending, for text files)
- sheets (for Excel files - array of {name, rowCount, colCount})
Only works within allowed directories.
${PATH_GUIDANCE}
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(GetFileInfoArgsSchema),
annotations: {
title: "Get File Information",
readOnlyHint: true,
},
},
// Note: list_allowed_directories removed - use get_config to check allowedDirectories
// Editing tools
{
name: "edit_block",
description: `
Apply surgical edits to files.
BEST PRACTICE: Make multiple small, focused edits rather than one large edit.
Each edit_block call should change only what needs to be changed - include just enough
context to uniquely identify the text being modified.
FORMAT HANDLING (by extension):
EXCEL FILES (.xlsx, .xls, .xlsm) - Range Update mode:
Takes:
- file_path: Path to the Excel file
- range: ALWAYS use FROM:TO format - "SheetName!A1:C10" or "SheetName!C1:C1"
- content: 2D array, e.g., [["H1","H2"],["R1","R2"]]
TEXT FILES - Find/Replace mode:
Takes:
- file_path: Path to the file to edit
- old_string: Text to replace
- new_string: Replacement text
- expected_replacements: Optional number of replacements (default: 1)
DOCX FILES (.docx) - XML Find/Replace mode:
Takes same parameters as text files (old_string, new_string, expected_replacements).
Operates on the pretty-printed XML inside the DOCX — the same XML you see from
read_file with offset/length. Copy XML fragments from read output as old_string.
After editing, the XML is repacked into a valid DOCX.
Also searches headers/footers if not found in document body.
Examples:
- Replace text: old_string="<w:t>Old Text</w:t>" new_string="<w:t>New Text</w:t>"
- Change style: old_string='<w:pStyle w:val="Normal"/>' new_string='<w:pStyle w:val="Heading1"/>'
- Add content: include surrounding XML context in old_string, add new elements in new_string
By default, replaces only ONE occurrence of the search text.
To replace multiple occurrences, provide expected_replacements with
the exact number of matches expected.
UNIQUENESS REQUIREMENT: When expected_replacements=1 (default), include the minimal
amount of context necessary (typically 1-3 lines) before and after the change point,
with exact whitespace and indentation.
When editing multiple sections, make separate edit_block calls for each distinct change
rather than one large replacement.
When a close but non-exact match is found, a character-level diff is shown in the format:
common_prefix{-removed-}{+added+}common_suffix to help you identify what's different.
Similar to write_file, there is a configurable line limit (fileWriteLineLimit) that warns
if the edited file exceeds this limit. If this happens, consider breaking your edits into
smaller, more focused changes.
${PATH_GUIDANCE}
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(EditBlockArgsSchema),
annotations: {
title: "Edit Block",
readOnlyHint: false,
destructiveHint: true,
openWorldHint: false,
},
},
// Terminal tools
{
name: "start_process",
description: `
Start a new terminal process with intelligent state detection.
PRIMARY TOOL FOR FILE ANALYSIS AND DATA PROCESSING
This is the ONLY correct tool for analyzing local files (CSV, JSON, logs, etc.).
The analysis tool CANNOT access local files and WILL FAIL - always use processes for file-based work.
CRITICAL RULE: For ANY local file work, ALWAYS use this tool + interact_with_process, NEVER use analysis/REPL tool.
${OS_GUIDANCE}
REQUIRED WORKFLOW FOR LOCAL FILES:
1. start_process("python3 -i") - Start Python REPL for data analysis
2. interact_with_process(pid, "import pandas as pd, numpy as np")
3. interact_with_process(pid, "df = pd.read_csv('/absolute/path/file.csv')")
4. interact_with_process(pid, "print(df.describe())")
5. Continue analysis with pandas, matplotlib, seaborn, etc.
COMMON FILE ANALYSIS PATTERNS:
• start_process("python3 -i") → Python REPL for data analysis (RECOMMENDED)
• start_process("node -i") → Node.js REPL for JSON processing
• start_process("node:local") → Node.js on MCP server (stateless, ES imports, all code in one call)
• start_process("cut -d',' -f1 file.csv | sort | uniq -c") → Quick CSV analysis
• start_process("wc -l /path/file.csv") → Line counting
• start_process("head -10 /path/file.csv") → File preview
BINARY FILE SUPPORT:
For PDF, Excel, Word, archives, databases, and other binary formats, use process tools with appropriate libraries or command-line utilities.
INTERACTIVE PROCESSES FOR DATA ANALYSIS:
For code/calculations, use in this priority order:
1. start_process("python3 -i") - Python REPL (preferred)
2. start_process("node -i") - Node.js REPL (when Python unavailable)
3. start_process("node:local") - Node.js fallback (when node -i fails)
4. Use interact_with_process() to send commands
5. Use read_process_output() to get responses
When Python is unavailable, prefer Node.js over shell for calculations.
Node.js: Always use ES import syntax (import x from 'y'), not require().
SMART DETECTION:
- Detects REPL prompts (>>>, >, $, etc.)
- Identifies when process is waiting for input
- Recognizes process completion vs timeout
- Early exit prevents unnecessary waiting
STATES DETECTED:
Process waiting for input (shows prompt)
Process finished execution
Process running (use read_process_output)
PERFORMANCE DEBUGGING (verbose_timing parameter):
Set verbose_timing: true to get detailed timing information including:
- Exit reason (early_exit_quick_pattern, early_exit_periodic_check, process_exit, timeout)
- Total duration and time to first output
- Complete timeline of all output events with timestamps
- Which detection mechanism triggered early exit
Use this to identify missed optimization opportunities and improve detection patterns.
ALWAYS USE FOR: Local file analysis, CSV processing, data exploration, system commands
NEVER USE ANALYSIS TOOL FOR: Local file access (analysis tool is browser-only and WILL FAIL)
${PATH_GUIDANCE}
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(StartProcessArgsSchema),
annotations: {
title: "Start Terminal Process",
readOnlyHint: false,
destructiveHint: true,
openWorldHint: true,
},
},
{
name: "read_process_output",
description: `
Read output from a running process with file-like pagination support.
Supports partial output reading with offset and length parameters (like read_file):
- 'offset' (start line, default: 0)
* offset=0: Read NEW output since last read (default, like old behavior)
* Positive: Read from absolute line position
* Negative: Read last N lines from end (tail behavior)
- 'length' (max lines to read, default: configurable via 'fileReadLineLimit' setting)
Examples:
- offset: 0, length: 100 → First 100 NEW lines since last read
- offset: 0 → All new lines (respects config limit)
- offset: 500, length: 50 → Lines 500-549 (absolute position)
- offset: -20 → Last 20 lines (tail)
- offset: -50, length: 10 → Start 50 from end, read 10 lines
OUTPUT PROTECTION:
- Uses same fileReadLineLimit as read_file (default: 1000 lines)
- Returns status like: [Reading 100 lines from line 0 (total: 5000 lines, 4900 remaining)]
- Prevents context overflow from verbose processes
SMART FEATURES:
- For offset=0, waits up to timeout_ms for new output to arrive
- Detects REPL prompts and process completion
- Shows process state (waiting for input, finished, etc.)
DETECTION STATES:
Process waiting for input (ready for interact_with_process)
Process finished execution
Timeout reached (may still be running)
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(ReadProcessOutputArgsSchema),
annotations: {
title: "Read Process Output",
readOnlyHint: true,
},
},
{
name: "interact_with_process",
description: `
Send input to a running process and automatically receive the response.
CRITICAL: THIS IS THE PRIMARY TOOL FOR ALL LOCAL FILE ANALYSIS
For ANY local file analysis (CSV, JSON, data processing), ALWAYS use this instead of the analysis tool.
The analysis tool CANNOT access local files and WILL FAIL - use processes for ALL file-based work.
FILE ANALYSIS PRIORITY ORDER (MANDATORY):
1. ALWAYS FIRST: Use this tool (start_process + interact_with_process) for local data analysis
2. ALTERNATIVE: Use command-line tools (cut, awk, grep) for quick processing
3. NEVER EVER: Use analysis tool for local file access (IT WILL FAIL)
REQUIRED INTERACTIVE WORKFLOW FOR FILE ANALYSIS:
1. Start REPL: start_process("python3 -i")
2. Load libraries: interact_with_process(pid, "import pandas as pd, numpy as np")
3. Read file: interact_with_process(pid, "df = pd.read_csv('/absolute/path/file.csv')")
4. Analyze: interact_with_process(pid, "print(df.describe())")
5. Continue: interact_with_process(pid, "df.groupby('column').size()")
BINARY FILE PROCESSING WORKFLOWS:
Use appropriate Python libraries (PyPDF2, pandas, docx2txt, etc.) or command-line tools for binary file analysis.
SMART DETECTION:
- Automatically waits for REPL prompt (>>>, >, etc.)
- Detects errors and completion states
- Early exit prevents timeout delays
- Clean output formatting (removes prompts)
SUPPORTED REPLs:
- Python: python3 -i (RECOMMENDED for data analysis)
- Node.js: node -i
- R: R
- Julia: julia
- Shell: bash, zsh
- Database: mysql, postgres
PARAMETERS:
- pid: Process ID from start_process
- input: Code/command to execute
- timeout_ms: Max wait (default: 8000ms)
- wait_for_prompt: Auto-wait for response (default: true)
- verbose_timing: Enable detailed performance telemetry (default: false)
Returns execution result with status indicators.
PERFORMANCE DEBUGGING (verbose_timing parameter):
Set verbose_timing: true to get detailed timing information including:
- Exit reason (early_exit_quick_pattern, early_exit_periodic_check, process_finished, timeout, no_wait)
- Total duration and time to first output
- Complete timeline of all output events with timestamps
- Which detection mechanism triggered early exit
Use this to identify slow interactions and optimize detection patterns.
ALWAYS USE FOR: CSV analysis, JSON processing, file statistics, data visualization prep, ANY local file work
NEVER USE ANALYSIS TOOL FOR: Local file access (it cannot read files from disk and WILL FAIL)
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(InteractWithProcessArgsSchema),
annotations: {
title: "Send Input to Process",
readOnlyHint: false,
destructiveHint: true,
openWorldHint: true,
},
},
{
name: "force_terminate",
description: `
Force terminate a running terminal session.
${CMD_PREFIX_DESCRIPTION}`,
inputSchema: zodToJsonSchema(ForceTerminateArgsSchema),
annotations: {
title: "Force Terminate Process",
readOnlyHint: false,
destructiveHint: true,
openWorldHint: false,
},
},
{
name: "list_sessions",
description: `
List all active terminal sessions.
Shows session status including:
- PID: Process identifier
- Blocked: Whether session is waiting for input
- Runtime: How long the session has been running
DEBUGGING REPLs:
- "Blocked: true" often means REPL is waiting for input
- Use this to verify sessions are running before sending input
- Long runtime with blocked status may indicate stuck process