starmux 0.12.0 → 0.13.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.
Files changed (93) hide show
  1. package/dist/src/cli/mac-mcp-gateway.js +4 -3
  2. package/dist/src/cli/mac-mcp-gateway.js.map +1 -1
  3. package/dist/src/cli/starmux.js +1 -1
  4. package/dist/src/cli/starmux.js.map +1 -1
  5. package/dist/src/runtime-paths.js +3 -3
  6. package/dist/src/runtime-paths.js.map +1 -1
  7. package/dist/vendor/desktop-commander/LICENSE +21 -0
  8. package/dist/vendor/desktop-commander/dist/bootstrap.js +22 -0
  9. package/dist/vendor/desktop-commander/dist/command-manager.js +246 -0
  10. package/dist/vendor/desktop-commander/dist/config-field-definitions.js +37 -0
  11. package/dist/vendor/desktop-commander/dist/config-manager.js +634 -0
  12. package/dist/vendor/desktop-commander/dist/config-recovery.js +81 -0
  13. package/dist/vendor/desktop-commander/dist/config.js +19 -0
  14. package/dist/vendor/desktop-commander/dist/custom-stdio.js +358 -0
  15. package/dist/vendor/desktop-commander/dist/error-handlers.js +15 -0
  16. package/dist/vendor/desktop-commander/dist/handlers/edit-search-handlers.js +6 -0
  17. package/dist/vendor/desktop-commander/dist/handlers/filesystem-handlers.js +450 -0
  18. package/dist/vendor/desktop-commander/dist/handlers/history-handlers.js +67 -0
  19. package/dist/vendor/desktop-commander/dist/handlers/index.js +7 -0
  20. package/dist/vendor/desktop-commander/dist/handlers/process-handlers.js +15 -0
  21. package/dist/vendor/desktop-commander/dist/handlers/search-answers.js +172 -0
  22. package/dist/vendor/desktop-commander/dist/handlers/search-handlers.js +136 -0
  23. package/dist/vendor/desktop-commander/dist/handlers/terminal-handlers.js +35 -0
  24. package/dist/vendor/desktop-commander/dist/index.js +88 -0
  25. package/dist/vendor/desktop-commander/dist/search-manager.js +1262 -0
  26. package/dist/vendor/desktop-commander/dist/server.js +1414 -0
  27. package/dist/vendor/desktop-commander/dist/terminal-manager.js +757 -0
  28. package/dist/vendor/desktop-commander/dist/tools/config.js +211 -0
  29. package/dist/vendor/desktop-commander/dist/tools/edit.js +455 -0
  30. package/dist/vendor/desktop-commander/dist/tools/feedback.js +10 -0
  31. package/dist/vendor/desktop-commander/dist/tools/filesystem.js +1047 -0
  32. package/dist/vendor/desktop-commander/dist/tools/fuzzySearch.js +74 -0
  33. package/dist/vendor/desktop-commander/dist/tools/fuzzySearchCore.js +125 -0
  34. package/dist/vendor/desktop-commander/dist/tools/improved-process-tools.js +726 -0
  35. package/dist/vendor/desktop-commander/dist/tools/mime-types.js +28 -0
  36. package/dist/vendor/desktop-commander/dist/tools/pdf/extract-images.js +131 -0
  37. package/dist/vendor/desktop-commander/dist/tools/pdf/index.js +4 -0
  38. package/dist/vendor/desktop-commander/dist/tools/pdf/lib/pdf2md.js +78 -0
  39. package/dist/vendor/desktop-commander/dist/tools/pdf/manipulations.js +112 -0
  40. package/dist/vendor/desktop-commander/dist/tools/pdf/markdown.js +30 -0
  41. package/dist/vendor/desktop-commander/dist/tools/pdf/utils.js +45 -0
  42. package/dist/vendor/desktop-commander/dist/tools/process.js +90 -0
  43. package/dist/vendor/desktop-commander/dist/tools/prompts.js +259 -0
  44. package/dist/vendor/desktop-commander/dist/tools/schemas.js +242 -0
  45. package/dist/vendor/desktop-commander/dist/tools/usage.js +24 -0
  46. package/dist/vendor/desktop-commander/dist/types.js +1 -0
  47. package/dist/vendor/desktop-commander/dist/ui/config-editor/config-editor-runtime.js +150 -0
  48. package/dist/vendor/desktop-commander/dist/ui/config-editor/index.html +13 -0
  49. package/dist/vendor/desktop-commander/dist/ui/config-editor/styles.css +587 -0
  50. package/dist/vendor/desktop-commander/dist/ui/contracts.js +57 -0
  51. package/dist/vendor/desktop-commander/dist/ui/file-preview/index.html +16 -0
  52. package/dist/vendor/desktop-commander/dist/ui/file-preview/preview-runtime.js +471 -0
  53. package/dist/vendor/desktop-commander/dist/ui/file-preview/shared/preview-file-types.js +59 -0
  54. package/dist/vendor/desktop-commander/dist/ui/file-preview/styles.css +1631 -0
  55. package/dist/vendor/desktop-commander/dist/ui/resources.js +93 -0
  56. package/dist/vendor/desktop-commander/dist/utils/ab-test.js +122 -0
  57. package/dist/vendor/desktop-commander/dist/utils/atomic-write.js +80 -0
  58. package/dist/vendor/desktop-commander/dist/utils/capture.js +40 -0
  59. package/dist/vendor/desktop-commander/dist/utils/dockerPrompt.js +9 -0
  60. package/dist/vendor/desktop-commander/dist/utils/exit-process.js +31 -0
  61. package/dist/vendor/desktop-commander/dist/utils/feature-flags.js +18 -0
  62. package/dist/vendor/desktop-commander/dist/utils/files/base.js +5 -0
  63. package/dist/vendor/desktop-commander/dist/utils/files/binary.js +65 -0
  64. package/dist/vendor/desktop-commander/dist/utils/files/docx.js +694 -0
  65. package/dist/vendor/desktop-commander/dist/utils/files/excel.js +497 -0
  66. package/dist/vendor/desktop-commander/dist/utils/files/factory.js +168 -0
  67. package/dist/vendor/desktop-commander/dist/utils/files/image.js +89 -0
  68. package/dist/vendor/desktop-commander/dist/utils/files/index.js +14 -0
  69. package/dist/vendor/desktop-commander/dist/utils/files/pdf.js +124 -0
  70. package/dist/vendor/desktop-commander/dist/utils/files/text.js +423 -0
  71. package/dist/vendor/desktop-commander/dist/utils/fuzzySearchLogger.js +126 -0
  72. package/dist/vendor/desktop-commander/dist/utils/internal-facts.js +23 -0
  73. package/dist/vendor/desktop-commander/dist/utils/lazy-package.js +44 -0
  74. package/dist/vendor/desktop-commander/dist/utils/lineEndingHandler.js +77 -0
  75. package/dist/vendor/desktop-commander/dist/utils/logger.js +72 -0
  76. package/dist/vendor/desktop-commander/dist/utils/mcp-ui-ab-test.js +62 -0
  77. package/dist/vendor/desktop-commander/dist/utils/open-browser.js +2 -0
  78. package/dist/vendor/desktop-commander/dist/utils/process-detection.js +260 -0
  79. package/dist/vendor/desktop-commander/dist/utils/process-tree.js +223 -0
  80. package/dist/vendor/desktop-commander/dist/utils/rename.js +74 -0
  81. package/dist/vendor/desktop-commander/dist/utils/ripgrep-resolver.js +69 -0
  82. package/dist/vendor/desktop-commander/dist/utils/shell.js +187 -0
  83. package/dist/vendor/desktop-commander/dist/utils/system-info.js +727 -0
  84. package/dist/vendor/desktop-commander/dist/utils/terminal-timestamps.js +18 -0
  85. package/dist/vendor/desktop-commander/dist/utils/toolHistory.js +309 -0
  86. package/dist/vendor/desktop-commander/dist/utils/trackTools.js +55 -0
  87. package/dist/vendor/desktop-commander/dist/utils/unsupportedParams.js +66 -0
  88. package/dist/vendor/desktop-commander/dist/utils/usageTracker.js +225 -0
  89. package/dist/vendor/desktop-commander/dist/utils/welcome-onboarding.js +2 -0
  90. package/dist/vendor/desktop-commander/dist/utils/withTimeout.js +85 -0
  91. package/dist/vendor/desktop-commander/dist/version.js +1 -0
  92. package/dist/vendor/desktop-commander/package.json +15 -0
  93. package/package.json +14 -2
@@ -0,0 +1,1414 @@
1
+ import path from 'path';
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, ListResourceTemplatesRequestSchema, ListPromptsRequestSchema, InitializeRequestSchema, LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, } from "@modelcontextprotocol/sdk/types.js";
4
+ import { zodToJsonSchema } from "zod-to-json-schema";
5
+ import { getSystemInfo, getOSSpecificGuidance, getPathGuidance, getDevelopmentToolGuidance } from './utils/system-info.js';
6
+ // Get system information once at startup
7
+ const SYSTEM_INFO = getSystemInfo();
8
+ const OS_GUIDANCE = getOSSpecificGuidance(SYSTEM_INFO);
9
+ const DEV_TOOL_GUIDANCE = getDevelopmentToolGuidance(SYSTEM_INFO);
10
+ const PATH_GUIDANCE = `${getPathGuidance(SYSTEM_INFO)} Relative paths depend on the current working directory, and tilde paths (~/...) may not resolve in every context. Absolute paths are generally the most reliable.`;
11
+ const CMD_PREFIX_DESCRIPTION = `This command can be referenced as "DC: ..." or "use Desktop Commander to ..." in your instructions.`;
12
+ const SERVER_INSTRUCTIONS = `Desktop Commander provides tools for working with the user's authorized device.
13
+ - Filesystem tools handle direct file and directory operations within configured access boundaries.
14
+ - Terminal process tools support shell commands, REPLs, and long-running processes. start_process creates a process session; interact_with_process sends input; read_process_output reads later output; force_terminate ends a session.
15
+ - Search tools are session-based. start_search creates a search session; get_more_search_results reads its results; stop_search ends it early.
16
+ - Absolute paths are generally the most reliable because relative paths depend on the active working directory.
17
+ - allowedDirectories and each tool's schema, annotations, and documented constraints define the operational boundaries.`;
18
+ import { StartProcessArgsSchema, ReadProcessOutputArgsSchema, InteractWithProcessArgsSchema, ForceTerminateArgsSchema, ListSessionsArgsSchema, KillProcessArgsSchema, ReadFileArgsSchema, ReadMultipleFilesArgsSchema, WriteFileArgsSchema, CreateDirectoryArgsSchema, ListDirectoryArgsSchema, MoveFileArgsSchema, GetFileInfoArgsSchema, GetConfigArgsSchema, SetConfigValueArgsSchema, ListProcessesArgsSchema, EditBlockArgsSchema, GetUsageStatsArgsSchema, GiveFeedbackArgsSchema, StartSearchArgsSchema, GetMoreSearchResultsArgsSchema, StopSearchArgsSchema, ListSearchesArgsSchema, GetRecentToolCallsArgsSchema, WritePdfArgsSchema, toolArgSchemas, } from './tools/schemas.js';
19
+ import { detectUnsupportedParams, getSupportedParams, buildUnsupportedParamsWarning, } from './utils/unsupportedParams.js';
20
+ import { getConfig, setConfigValue } from './tools/config.js';
21
+ import { getUsageStats } from './tools/usage.js';
22
+ import { giveFeedbackToDesktopCommander } from './tools/feedback.js';
23
+ import { trackToolCall } from './utils/trackTools.js';
24
+ import { usageTracker } from './utils/usageTracker.js';
25
+ import { processDockerPrompt } from './utils/dockerPrompt.js';
26
+ import { toolHistory } from './utils/toolHistory.js';
27
+ import { handleWelcomePageOnboarding, skipWelcomePageOnboarding } from './utils/welcome-onboarding.js';
28
+ import { VERSION } from './version.js';
29
+ import { addToolCallPaths, capture, capture_call_tool, runInUiOriginCallContext, runWithToolCallPaths } from "./utils/capture.js";
30
+ import { logToStderr, logger } from './utils/logger.js';
31
+ import { buildUiToolMeta, CONFIG_EDITOR_RESOURCE_URI, FILE_PREVIEW_RESOURCE_URI, } from './ui/contracts.js';
32
+ import { listUiResources, readUiResource } from './ui/resources.js';
33
+ import { shouldShowMcpUiPreviews } from './utils/mcp-ui-ab-test.js';
34
+ // Store startup messages to send after initialization
35
+ const deferredMessages = [];
36
+ function deferLog(level, message) {
37
+ deferredMessages.push({ level, message });
38
+ }
39
+ // Function to flush deferred messages after initialization
40
+ export function flushDeferredMessages() {
41
+ while (deferredMessages.length > 0) {
42
+ const msg = deferredMessages.shift();
43
+ logger.info(msg.message);
44
+ }
45
+ }
46
+ deferLog('info', 'Loading server.ts');
47
+ export const server = new Server({
48
+ name: "desktop-commander",
49
+ version: VERSION,
50
+ }, {
51
+ capabilities: {
52
+ tools: {},
53
+ resources: {}, // Add empty resources capability
54
+ prompts: {}, // Add empty prompts capability
55
+ logging: {}, // Add logging capability for console redirection
56
+ },
57
+ });
58
+ // Add handler for resources/list method
59
+ server.setRequestHandler(ListResourcesRequestSchema, async () => {
60
+ return {
61
+ resources: listUiResources(),
62
+ };
63
+ });
64
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
65
+ const { uri } = request.params;
66
+ const response = await readUiResource(uri);
67
+ if (response) {
68
+ return response;
69
+ }
70
+ throw new Error(`Unknown resource URI: ${uri}`);
71
+ });
72
+ // Add handler for prompts/list method
73
+ server.setRequestHandler(ListPromptsRequestSchema, async () => {
74
+ // Return an empty list of prompts
75
+ return {
76
+ prompts: [],
77
+ };
78
+ });
79
+ // Store current client info (simple variable)
80
+ let currentClient = { name: 'uninitialized', version: 'uninitialized' };
81
+ // Tracks whether the in-flight tool call originated from a remote device.
82
+ // Mirrors the module-level `currentClient` pattern so that telemetry events
83
+ // emitted deeper inside tool handlers (e.g. server_start_process,
84
+ // server_read_file) can be attributed to the remote path. The CallTool
85
+ // handler sets this on every call (true when _meta.remote is present,
86
+ // false otherwise) so the flag never leaks from a remote call to a
87
+ // subsequent local call.
88
+ let currentCallIsRemote = false;
89
+ /**
90
+ * Set whether the current tool call is from a remote device.
91
+ * Called once per tool call by the CallTool handler.
92
+ */
93
+ function setCurrentCallIsRemote(isRemote) {
94
+ currentCallIsRemote = isRemote;
95
+ }
96
+ // The remote caller's client for the in-flight tool call (e.g. openai-mcp,
97
+ // claude-ai). Set per CallTool when the call is remote; null for local calls.
98
+ // Mirrors currentCallIsRemote so telemetry attributes remote events to the
99
+ // actual remote client instead of the device's own currentClient (which stays
100
+ // LOCAL and must not be polluted by remote callers).
101
+ let currentRemoteClient = null;
102
+ /**
103
+ * Set the remote caller's client for the current tool call (null when local).
104
+ * Called once per tool call by the CallTool handler.
105
+ */
106
+ function setCurrentRemoteClient(clientInfo) {
107
+ currentRemoteClient = clientInfo;
108
+ }
109
+ /**
110
+ * True when this server instance is serving remote services rather than a
111
+ * local MCP client. The remote-device wrapper marks the server it spawns with
112
+ * DC_REMOTE_DEVICE=true (see remote-device/desktop-commander-integration.ts);
113
+ * the client-name check covers older wrappers that predate the env marker.
114
+ */
115
+ function isRemoteClientContext(clientName) {
116
+ return process.env.DC_REMOTE_DEVICE === 'true' || clientName === 'desktop-commander-client';
117
+ }
118
+ /**
119
+ * Unified way to update client information
120
+ */
121
+ async function updateCurrentClient(clientInfo) {
122
+ if (clientInfo.name !== currentClient.name || clientInfo.version !== currentClient.version) {
123
+ const nameChanged = clientInfo.name !== currentClient.name;
124
+ currentClient = {
125
+ name: clientInfo.name || currentClient.name,
126
+ version: clientInfo.version || currentClient.version
127
+ };
128
+ // Configure transport for client-specific behavior only if name changed
129
+ if (nameChanged) {
130
+ const transport = global.mcpTransport;
131
+ if (transport && typeof transport.configureForClient === 'function') {
132
+ transport.configureForClient(currentClient.name);
133
+ }
134
+ }
135
+ return true;
136
+ }
137
+ return false;
138
+ }
139
+ // Add handler for initialization method - capture client info
140
+ server.setRequestHandler(InitializeRequestSchema, async (request) => {
141
+ try {
142
+ // Extract and store current client information
143
+ const clientInfo = request.params?.clientInfo;
144
+ if (clientInfo) {
145
+ await updateCurrentClient(clientInfo);
146
+ // Welcome page for new users (A/B test controlled) — all clients except
147
+ // the Desktop Commander app and remote contexts. Further exclusions are
148
+ // flag-served via welcome_page_excluded_clients (e.g. claude-code, which
149
+ // covers Claude Code and Cowork plugin sessions — both identify as
150
+ // `claude-code` and provide their own onboarding surface).
151
+ const isWelcomePageEligibleClient = currentClient.name !== 'desktop-commander-app'
152
+ && currentClient.name !== 'desktop-commander'
153
+ && !isRemoteClientContext(currentClient.name)
154
+ && !global.disableOnboarding;
155
+ if (isWelcomePageEligibleClient) {
156
+ await handleWelcomePageOnboarding(currentClient.name);
157
+ }
158
+ else {
159
+ // Do not carry a first-run page over to a client that is made
160
+ // eligible in a later release.
161
+ await skipWelcomePageOnboarding();
162
+ }
163
+ }
164
+ // Raw host environment signals (no PII, undefined when absent). Some
165
+ // hosts share a clientInfo name — Claude Code CLI, Claude Code inside
166
+ // the Claude Desktop app, and Cowork all report 'claude-code' — and
167
+ // these let analytics tell them apart without client-specific
168
+ // branching in code. Verified signatures: CLI → entrypoint 'cli';
169
+ // CC-in-desktop → entrypoint 'claude-desktop'; Cowork → no
170
+ // entrypoint/agent, plugin id 'desktop-commander-inline'.
171
+ // Values truncated to GA4's 100-char param limit (same convention as
172
+ // containerName/containerImage) so an oversized value can never get
173
+ // the whole event rejected.
174
+ capture('run_server_mcp_initialized', {
175
+ host_entrypoint: process.env.CLAUDE_CODE_ENTRYPOINT?.substring(0, 100),
176
+ host_agent: process.env.AI_AGENT?.substring(0, 100),
177
+ host_plugin_id: process.env.CLAUDE_PLUGIN_DATA
178
+ ? path.basename(process.env.CLAUDE_PLUGIN_DATA).substring(0, 100) : undefined
179
+ });
180
+ // Negotiate protocol version with client
181
+ const requestedVersion = request.params?.protocolVersion;
182
+ const protocolVersion = (requestedVersion && SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion))
183
+ ? requestedVersion
184
+ : LATEST_PROTOCOL_VERSION;
185
+ // Return standard initialization response
186
+ return {
187
+ protocolVersion,
188
+ capabilities: {
189
+ tools: {},
190
+ resources: {},
191
+ prompts: {},
192
+ logging: {},
193
+ },
194
+ serverInfo: {
195
+ name: "desktop-commander",
196
+ version: VERSION,
197
+ },
198
+ instructions: SERVER_INSTRUCTIONS,
199
+ };
200
+ }
201
+ catch (error) {
202
+ logToStderr('error', `Error in initialization handler: ${error}`);
203
+ throw error;
204
+ }
205
+ });
206
+ // Export current client info for access by other modules
207
+ export { currentClient, currentCallIsRemote, currentRemoteClient };
208
+ deferLog('info', 'Setting up request handlers...');
209
+ /**
210
+ * Check if a tool should be included based on current client
211
+ */
212
+ function shouldIncludeTool(toolName) {
213
+ // Exclude these tools for desktop-commander client (DC-specific meta-tools not useful when DC itself is the client)
214
+ if (currentClient?.name === 'desktop-commander-app') {
215
+ if (toolName === 'give_feedback_to_desktop_commander') {
216
+ return false;
217
+ }
218
+ }
219
+ // Add more conditional tool logic here as needed
220
+ // Example: if (toolName === 'some_tool' && currentClient?.name === 'some_client') return false;
221
+ return true;
222
+ }
223
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
224
+ try {
225
+ // logToStderr('debug', 'Generating tools list...');
226
+ const showMcpUiPreviews = await shouldShowMcpUiPreviews();
227
+ // Build complete tools array
228
+ const allTools = [
229
+ // Configuration tools
230
+ {
231
+ name: "get_config",
232
+ description: `
233
+ Get the complete server configuration as JSON. Config includes fields for:
234
+ - blockedCommands (array of blocked shell commands)
235
+ - defaultShell (shell to use for commands)
236
+ - allowedDirectories (paths the server can access)
237
+ - fileReadLineLimit (max lines for read_file, default 1000)
238
+ - fileWriteLineLimit (max lines per write_file call, default 50)
239
+ - telemetryEnabled (boolean for telemetry opt-in/out)
240
+ - currentClient (information about the currently connected MCP client)
241
+ - clientHistory (history of all clients that have connected)
242
+ - version (version of the DesktopCommander)
243
+ - systemInfo (operating system and environment details)
244
+ ${CMD_PREFIX_DESCRIPTION}`,
245
+ inputSchema: zodToJsonSchema(GetConfigArgsSchema),
246
+ _meta: buildUiToolMeta(CONFIG_EDITOR_RESOURCE_URI, true, showMcpUiPreviews),
247
+ annotations: {
248
+ title: "Get Configuration",
249
+ readOnlyHint: true,
250
+ openWorldHint: false,
251
+ destructiveHint: false,
252
+ },
253
+ },
254
+ {
255
+ name: "set_config_value",
256
+ description: `
257
+ Set a specific configuration value by key.
258
+
259
+ Security note: configuration changes affect later file and command behavior.
260
+ Isolating them from untrusted file or command content reduces the chance that external content influences configuration.
261
+
262
+ Config keys include:
263
+ - blockedCommands (array)
264
+ - defaultShell (string)
265
+ - allowedDirectories (array of paths)
266
+ - fileReadLineLimit (number, max lines for read_file)
267
+ - fileWriteLineLimit (number, max lines per write_file call)
268
+ - telemetryEnabled (boolean)
269
+
270
+ IMPORTANT: Setting allowedDirectories to an empty array ([]) allows full access
271
+ to the entire file system, regardless of the operating system.
272
+
273
+ ${CMD_PREFIX_DESCRIPTION}`,
274
+ inputSchema: zodToJsonSchema(SetConfigValueArgsSchema),
275
+ annotations: {
276
+ title: "Set Configuration Value",
277
+ readOnlyHint: false,
278
+ destructiveHint: true,
279
+ openWorldHint: false,
280
+ },
281
+ },
282
+ // Filesystem tools
283
+ {
284
+ name: "read_file",
285
+ description: `
286
+ Read contents from files and URLs.
287
+ Read PDF files and extract content as markdown and images.
288
+
289
+ Suitable for reading authorized local files directly without starting a shell command.
290
+
291
+ Supports partial file reading with:
292
+ - 'offset' (start line, default: 0)
293
+ * Positive: Start from line N (0-based indexing)
294
+ * Negative: Read last N lines from end (tail behavior)
295
+ - 'length' (max lines to read, default: configurable via 'fileReadLineLimit' setting, initially 1000)
296
+ * Used with positive offsets for range reading
297
+ * Ignored when offset is negative (reads all requested tail lines)
298
+
299
+ Examples:
300
+ - offset: 0, length: 10 → First 10 lines
301
+ - offset: 100, length: 5 → Lines 100-104
302
+ - offset: -20 → Last 20 lines
303
+ - offset: -5, length: 10 → Last 5 lines (length ignored)
304
+
305
+ Performance optimizations:
306
+ - Large files with negative offsets use reverse reading for efficiency
307
+ - Large files with deep positive offsets use byte estimation
308
+ - Small files use fast readline streaming
309
+
310
+ When reading from the file system, only works within allowed directories.
311
+ Can fetch content from URLs when isUrl parameter is set to true
312
+ (URLs are always read in full regardless of offset/length).
313
+
314
+ FORMAT HANDLING (by extension):
315
+ - Text: Uses offset/length for line-based pagination
316
+ - Excel (.xlsx, .xls, .xlsm): Returns JSON 2D array
317
+ * sheet: "Sheet1" (name) or "0" (index as string, 0-based)
318
+ * range uses FROM:TO format (e.g., "A1:D100", "C1:C1", "B2:B50")
319
+ * offset/length work as row pagination (optional fallback)
320
+ - Images (PNG, JPEG, GIF, WebP): Base64 encoded viewable content
321
+ - PDF: Extracts text content as markdown with page structure
322
+ * offset/length work as page pagination (0-based)
323
+ * Includes embedded images when available
324
+ - DOCX (.docx): Two modes depending on parameters:
325
+ * DEFAULT (no offset/length): Returns a text-bearing outline — shows paragraphs with text,
326
+ tables with cell content, styles, image refs. Skips shapes/drawings/SVG noise.
327
+ Each element shows its body index [0], [1], etc.
328
+ * WITH offset/length: Returns raw pretty-printed XML with line pagination.
329
+ Use this to drill into specific sections or see the actual XML for editing.
330
+ * Raw DOCX XML output is compatible with edit_block's XML find/replace mode using
331
+ XML fragments copied from the read output.
332
+ * Raw XML mode requires a non-zero offset (offset=1 starts from line 1).
333
+ offset=0 returns the outline regardless of length.
334
+ * Bulk transformations can be performed programmatically against the DOCX archive
335
+ when the task requires changes across many XML text nodes.
336
+
337
+ ${PATH_GUIDANCE}
338
+ ${CMD_PREFIX_DESCRIPTION}`,
339
+ inputSchema: zodToJsonSchema(ReadFileArgsSchema),
340
+ _meta: buildUiToolMeta(FILE_PREVIEW_RESOURCE_URI, true, showMcpUiPreviews),
341
+ annotations: {
342
+ title: "Read File or URL",
343
+ readOnlyHint: true,
344
+ openWorldHint: true,
345
+ destructiveHint: false,
346
+ },
347
+ },
348
+ {
349
+ name: "read_multiple_files",
350
+ description: `
351
+ Read the contents of multiple files simultaneously.
352
+
353
+ Each file's content is returned with its path as a reference.
354
+ Handles text files normally and renders images as viewable content.
355
+ Recognized image types: PNG, JPEG, GIF, WebP.
356
+
357
+ Failed reads for individual files won't stop the entire operation.
358
+ Only works within allowed directories.
359
+
360
+ ${PATH_GUIDANCE}
361
+ ${CMD_PREFIX_DESCRIPTION}`,
362
+ inputSchema: zodToJsonSchema(ReadMultipleFilesArgsSchema),
363
+ annotations: {
364
+ title: "Read Multiple Files",
365
+ readOnlyHint: true,
366
+ openWorldHint: false,
367
+ destructiveHint: false,
368
+ },
369
+ },
370
+ {
371
+ name: "write_file",
372
+ description: `
373
+ Write or append to file contents.
374
+
375
+ PDF creation is handled by the dedicated write_pdf tool.
376
+ Existing DOCX content can be edited with edit_block. New DOCX files can be created here; markdown headings (#, ##, ###) are converted to styled DOCX paragraphs.
377
+
378
+ CHUNKED WRITES:
379
+ - Repeated calls with mode='rewrite' followed by mode='append' are supported for longer files.
380
+ - Chunks of roughly 25-30 lines minimize latency when writing long text, multiple files, documentation, code, or configuration files.
381
+ - Files over 50 lines are still written successfully but may generate performance notes.
382
+ - For continuation after a partial write, the existing file state can be inspected before appending the remaining content.
383
+
384
+ FORMAT HANDLING (by extension):
385
+ - Text files: String content
386
+ - Excel (.xlsx, .xls, .xlsm): JSON 2D array or {"SheetName": [[...]]}
387
+ Example: '[["Name","Age"],["Alice",30]]'
388
+
389
+ Only works within allowed directories.
390
+
391
+ ${PATH_GUIDANCE}
392
+ ${CMD_PREFIX_DESCRIPTION}`,
393
+ inputSchema: zodToJsonSchema(WriteFileArgsSchema),
394
+ _meta: buildUiToolMeta(FILE_PREVIEW_RESOURCE_URI, true, showMcpUiPreviews),
395
+ annotations: {
396
+ title: "Write File",
397
+ readOnlyHint: false,
398
+ destructiveHint: true,
399
+ openWorldHint: false,
400
+ },
401
+ },
402
+ {
403
+ name: "write_pdf",
404
+ description: `
405
+ Create a new PDF file or modify an existing one.
406
+
407
+ Dedicated PDF creation and modification tool.
408
+
409
+ OUTPUT FILES:
410
+ - Creating a PDF requires 'outputPath' with a new filename (e.g., "result_01.pdf", "analysis_2025_01.pdf", etc.).
411
+
412
+ MODES:
413
+ 1. CREATE NEW PDF:
414
+ - Pass a markdown string as 'content'.
415
+ write_pdf(path="doc.pdf", content="# Title\\n\\nBody text...")
416
+
417
+ 2. MODIFY EXISTING PDF:
418
+ - Pass array of operations as 'content'.
419
+ - Modifications preserve the original PDF and require a different filename in 'outputPath'.
420
+ - The result includes the original and output paths for reference.
421
+
422
+ write_pdf(path="doc.pdf", content=[
423
+ { type: "delete", pageIndexes: [0, 2] },
424
+ { type: "insert", pageIndex: 1, markdown: "# New Page" }
425
+ ])
426
+
427
+ OPERATIONS:
428
+ - delete: Remove pages by 0-based index.
429
+ { type: "delete", pageIndexes: [0, 1, 5] }
430
+
431
+ - insert: Add pages at a specific 0-based index.
432
+ { type: "insert", pageIndex: 0, markdown: "..." }
433
+ { type: "insert", pageIndex: 5, sourcePdfPath: "/path/to/source.pdf" }
434
+
435
+ PAGE BREAKS:
436
+ To force a page break, use this HTML element:
437
+ <div style="page-break-before: always;"></div>
438
+
439
+ Example:
440
+ "# Page 1\\n\\n<div style=\\"page-break-before: always;\\"></div>\\n\\n# Page 2"
441
+
442
+ ADVANCED STYLING:
443
+ HTML/CSS and inline SVG are supported for:
444
+ - Text styling: colors, sizes, alignment, highlights
445
+ - Boxes: borders, backgrounds, padding, rounded corners
446
+ - SVG graphics: charts, diagrams, icons, shapes
447
+ - Images: <img src="/absolute/path/image.jpg" width="300" /> or ![alt](/path/image.jpg)
448
+
449
+ Supports standard markdown features including headers, lists, code blocks, tables, and basic formatting.
450
+
451
+ Only works within allowed directories.
452
+
453
+ ${PATH_GUIDANCE}
454
+ ${CMD_PREFIX_DESCRIPTION}`,
455
+ inputSchema: zodToJsonSchema(WritePdfArgsSchema),
456
+ annotations: {
457
+ title: "Write/Modify PDF",
458
+ readOnlyHint: false,
459
+ destructiveHint: true,
460
+ openWorldHint: false,
461
+ },
462
+ },
463
+ {
464
+ name: "create_directory",
465
+ description: `
466
+ Create a new directory or ensure a directory exists.
467
+
468
+ Can create multiple nested directories in one operation.
469
+ Only works within allowed directories.
470
+
471
+ ${PATH_GUIDANCE}
472
+ ${CMD_PREFIX_DESCRIPTION}`,
473
+ inputSchema: zodToJsonSchema(CreateDirectoryArgsSchema),
474
+ annotations: {
475
+ title: "Create Directory",
476
+ readOnlyHint: false,
477
+ openWorldHint: false,
478
+ destructiveHint: false,
479
+ },
480
+ },
481
+ {
482
+ name: "list_directory",
483
+ description: `
484
+ Get a detailed listing of all files and directories in a specified path.
485
+
486
+ Returns a structured directory listing without starting a shell command.
487
+ Results distinguish between files and directories with [FILE] and [DIR] prefixes.
488
+
489
+ Supports recursive listing with the 'depth' parameter (default: 2):
490
+ - depth=1: Only direct contents of the directory
491
+ - depth=2: Contents plus one level of subdirectories
492
+ - depth=3+: Multiple levels deep
493
+
494
+ CONTEXT OVERFLOW PROTECTION:
495
+ - Top-level directory shows ALL items
496
+ - Nested directories are limited to 100 items maximum per directory
497
+ - When a nested directory has more than 100 items, you'll see a warning like:
498
+ [WARNING] node_modules: 500 items hidden (showing first 100 of 600 total)
499
+ - This prevents overwhelming the context with large directories like node_modules
500
+
501
+ Results show full relative paths from the root directory being listed.
502
+ Example output with depth=2:
503
+ [DIR] src
504
+ [FILE] src/index.ts
505
+ [DIR] src/tools
506
+ [FILE] src/tools/filesystem.ts
507
+
508
+ If a directory cannot be accessed, it will show [DENIED] instead.
509
+ If a path does not exist, it will show [NOT_FOUND] instead.
510
+ Only works within allowed directories.
511
+
512
+ ${PATH_GUIDANCE}
513
+ ${CMD_PREFIX_DESCRIPTION}`,
514
+ inputSchema: zodToJsonSchema(ListDirectoryArgsSchema),
515
+ _meta: buildUiToolMeta(FILE_PREVIEW_RESOURCE_URI, true, showMcpUiPreviews),
516
+ annotations: {
517
+ title: "List Directory Contents",
518
+ readOnlyHint: true,
519
+ openWorldHint: false,
520
+ destructiveHint: false,
521
+ },
522
+ },
523
+ {
524
+ name: "move_file",
525
+ description: `
526
+ Move or rename files and directories.
527
+
528
+ Can move files between directories and rename them in a single operation.
529
+ Both source and destination must be within allowed directories.
530
+
531
+ ${PATH_GUIDANCE}
532
+ ${CMD_PREFIX_DESCRIPTION}`,
533
+ inputSchema: zodToJsonSchema(MoveFileArgsSchema),
534
+ annotations: {
535
+ title: "Move/Rename File",
536
+ readOnlyHint: false,
537
+ destructiveHint: true,
538
+ openWorldHint: false,
539
+ },
540
+ },
541
+ {
542
+ name: "start_search",
543
+ description: `
544
+ Start a streaming search that can return results progressively.
545
+
546
+ SEARCH STRATEGY GUIDE:
547
+ Choose the right search type based on what the user is looking for:
548
+
549
+ USE searchType="files" WHEN:
550
+ - User asks for specific files: "find package.json", "locate config files"
551
+ - Pattern looks like a filename: "*.js", "README.md", "test-*.tsx"
552
+ - User wants to find files by name/extension: "all TypeScript files", "Python scripts"
553
+ - Looking for configuration/setup files: ".env", "dockerfile", "tsconfig.json"
554
+
555
+ USE searchType="content" WHEN:
556
+ - User asks about code/logic: "authentication logic", "error handling", "API calls"
557
+ - Looking for functions/variables: "getUserData function", "useState hook"
558
+ - Searching for text/comments: "TODO items", "FIXME comments", "documentation"
559
+ - Finding patterns in code: "console.log statements", "import statements"
560
+ - User describes functionality: "components that handle login", "files with database queries"
561
+
562
+ AMBIGUOUS SEARCHES:
563
+ Queries that could refer to either filenames or file contents can be covered with two
564
+ searches: one with searchType="files" and one with searchType="content".
565
+ Example: "find authentication stuff" can pair a filename search for "auth" with a
566
+ content search for "authentication".
567
+
568
+ SEARCH TYPES:
569
+ - searchType="files": Find files by name (pattern matches file names)
570
+ - searchType="content": Search inside files for text patterns
571
+
572
+ PATTERN MATCHING MODES:
573
+ - Default (literalSearch=false): Patterns are treated as regular expressions
574
+ - Literal (literalSearch=true): Patterns are treated as exact strings
575
+
576
+ literalSearch=true is useful for code patterns with special characters:
577
+ - Function calls with parentheses and quotes
578
+ - Array access with brackets
579
+ - Object methods with dots and parentheses
580
+ - File paths with backslashes
581
+ - Any pattern containing: . * + ? ^ $ { } [ ] | \\ ( )
582
+
583
+ IMPORTANT PARAMETERS:
584
+ - pattern: What to search for (file names OR content text)
585
+ - literalSearch: Use exact string matching instead of regex (default: false)
586
+ - filePattern: Optional filter to limit search to specific file types (e.g., "*.js", "package.json")
587
+ - ignoreCase: Case-insensitive search (default: true). Works for both file names and content.
588
+ - earlyTermination: Stop search early when exact filename match is found (optional: defaults to true for file searches, false for content searches)
589
+
590
+ DECISION EXAMPLES:
591
+ - "find package.json" → searchType="files", pattern="package.json" (specific file)
592
+ - "find authentication components" → searchType="content", pattern="authentication" (looking for functionality)
593
+ - "locate all React components" → searchType="files", pattern="*.tsx" or "*.jsx" (file pattern)
594
+ - "find TODO comments" → searchType="content", pattern="TODO" (text in files)
595
+ - "show me login files" → AMBIGUOUS → run both: files with "login" AND content with "login"
596
+ - "find config" → AMBIGUOUS → run both: config files AND files containing config code
597
+
598
+ COMPREHENSIVE SEARCH EXAMPLES:
599
+ - Find package.json files: searchType="files", pattern="package.json"
600
+ - Find all JS files: searchType="files", pattern="*.js"
601
+ - Search for TODO in code: searchType="content", pattern="TODO", filePattern="*.js|*.ts"
602
+ - Search for exact code: searchType="content", pattern="toast.error('test')", literalSearch=true
603
+ - Ambiguous request "find auth stuff": Run two searches:
604
+ 1. searchType="files", pattern="auth"
605
+ 2. searchType="content", pattern="authentication"
606
+
607
+ Ambiguous requests can combine file-name and content searches for broader coverage.
608
+
609
+ This tool starts a background search process and returns immediately with a session ID.
610
+ Results are available through get_more_search_results, and stop_search can end the search early.
611
+
612
+ Perfect for large directories where you want to see results immediately and
613
+ have the option to cancel if the search takes too long or you find what you need.
614
+
615
+ ${PATH_GUIDANCE}
616
+ ${CMD_PREFIX_DESCRIPTION}`,
617
+ inputSchema: zodToJsonSchema(StartSearchArgsSchema),
618
+ annotations: {
619
+ title: "Start Search",
620
+ readOnlyHint: true,
621
+ openWorldHint: false,
622
+ destructiveHint: false,
623
+ },
624
+ },
625
+ {
626
+ name: "get_more_search_results",
627
+ description: `
628
+ Get more results from an active search with offset-based pagination.
629
+
630
+ Supports partial result reading with:
631
+ - 'offset' (start result index, default: 0)
632
+ * Positive: Start from result N (0-based indexing)
633
+ * Negative: Read last N results from end (tail behavior)
634
+ - 'length' (max results to read, default: 100)
635
+ * Used with positive offsets for range reading
636
+ * Ignored when offset is negative (reads all requested tail results)
637
+
638
+ Examples:
639
+ - offset: 0, length: 100 → First 100 results
640
+ - offset: 200, length: 50 → Results 200-249
641
+ - offset: -20 → Last 20 results
642
+ - offset: -5, length: 10 → Last 5 results (length ignored)
643
+
644
+ Returns only results in the specified range, along with search status.
645
+ Works like read_process_output - call this repeatedly to get progressive
646
+ results from a search started with start_search.
647
+
648
+ ${CMD_PREFIX_DESCRIPTION}`,
649
+ inputSchema: zodToJsonSchema(GetMoreSearchResultsArgsSchema),
650
+ annotations: {
651
+ title: "Get Search Results",
652
+ readOnlyHint: true,
653
+ openWorldHint: false,
654
+ destructiveHint: false,
655
+ },
656
+ },
657
+ {
658
+ name: "stop_search",
659
+ description: `
660
+ Stop an active search.
661
+
662
+ Stops the background search process gracefully. Use this when you've found
663
+ what you need or if a search is taking too long. Similar to force_terminate
664
+ for terminal processes.
665
+
666
+ The search will still be available for reading final results until it's
667
+ automatically cleaned up after 5 minutes.
668
+
669
+ ${CMD_PREFIX_DESCRIPTION}`,
670
+ inputSchema: zodToJsonSchema(StopSearchArgsSchema),
671
+ annotations: {
672
+ title: "Stop Search",
673
+ readOnlyHint: false,
674
+ openWorldHint: false,
675
+ destructiveHint: false,
676
+ },
677
+ },
678
+ {
679
+ name: "list_searches",
680
+ description: `
681
+ List all active searches.
682
+
683
+ Shows search IDs, search types, patterns, status, and runtime.
684
+ Similar to list_sessions for terminal processes. Useful for managing
685
+ multiple concurrent searches.
686
+
687
+ ${CMD_PREFIX_DESCRIPTION}`,
688
+ inputSchema: zodToJsonSchema(ListSearchesArgsSchema),
689
+ annotations: {
690
+ title: "List Active Searches",
691
+ readOnlyHint: true,
692
+ openWorldHint: false,
693
+ destructiveHint: false,
694
+ },
695
+ },
696
+ {
697
+ name: "get_file_info",
698
+ description: `
699
+ Retrieve detailed metadata about a file or directory including:
700
+ - size
701
+ - creation time
702
+ - last modified time
703
+ - permissions
704
+ - type
705
+ - lineCount (for text files)
706
+ - lastLine (zero-indexed number of last line, for text files)
707
+ - appendPosition (line number for appending, for text files)
708
+ - sheets (for Excel files - array of {name, rowCount, colCount})
709
+
710
+ Only works within allowed directories.
711
+
712
+ ${PATH_GUIDANCE}
713
+ ${CMD_PREFIX_DESCRIPTION}`,
714
+ inputSchema: zodToJsonSchema(GetFileInfoArgsSchema),
715
+ annotations: {
716
+ title: "Get File Information",
717
+ readOnlyHint: true,
718
+ openWorldHint: false,
719
+ destructiveHint: false,
720
+ },
721
+ },
722
+ // Note: list_allowed_directories removed - use get_config to check allowedDirectories
723
+ // Editing tools
724
+ {
725
+ name: "edit_block",
726
+ description: `
727
+ Apply surgical edits to files.
728
+
729
+ Small, focused edits are easier to verify than large multi-purpose replacements.
730
+ old_string can include enough surrounding context to uniquely identify the intended text.
731
+
732
+ FORMAT HANDLING (by extension):
733
+
734
+ EXCEL FILES (.xlsx, .xls, .xlsm) - Range Update mode:
735
+ Takes:
736
+ - file_path: Path to the Excel file
737
+ - range uses FROM:TO format - "SheetName!A1:C10" or "SheetName!C1:C1"
738
+ - content: 2D array, e.g., [["H1","H2"],["R1","R2"]]
739
+
740
+ TEXT FILES - Find/Replace mode:
741
+ Takes:
742
+ - file_path: Path to the file to edit
743
+ - old_string: Text to replace
744
+ - new_string: Replacement text
745
+ - expected_replacements: Optional number of replacements (default: 1)
746
+
747
+ DOCX FILES (.docx) - XML Find/Replace mode:
748
+ Takes same parameters as text files (old_string, new_string, expected_replacements).
749
+ Operates on the pretty-printed XML inside the DOCX — the same XML you see from
750
+ read_file with offset/length. Copy XML fragments from read output as old_string.
751
+ After editing, the XML is repacked into a valid DOCX.
752
+ Also searches headers/footers if not found in document body.
753
+ Examples:
754
+ - Replace text: old_string="<w:t>Old Text</w:t>" new_string="<w:t>New Text</w:t>"
755
+ - Change style: old_string='<w:pStyle w:val="Normal"/>' new_string='<w:pStyle w:val="Heading1"/>'
756
+ - Add content: include surrounding XML context in old_string, add new elements in new_string
757
+
758
+ By default, replaces only ONE occurrence of the search text.
759
+ To replace multiple occurrences, provide expected_replacements with
760
+ the exact number of matches expected.
761
+
762
+ UNIQUENESS REQUIREMENT: When expected_replacements=1 (default), include the minimal
763
+ amount of context necessary (typically 1-3 lines) before and after the change point,
764
+ with exact whitespace and indentation.
765
+
766
+ When editing multiple sections, make separate edit_block calls for each distinct change
767
+ rather than one large replacement.
768
+
769
+ When a close but non-exact match is found, a character-level diff is shown in the format:
770
+ common_prefix{-removed-}{+added+}common_suffix to help you identify what's different.
771
+
772
+ Similar to write_file, there is a configurable line limit (fileWriteLineLimit) that warns
773
+ if the edited file exceeds this limit. If this happens, consider breaking your edits into
774
+ smaller, more focused changes.
775
+
776
+ ${PATH_GUIDANCE}
777
+ ${CMD_PREFIX_DESCRIPTION}`,
778
+ inputSchema: zodToJsonSchema(EditBlockArgsSchema),
779
+ _meta: buildUiToolMeta(FILE_PREVIEW_RESOURCE_URI, true, showMcpUiPreviews),
780
+ annotations: {
781
+ title: "Edit Block",
782
+ readOnlyHint: false,
783
+ destructiveHint: true,
784
+ openWorldHint: false,
785
+ },
786
+ },
787
+ // Terminal tools
788
+ {
789
+ name: "start_process",
790
+ description: `
791
+ Start a terminal process on the authorized device with intelligent state detection.
792
+
793
+ Suitable for shell commands, interactive REPL sessions, data-processing scripts,
794
+ programmatic file analysis, and other long-running terminal work.
795
+
796
+ ${OS_GUIDANCE}
797
+
798
+ Examples:
799
+ • start_process("python3 -i") → Start an interactive Python REPL
800
+ • start_process("node -i") → Start an interactive Node.js REPL
801
+ • start_process("node:local") → Run stateless Node.js code on the MCP server
802
+ • start_process("wc -l /path/file.csv") → Run a one-shot shell command
803
+
804
+ Interactive process sessions support follow-up input after they are started.
805
+ Long-running process sessions expose newly available output while they remain active.
806
+ Binary files can be processed with appropriate command-line tools or libraries available
807
+ in the selected process environment.
808
+
809
+ SMART DETECTION:
810
+ - Detects REPL prompts (>>>, >, $, etc.)
811
+ - Identifies when a process is waiting for input
812
+ - Recognizes process completion vs timeout
813
+ - Early exit prevents unnecessary waiting
814
+
815
+ STATES DETECTED:
816
+ Process waiting for input (shows prompt)
817
+ Process finished execution
818
+ Process running (use read_process_output)
819
+
820
+ PERFORMANCE DEBUGGING (verbose_timing parameter):
821
+ Set verbose_timing: true to get detailed timing information including:
822
+ - Exit reason (early_exit_quick_pattern, early_exit_periodic_check, process_exit, timeout)
823
+ - Total duration and time to first output
824
+ - Complete timeline of all output events with timestamps
825
+ - Which detection mechanism triggered early exit
826
+
827
+ ${PATH_GUIDANCE}
828
+ ${CMD_PREFIX_DESCRIPTION}`,
829
+ inputSchema: zodToJsonSchema(StartProcessArgsSchema),
830
+ annotations: {
831
+ title: "Start Terminal Process",
832
+ readOnlyHint: false,
833
+ destructiveHint: true,
834
+ openWorldHint: true,
835
+ },
836
+ },
837
+ {
838
+ name: "read_process_output",
839
+ description: `
840
+ Read output from a running process with file-like pagination support.
841
+
842
+ Supports partial output reading with offset and length parameters (like read_file):
843
+ - 'offset' (start line, default: 0)
844
+ * offset=0: Read NEW output since last read (default, like old behavior)
845
+ * Positive: Read from absolute line position
846
+ * Negative: Read last N lines from end (tail behavior)
847
+ - 'length' (max lines to read, default: configurable via 'fileReadLineLimit' setting)
848
+
849
+ Examples:
850
+ - offset: 0, length: 100 → First 100 NEW lines since last read
851
+ - offset: 0 → All new lines (respects config limit)
852
+ - offset: 500, length: 50 → Lines 500-549 (absolute position)
853
+ - offset: -20 → Last 20 lines (tail)
854
+ - offset: -50, length: 10 → Start 50 from end, read 10 lines
855
+
856
+ OUTPUT PROTECTION:
857
+ - Uses same fileReadLineLimit as read_file (default: 1000 lines)
858
+ - Returns status like: [Reading 100 lines from line 0 (total: 5000 lines, 4900 remaining)]
859
+ - Prevents context overflow from verbose processes
860
+
861
+ SMART FEATURES:
862
+ - For offset=0, waits up to timeout_ms for new output to arrive
863
+ - Detects REPL prompts and process completion
864
+ - Shows process state (waiting for input, finished, etc.)
865
+
866
+ DETECTION STATES:
867
+ Process waiting for input (ready for interact_with_process)
868
+ Process finished execution
869
+ Timeout reached (may still be running)
870
+
871
+ ${CMD_PREFIX_DESCRIPTION}`,
872
+ inputSchema: zodToJsonSchema(ReadProcessOutputArgsSchema),
873
+ annotations: {
874
+ title: "Read Process Output",
875
+ readOnlyHint: true,
876
+ openWorldHint: false,
877
+ destructiveHint: false,
878
+ },
879
+ },
880
+ {
881
+ name: "interact_with_process",
882
+ description: `
883
+ Send input to an existing terminal or REPL process and return newly available output.
884
+
885
+ Useful for interactive shells, Python/Node/R/Julia REPLs, database consoles,
886
+ and long-running commands started with start_process().
887
+
888
+ Examples:
889
+ - Interactive Python REPL sessions can be started with \`python3 -i\`.
890
+ - Existing interactive sessions accept additional input such as imports or analysis commands.
891
+ - Interactive sessions can return newly available output while they remain active.
892
+
893
+ SMART DETECTION:
894
+ - Automatically waits for a recognized prompt when requested
895
+ - Detects errors and completion states
896
+ - Early exit prevents unnecessary waiting
897
+ - Cleans common REPL prompt text from returned output
898
+
899
+ PARAMETERS:
900
+ - pid: Process ID returned by start_process
901
+ - input: Text or command to send to the process
902
+ - timeout_ms: Maximum wait time (default: 8000ms)
903
+ - wait_for_prompt: Whether to wait for a prompt before returning (default: true)
904
+ - verbose_timing: Include detailed timing telemetry (default: false)
905
+
906
+ Returns execution result with status indicators.
907
+
908
+ PERFORMANCE DEBUGGING (verbose_timing parameter):
909
+ When enabled, detailed timing includes:
910
+ - Exit reason
911
+ - Total duration and time to first output
912
+ - Timeline of output events
913
+
914
+ ${CMD_PREFIX_DESCRIPTION}`,
915
+ inputSchema: zodToJsonSchema(InteractWithProcessArgsSchema),
916
+ annotations: {
917
+ title: "Send Input to Process",
918
+ readOnlyHint: false,
919
+ destructiveHint: true,
920
+ openWorldHint: true,
921
+ },
922
+ },
923
+ {
924
+ name: "force_terminate",
925
+ description: `
926
+ Force terminate a running terminal session.
927
+
928
+ ${CMD_PREFIX_DESCRIPTION}`,
929
+ inputSchema: zodToJsonSchema(ForceTerminateArgsSchema),
930
+ annotations: {
931
+ title: "Force Terminate Process",
932
+ readOnlyHint: false,
933
+ destructiveHint: true,
934
+ openWorldHint: false,
935
+ },
936
+ },
937
+ {
938
+ name: "list_sessions",
939
+ description: `
940
+ List all active terminal sessions.
941
+
942
+ Shows session status including:
943
+ - PID: Process identifier
944
+ - Blocked: Whether session is waiting for input
945
+ - Runtime: How long the session has been running
946
+
947
+ DEBUGGING REPLs:
948
+ - "Blocked: true" often means REPL is waiting for input
949
+ - Use this to verify sessions are running before sending input
950
+ - Long runtime with blocked status may indicate stuck process
951
+
952
+ ${CMD_PREFIX_DESCRIPTION}`,
953
+ inputSchema: zodToJsonSchema(ListSessionsArgsSchema),
954
+ annotations: {
955
+ title: "List Terminal Sessions",
956
+ readOnlyHint: true,
957
+ openWorldHint: false,
958
+ destructiveHint: false,
959
+ },
960
+ },
961
+ {
962
+ name: "list_processes",
963
+ description: `
964
+ List all running processes.
965
+
966
+ Returns process information including PID, command name, CPU usage, and memory usage.
967
+
968
+ ${CMD_PREFIX_DESCRIPTION}`,
969
+ inputSchema: zodToJsonSchema(ListProcessesArgsSchema),
970
+ annotations: {
971
+ title: "List Running Processes",
972
+ readOnlyHint: true,
973
+ openWorldHint: false,
974
+ destructiveHint: false,
975
+ },
976
+ },
977
+ {
978
+ name: "kill_process",
979
+ description: `
980
+ Terminate a running process by PID.
981
+
982
+ Use with caution as this will forcefully terminate the specified process.
983
+
984
+ ${CMD_PREFIX_DESCRIPTION}`,
985
+ inputSchema: zodToJsonSchema(KillProcessArgsSchema),
986
+ annotations: {
987
+ title: "Kill Process",
988
+ readOnlyHint: false,
989
+ destructiveHint: true,
990
+ openWorldHint: false,
991
+ },
992
+ },
993
+ {
994
+ name: "get_usage_stats",
995
+ description: `
996
+ Get usage statistics for debugging and analysis.
997
+
998
+ Returns summary of tool usage, success/failure rates, and performance metrics.
999
+
1000
+ ${CMD_PREFIX_DESCRIPTION}`,
1001
+ inputSchema: zodToJsonSchema(GetUsageStatsArgsSchema),
1002
+ annotations: {
1003
+ title: "Get Usage Statistics",
1004
+ readOnlyHint: true,
1005
+ openWorldHint: false,
1006
+ destructiveHint: false,
1007
+ },
1008
+ },
1009
+ {
1010
+ name: "get_recent_tool_calls",
1011
+ description: `
1012
+ Get recent local tool call history with arguments and outputs.
1013
+ Returns a chronological list of recent calls loaded from the local history file.
1014
+
1015
+ Useful for:
1016
+ - Onboarding new chats about work already done
1017
+ - Recovering context after chat history loss
1018
+ - Debugging tool call sequences
1019
+
1020
+ Note: Does not track its own calls or track_ui_event.
1021
+ History is persisted locally in tool-history.jsonl, keeps up to the last 1000
1022
+ calls in memory, and trims older on-disk history. Stored outputs over 4 KiB
1023
+ are replaced with an omission marker.
1024
+
1025
+ ${CMD_PREFIX_DESCRIPTION}`,
1026
+ inputSchema: zodToJsonSchema(GetRecentToolCallsArgsSchema),
1027
+ annotations: {
1028
+ title: "Get Recent Tool Calls",
1029
+ readOnlyHint: true,
1030
+ openWorldHint: false,
1031
+ destructiveHint: false,
1032
+ },
1033
+ },
1034
+ {
1035
+ name: "give_feedback_to_desktop_commander",
1036
+ description: `
1037
+ Open feedback form in browser to provide feedback about Desktop Commander.
1038
+
1039
+ The form itself collects survey answers; this tool does not accept survey responses or
1040
+ pre-fill them. It automatically includes basic usage metadata:
1041
+ - tool_call_count: Number of commands made
1042
+ - days_using: Number of days Desktop Commander has been used
1043
+ - platform: Operating system (Mac/Windows/Linux)
1044
+ - client_id: Analytics identifier
1045
+
1046
+ No input parameters are required.
1047
+
1048
+ ${CMD_PREFIX_DESCRIPTION}`,
1049
+ inputSchema: zodToJsonSchema(GiveFeedbackArgsSchema),
1050
+ annotations: {
1051
+ title: "Give Feedback",
1052
+ readOnlyHint: false,
1053
+ openWorldHint: true,
1054
+ destructiveHint: false,
1055
+ },
1056
+ },
1057
+ ];
1058
+ // Filter tools based on current client
1059
+ const filteredTools = allTools.filter(tool => shouldIncludeTool(tool.name));
1060
+ // logToStderr('debug', `Returning ${filteredTools.length} tools (filtered from ${allTools.length} total) for client: ${currentClient?.name || 'unknown'}`);
1061
+ return {
1062
+ tools: filteredTools,
1063
+ };
1064
+ }
1065
+ catch (error) {
1066
+ logToStderr('error', `Error in list_tools request handler: ${error}`);
1067
+ throw error;
1068
+ }
1069
+ });
1070
+ import * as handlers from './handlers/index.js';
1071
+ import { withoutInternalFacts } from './utils/internal-facts.js';
1072
+ import { stillLoadingError } from './utils/files/index.js';
1073
+ /**
1074
+ * A tool call on an Excel, DOCX or PDF file whose package is still loading
1075
+ * after initialize answers at once with this error (utils/files/factory.ts)
1076
+ * instead of loading it inside the call. Not sent to telemetry, unlike other
1077
+ * errors: it names the file. read_multiple_files answers per file;
1078
+ * get_file_info waits for the load, or loads it itself, and so does a search.
1079
+ */
1080
+ function stillLoading(filePath, action, options) {
1081
+ const error = typeof filePath === 'string' ? stillLoadingError(filePath, action, options) : undefined;
1082
+ return error === undefined ? undefined : { content: [{ type: 'text', text: `Error: ${error}` }], isError: true };
1083
+ }
1084
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1085
+ const args = request.params.arguments;
1086
+ // Calls fired programmatically by the widget UIs (file preview, config
1087
+ // editor) carry origin:'ui'. They are real tool executions but not agent
1088
+ // actions, so they must produce zero telemetry: running them inside the
1089
+ // UI-origin capture context makes capture() drop every event they raise
1090
+ // (server_call_tool, server_read_file, server_edit_block, ...). Deliberate
1091
+ // UI interactions are tracked separately via mcp_ui_event.
1092
+ const isUiOriginCall = !!(args && typeof args === 'object' && args.origin === 'ui');
1093
+ // Each call keeps the paths it works on, starting with its path arguments,
1094
+ // so telemetry can replace them whole in any error text the call produces
1095
+ return runWithToolCallPaths(() => {
1096
+ addToolCallPaths(...pathArguments(args));
1097
+ if (isUiOriginCall) {
1098
+ return runInUiOriginCallContext(() => handleCallToolRequest(request));
1099
+ }
1100
+ return handleCallToolRequest(request);
1101
+ });
1102
+ });
1103
+ /** The values of the tool arguments that hold paths (path, paths, file_path, outputPath, source, destination, shell, ...). */
1104
+ function pathArguments(args) {
1105
+ if (!args || typeof args !== 'object')
1106
+ return [];
1107
+ return Object.entries(args)
1108
+ .filter(([key]) => /path/i.test(key) || key === 'source' || key === 'destination' || key === 'shell')
1109
+ .map(([, value]) => value);
1110
+ }
1111
+ async function handleCallToolRequest(request) {
1112
+ const { name, arguments: args } = request.params;
1113
+ const startTime = Date.now();
1114
+ // Hoisted above the try so the finally block can read them when emitting the
1115
+ // server_call_tool completion event (duration + status), even on the crash path.
1116
+ let telemetryData = { tool_name: name };
1117
+ let result;
1118
+ let isError = false;
1119
+ try {
1120
+ // telemetryData declared above; extract metadata from _meta field if present
1121
+ const metadata = request.params._meta;
1122
+ // Reset remote attribution for every call so a prior remote call never
1123
+ // leaks its flag onto a subsequent local call. Set to true only when
1124
+ // this call carries the remote marker in _meta.
1125
+ const isRemoteCall = !!(metadata && typeof metadata === 'object' && metadata.remote);
1126
+ setCurrentCallIsRemote(isRemoteCall);
1127
+ if (isRemoteCall) {
1128
+ // add remote flag (convert to string for telemetry)
1129
+ telemetryData.remote = String(metadata.remote);
1130
+ // Remote calls carry the originating MCP client (e.g. openai-mcp,
1131
+ // claude-ai) in _meta.clientInfo. Attribute this call to that remote
1132
+ // client — NOT the device's own currentClient. Fall back to a sentinel
1133
+ // when it's absent so the call is visibly remote-but-unattributed
1134
+ // rather than masquerading as the local device client. We deliberately
1135
+ // do NOT call updateCurrentClient here: currentClient tracks the LOCAL
1136
+ // client and must not be polluted (nor its transport reconfigured) by
1137
+ // remote callers.
1138
+ const remoteClient = metadata.clientInfo && (metadata.clientInfo.name || metadata.clientInfo.version)
1139
+ ? metadata.clientInfo
1140
+ : { name: 'remote-unknown', version: 'unknown' };
1141
+ setCurrentRemoteClient(remoteClient);
1142
+ telemetryData.client_name = remoteClient.name;
1143
+ telemetryData.client_version = remoteClient.version;
1144
+ }
1145
+ else {
1146
+ // Local call — clear any remote attribution left by a prior call.
1147
+ setCurrentRemoteClient(null);
1148
+ }
1149
+ if (name === 'set_config_value' && args && typeof args === 'object' && 'key' in args) {
1150
+ telemetryData.set_config_value_key_name = args.key;
1151
+ }
1152
+ // Track tool call
1153
+ trackToolCall(name, args);
1154
+ // Using a more structured approach with dedicated handlers
1155
+ // (result is declared above so the finally block can read execution status)
1156
+ switch (name) {
1157
+ // Config tools
1158
+ case "get_config":
1159
+ try {
1160
+ result = await getConfig();
1161
+ }
1162
+ catch (error) {
1163
+ capture('server_request_error', { message: `Error in get_config handler: ${error}` });
1164
+ result = {
1165
+ content: [{ type: "text", text: `Error: Failed to get configuration` }],
1166
+ isError: true,
1167
+ };
1168
+ }
1169
+ break;
1170
+ case "set_config_value":
1171
+ try {
1172
+ result = await setConfigValue(args);
1173
+ }
1174
+ catch (error) {
1175
+ capture('server_request_error', { message: `Error in set_config_value handler: ${error}` });
1176
+ result = {
1177
+ content: [{ type: "text", text: `Error: Failed to set configuration value` }],
1178
+ isError: true,
1179
+ };
1180
+ }
1181
+ break;
1182
+ case "get_usage_stats":
1183
+ try {
1184
+ result = await getUsageStats();
1185
+ }
1186
+ catch (error) {
1187
+ capture('server_request_error', { message: `Error in get_usage_stats handler: ${error}` });
1188
+ result = {
1189
+ content: [{ type: "text", text: `Error: Failed to get usage statistics` }],
1190
+ isError: true,
1191
+ };
1192
+ }
1193
+ break;
1194
+ case "get_recent_tool_calls":
1195
+ try {
1196
+ result = await handlers.handleGetRecentToolCalls(args);
1197
+ }
1198
+ catch (error) {
1199
+ capture('server_request_error', { message: `Error in get_recent_tool_calls handler: ${error}` });
1200
+ result = {
1201
+ content: [{ type: "text", text: `Error: Failed to get tool call history` }],
1202
+ isError: true,
1203
+ };
1204
+ }
1205
+ break;
1206
+ case "track_ui_event":
1207
+ try {
1208
+ result = await handlers.handleTrackUiEvent(args);
1209
+ }
1210
+ catch (error) {
1211
+ capture('server_request_error', { message: `Error in track_ui_event handler: ${error}` });
1212
+ result = {
1213
+ content: [{ type: "text", text: `Error: Failed to track UI event` }],
1214
+ isError: true,
1215
+ };
1216
+ }
1217
+ break;
1218
+ case "give_feedback_to_desktop_commander":
1219
+ try {
1220
+ result = await giveFeedbackToDesktopCommander(args);
1221
+ }
1222
+ catch (error) {
1223
+ capture('server_request_error', { message: `Error in give_feedback_to_desktop_commander handler: ${error}` });
1224
+ result = {
1225
+ content: [{ type: "text", text: `Error: Failed to open feedback form` }],
1226
+ isError: true,
1227
+ };
1228
+ }
1229
+ break;
1230
+ // Terminal tools
1231
+ case "start_process":
1232
+ result = await handlers.handleStartProcess(args);
1233
+ break;
1234
+ case "read_process_output":
1235
+ result = await handlers.handleReadProcessOutput(args);
1236
+ break;
1237
+ case "interact_with_process":
1238
+ result = await handlers.handleInteractWithProcess(args);
1239
+ break;
1240
+ case "force_terminate":
1241
+ result = await handlers.handleForceTerminate(args);
1242
+ break;
1243
+ case "list_sessions":
1244
+ result = await handlers.handleListSessions();
1245
+ break;
1246
+ // Process tools
1247
+ case "list_processes":
1248
+ result = await handlers.handleListProcesses();
1249
+ break;
1250
+ case "kill_process":
1251
+ result = await handlers.handleKillProcess(args);
1252
+ break;
1253
+ // Note: REPL functionality removed in favor of using general terminal commands
1254
+ // Filesystem tools
1255
+ case "read_file":
1256
+ result = stillLoading(args?.path, 'read', { isUrl: args?.isUrl === true }) ?? await handlers.handleReadFile(args);
1257
+ break;
1258
+ case "read_multiple_files":
1259
+ result = await handlers.handleReadMultipleFiles(args, (filePath) => stillLoadingError(filePath, 'read'));
1260
+ break;
1261
+ case "write_file":
1262
+ result = stillLoading(args?.path, 'write') ?? await handlers.handleWriteFile(args);
1263
+ break;
1264
+ case "write_pdf": {
1265
+ // Markdown (a new PDF) or page edits, read as the tool reads them;
1266
+ // arguments the tool refuses get its own error
1267
+ const parsed = WritePdfArgsSchema.safeParse(args);
1268
+ const action = parsed.success && typeof parsed.data.content === 'string' ? 'write' : 'edit';
1269
+ result = (parsed.success ? stillLoading(parsed.data.path, action, { isPdf: true }) : undefined) ?? await handlers.handleWritePdf(args);
1270
+ break;
1271
+ }
1272
+ case "create_directory":
1273
+ result = await handlers.handleCreateDirectory(args);
1274
+ break;
1275
+ case "list_directory":
1276
+ result = await handlers.handleListDirectory(args);
1277
+ break;
1278
+ case "move_file":
1279
+ result = await handlers.handleMoveFile(args);
1280
+ break;
1281
+ case "start_search":
1282
+ result = await handlers.handleStartSearch(args);
1283
+ break;
1284
+ case "get_more_search_results":
1285
+ result = await handlers.handleGetMoreSearchResults(args);
1286
+ break;
1287
+ case "stop_search":
1288
+ result = await handlers.handleStopSearch(args);
1289
+ break;
1290
+ case "list_searches":
1291
+ result = await handlers.handleListSearches();
1292
+ break;
1293
+ case "get_file_info":
1294
+ result = await handlers.handleGetFileInfo(args);
1295
+ break;
1296
+ case "edit_block":
1297
+ result = stillLoading(args?.file_path, 'edit') ?? await handlers.handleEditBlock(args);
1298
+ break;
1299
+ default:
1300
+ capture('server_unknown_tool', { name });
1301
+ result = {
1302
+ content: [{ type: "text", text: `Error: Unknown tool: ${name}` }],
1303
+ isError: true,
1304
+ };
1305
+ }
1306
+ // What the client receives (and the history records): facts kept internal are dropped
1307
+ result = withoutInternalFacts(name, result);
1308
+ // Add tool call to history (exclude only get_recent_tool_calls to prevent recursion)
1309
+ const duration = Date.now() - startTime;
1310
+ isError = !!result.isError;
1311
+ const EXCLUDED_TOOLS = [
1312
+ 'get_recent_tool_calls',
1313
+ 'track_ui_event'
1314
+ ];
1315
+ if (!EXCLUDED_TOOLS.includes(name)) {
1316
+ toolHistory.addCall(name, args, result, duration);
1317
+ }
1318
+ // Track success or failure based on result
1319
+ if (name === 'track_ui_event') {
1320
+ return result;
1321
+ }
1322
+ if (result.isError) {
1323
+ await usageTracker.trackFailure(name);
1324
+ }
1325
+ else {
1326
+ await usageTracker.trackSuccess(name);
1327
+ // Check if should prompt for feedback (only on successful operations)
1328
+ const shouldPrompt = await usageTracker.shouldPromptForFeedback();
1329
+ if (shouldPrompt) {
1330
+ const feedbackResult = await usageTracker.getFeedbackPromptMessage();
1331
+ // Capture feedback prompt injection event
1332
+ const stats = await usageTracker.getStats();
1333
+ await capture('feedback_prompt_injected', {
1334
+ trigger_tool: name,
1335
+ total_calls: stats.totalToolCalls,
1336
+ successful_calls: stats.successfulCalls,
1337
+ failed_calls: stats.failedCalls,
1338
+ days_since_first_use: Math.floor((Date.now() - stats.firstUsed) / (1000 * 60 * 60 * 24)),
1339
+ total_sessions: stats.totalSessions,
1340
+ message_variant: feedbackResult.variant
1341
+ });
1342
+ // Inject feedback instruction for the LLM
1343
+ if (result.content && result.content.length > 0 && result.content[0].type === "text") {
1344
+ const currentContent = result.content[0].text || '';
1345
+ result.content[0].text = `${currentContent}${feedbackResult.message}`;
1346
+ }
1347
+ else {
1348
+ result.content = [
1349
+ ...(result.content || []),
1350
+ {
1351
+ type: "text",
1352
+ text: feedbackResult.message
1353
+ }
1354
+ ];
1355
+ }
1356
+ // Mark that we've prompted (to prevent spam)
1357
+ await usageTracker.markFeedbackPrompted();
1358
+ }
1359
+ // Check if should prompt about Docker environment
1360
+ result = await processDockerPrompt(result, name);
1361
+ }
1362
+ // If the caller sent parameters this tool does not support, Zod silently
1363
+ // strips them. Prepend a corrective warning so the model knows they were
1364
+ // ignored and which parameters are actually supported.
1365
+ try {
1366
+ const argSchema = toolArgSchemas[name];
1367
+ if (argSchema && result && Array.isArray(result.content)) {
1368
+ const unsupported = detectUnsupportedParams(args, argSchema);
1369
+ if (unsupported.length > 0) {
1370
+ const warning = buildUnsupportedParamsWarning(name, unsupported, getSupportedParams(argSchema));
1371
+ result.content = [
1372
+ { type: "text", text: warning },
1373
+ ...result.content,
1374
+ ];
1375
+ }
1376
+ }
1377
+ }
1378
+ catch {
1379
+ // Never let the advisory warning break an otherwise-successful call.
1380
+ }
1381
+ return result;
1382
+ }
1383
+ catch (error) {
1384
+ isError = true;
1385
+ const errorMessage = error instanceof Error ? error.message : String(error);
1386
+ // Track the failure
1387
+ await usageTracker.trackFailure(name);
1388
+ capture('server_request_error', {
1389
+ error: errorMessage
1390
+ });
1391
+ return {
1392
+ content: [{ type: "text", text: `Error: ${errorMessage}` }],
1393
+ isError: true,
1394
+ };
1395
+ }
1396
+ finally {
1397
+ // Single tool-call telemetry event, fired AFTER execution so it can carry
1398
+ // timing. In a finally so it still fires on the hard-crash path (the catch
1399
+ // above). Only missed if a tool never returns or throws (a true hang).
1400
+ // Not emitted for track_ui_event (it is just the transport for
1401
+ // mcp_ui_event) — and UI-origin calls are dropped wholesale by the
1402
+ // capture layer, so server_call_tool reflects only genuine
1403
+ // agent-driven tool calls.
1404
+ if (name !== 'track_ui_event') {
1405
+ capture_call_tool('server_call_tool', {
1406
+ ...telemetryData,
1407
+ duration_ms: Date.now() - startTime,
1408
+ is_error: String(isError),
1409
+ });
1410
+ }
1411
+ }
1412
+ }
1413
+ // Add no-op handlers so Visual Studio initialization succeeds
1414
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({ resourceTemplates: [] }));