@hcu-lab.me/mcp-device 1.0.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 (261) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +51 -0
  3. package/dist/bootstrap.d.ts +1 -0
  4. package/dist/bootstrap.js +22 -0
  5. package/dist/command-manager.d.ts +8 -0
  6. package/dist/command-manager.js +241 -0
  7. package/dist/config-field-definitions.d.ts +41 -0
  8. package/dist/config-field-definitions.js +37 -0
  9. package/dist/config-manager.d.ts +102 -0
  10. package/dist/config-manager.js +291 -0
  11. package/dist/config.d.ts +6 -0
  12. package/dist/config.js +10 -0
  13. package/dist/custom-stdio.d.ts +51 -0
  14. package/dist/custom-stdio.js +358 -0
  15. package/dist/data/official-app-ca.pem +12 -0
  16. package/dist/data/onboarding-prompts.json +70 -0
  17. package/dist/device/device-state.d.ts +13 -0
  18. package/dist/device/device-state.js +100 -0
  19. package/dist/device/device-status.d.ts +81 -0
  20. package/dist/device/device-status.js +156 -0
  21. package/dist/device/device.d.ts +16 -0
  22. package/dist/device/device.js +190 -0
  23. package/dist/device/execution-engine.d.ts +144 -0
  24. package/dist/device/execution-engine.js +195 -0
  25. package/dist/device/gateway-channel.d.ts +48 -0
  26. package/dist/device/gateway-channel.js +384 -0
  27. package/dist/device/gateway-config.d.ts +40 -0
  28. package/dist/device/gateway-config.js +207 -0
  29. package/dist/device/gateway-identity.d.ts +35 -0
  30. package/dist/device/gateway-identity.js +178 -0
  31. package/dist/device/gateway-pairing.d.ts +25 -0
  32. package/dist/device/gateway-pairing.js +105 -0
  33. package/dist/device/gateway-secure-transport.d.ts +25 -0
  34. package/dist/device/gateway-secure-transport.js +117 -0
  35. package/dist/device/gateway-tool-adapter.d.ts +17 -0
  36. package/dist/device/gateway-tool-adapter.js +284 -0
  37. package/dist/device/gateway-url-policy.d.ts +3 -0
  38. package/dist/device/gateway-url-policy.js +43 -0
  39. package/dist/device/linux-service.d.ts +70 -0
  40. package/dist/device/linux-service.js +268 -0
  41. package/dist/device/official-trust.d.ts +7 -0
  42. package/dist/device/official-trust.js +49 -0
  43. package/dist/device/project-inspection.d.ts +1 -0
  44. package/dist/device/project-inspection.js +180 -0
  45. package/dist/device/runtime-owner.d.ts +41 -0
  46. package/dist/device/runtime-owner.js +177 -0
  47. package/dist/device/windows-dpapi.d.ts +11 -0
  48. package/dist/device/windows-dpapi.js +67 -0
  49. package/dist/device/windows-service.d.ts +56 -0
  50. package/dist/device/windows-service.js +238 -0
  51. package/dist/error-handlers.d.ts +7 -0
  52. package/dist/error-handlers.js +15 -0
  53. package/dist/handlers/edit-search-handlers.d.ts +6 -0
  54. package/dist/handlers/edit-search-handlers.js +6 -0
  55. package/dist/handlers/filesystem-handlers.d.ts +38 -0
  56. package/dist/handlers/filesystem-handlers.js +440 -0
  57. package/dist/handlers/history-handlers.d.ts +12 -0
  58. package/dist/handlers/history-handlers.js +67 -0
  59. package/dist/handlers/index.d.ts +6 -0
  60. package/dist/handlers/index.js +7 -0
  61. package/dist/handlers/process-handlers.d.ts +9 -0
  62. package/dist/handlers/process-handlers.js +15 -0
  63. package/dist/handlers/search-handlers.d.ts +17 -0
  64. package/dist/handlers/search-handlers.js +224 -0
  65. package/dist/handlers/terminal-handlers.d.ts +21 -0
  66. package/dist/handlers/terminal-handlers.js +35 -0
  67. package/dist/index.d.ts +2 -0
  68. package/dist/index.js +138 -0
  69. package/dist/mcp-device.d.ts +2 -0
  70. package/dist/mcp-device.js +7 -0
  71. package/dist/npm-scripts/remote.d.ts +3 -0
  72. package/dist/npm-scripts/remote.js +314 -0
  73. package/dist/search-manager.d.ts +147 -0
  74. package/dist/search-manager.js +828 -0
  75. package/dist/server.d.ts +46 -0
  76. package/dist/server.js +1563 -0
  77. package/dist/terminal-manager.d.ts +104 -0
  78. package/dist/terminal-manager.js +635 -0
  79. package/dist/tools/config.d.ts +96 -0
  80. package/dist/tools/config.js +260 -0
  81. package/dist/tools/edit.d.ts +38 -0
  82. package/dist/tools/edit.js +435 -0
  83. package/dist/tools/feedback.d.ts +8 -0
  84. package/dist/tools/feedback.js +132 -0
  85. package/dist/tools/filesystem.d.ts +79 -0
  86. package/dist/tools/filesystem.js +947 -0
  87. package/dist/tools/fuzzySearch.d.ts +12 -0
  88. package/dist/tools/fuzzySearch.js +74 -0
  89. package/dist/tools/fuzzySearchCore.d.ts +52 -0
  90. package/dist/tools/fuzzySearchCore.js +125 -0
  91. package/dist/tools/improved-process-tools.d.ts +24 -0
  92. package/dist/tools/improved-process-tools.js +627 -0
  93. package/dist/tools/mime-types.d.ts +3 -0
  94. package/dist/tools/mime-types.js +28 -0
  95. package/dist/tools/pdf/extract-images.d.ts +34 -0
  96. package/dist/tools/pdf/extract-images.js +132 -0
  97. package/dist/tools/pdf/index.d.ts +6 -0
  98. package/dist/tools/pdf/index.js +3 -0
  99. package/dist/tools/pdf/lib/pdf2md.d.ts +36 -0
  100. package/dist/tools/pdf/lib/pdf2md.js +76 -0
  101. package/dist/tools/pdf/manipulations.d.ts +13 -0
  102. package/dist/tools/pdf/manipulations.js +99 -0
  103. package/dist/tools/pdf/markdown.d.ts +26 -0
  104. package/dist/tools/pdf/markdown.js +275 -0
  105. package/dist/tools/pdf/utils.d.ts +12 -0
  106. package/dist/tools/pdf/utils.js +34 -0
  107. package/dist/tools/process.d.ts +3 -0
  108. package/dist/tools/process.js +56 -0
  109. package/dist/tools/prompts.d.ts +28 -0
  110. package/dist/tools/prompts.js +259 -0
  111. package/dist/tools/schemas.d.ts +454 -0
  112. package/dist/tools/schemas.js +242 -0
  113. package/dist/tools/usage.d.ts +5 -0
  114. package/dist/tools/usage.js +24 -0
  115. package/dist/types.d.ts +83 -0
  116. package/dist/types.js +1 -0
  117. package/dist/ui/config-editor/config-editor-runtime.js +150 -0
  118. package/dist/ui/config-editor/index.html +13 -0
  119. package/dist/ui/config-editor/src/app.d.ts +43 -0
  120. package/dist/ui/config-editor/src/app.js +831 -0
  121. package/dist/ui/config-editor/src/array-modal.d.ts +19 -0
  122. package/dist/ui/config-editor/src/array-modal.js +185 -0
  123. package/dist/ui/config-editor/src/main.d.ts +1 -0
  124. package/dist/ui/config-editor/src/main.js +2 -0
  125. package/dist/ui/config-editor/styles.css +587 -0
  126. package/dist/ui/contracts.d.ts +14 -0
  127. package/dist/ui/contracts.js +21 -0
  128. package/dist/ui/file-preview/index.html +16 -0
  129. package/dist/ui/file-preview/preview-runtime.js +469 -0
  130. package/dist/ui/file-preview/shared/preview-file-types.d.ts +5 -0
  131. package/dist/ui/file-preview/shared/preview-file-types.js +59 -0
  132. package/dist/ui/file-preview/src/app.d.ts +4 -0
  133. package/dist/ui/file-preview/src/app.js +680 -0
  134. package/dist/ui/file-preview/src/components/code-viewer.d.ts +6 -0
  135. package/dist/ui/file-preview/src/components/code-viewer.js +73 -0
  136. package/dist/ui/file-preview/src/components/highlighting.d.ts +2 -0
  137. package/dist/ui/file-preview/src/components/highlighting.js +54 -0
  138. package/dist/ui/file-preview/src/components/html-renderer.d.ts +5 -0
  139. package/dist/ui/file-preview/src/components/html-renderer.js +47 -0
  140. package/dist/ui/file-preview/src/components/markdown-renderer.d.ts +1 -0
  141. package/dist/ui/file-preview/src/components/markdown-renderer.js +59 -0
  142. package/dist/ui/file-preview/src/directory-controller.d.ts +8 -0
  143. package/dist/ui/file-preview/src/directory-controller.js +240 -0
  144. package/dist/ui/file-preview/src/document-layout.d.ts +20 -0
  145. package/dist/ui/file-preview/src/document-layout.js +109 -0
  146. package/dist/ui/file-preview/src/document-outline.d.ts +17 -0
  147. package/dist/ui/file-preview/src/document-outline.js +97 -0
  148. package/dist/ui/file-preview/src/document-workspace.d.ts +19 -0
  149. package/dist/ui/file-preview/src/document-workspace.js +33 -0
  150. package/dist/ui/file-preview/src/file-type-handlers.d.ts +10 -0
  151. package/dist/ui/file-preview/src/file-type-handlers.js +109 -0
  152. package/dist/ui/file-preview/src/host/external-actions.d.ts +8 -0
  153. package/dist/ui/file-preview/src/host/external-actions.js +55 -0
  154. package/dist/ui/file-preview/src/host/selection-context.d.ts +9 -0
  155. package/dist/ui/file-preview/src/host/selection-context.js +106 -0
  156. package/dist/ui/file-preview/src/image-preview.d.ts +3 -0
  157. package/dist/ui/file-preview/src/image-preview.js +21 -0
  158. package/dist/ui/file-preview/src/main.d.ts +1 -0
  159. package/dist/ui/file-preview/src/main.js +5 -0
  160. package/dist/ui/file-preview/src/markdown/conflict-dialog.d.ts +40 -0
  161. package/dist/ui/file-preview/src/markdown/conflict-dialog.js +163 -0
  162. package/dist/ui/file-preview/src/markdown/controller.d.ts +44 -0
  163. package/dist/ui/file-preview/src/markdown/controller.js +1043 -0
  164. package/dist/ui/file-preview/src/markdown/editor.d.ts +131 -0
  165. package/dist/ui/file-preview/src/markdown/editor.js +1479 -0
  166. package/dist/ui/file-preview/src/markdown/linking.d.ts +16 -0
  167. package/dist/ui/file-preview/src/markdown/linking.js +228 -0
  168. package/dist/ui/file-preview/src/markdown/outline.d.ts +2 -0
  169. package/dist/ui/file-preview/src/markdown/outline.js +16 -0
  170. package/dist/ui/file-preview/src/markdown/parser.d.ts +30 -0
  171. package/dist/ui/file-preview/src/markdown/parser.js +38 -0
  172. package/dist/ui/file-preview/src/markdown/preview.d.ts +1 -0
  173. package/dist/ui/file-preview/src/markdown/preview.js +20 -0
  174. package/dist/ui/file-preview/src/markdown/slugify.d.ts +3 -0
  175. package/dist/ui/file-preview/src/markdown/slugify.js +31 -0
  176. package/dist/ui/file-preview/src/markdown/utils.d.ts +1 -0
  177. package/dist/ui/file-preview/src/markdown/utils.js +15 -0
  178. package/dist/ui/file-preview/src/model.d.ts +35 -0
  179. package/dist/ui/file-preview/src/model.js +1 -0
  180. package/dist/ui/file-preview/src/panel-actions.d.ts +17 -0
  181. package/dist/ui/file-preview/src/panel-actions.js +182 -0
  182. package/dist/ui/file-preview/src/path-utils.d.ts +6 -0
  183. package/dist/ui/file-preview/src/path-utils.js +64 -0
  184. package/dist/ui/file-preview/src/payload-utils.d.ts +11 -0
  185. package/dist/ui/file-preview/src/payload-utils.js +119 -0
  186. package/dist/ui/file-preview/src/types.d.ts +1 -0
  187. package/dist/ui/file-preview/src/types.js +1 -0
  188. package/dist/ui/file-preview/styles.css +1631 -0
  189. package/dist/ui/resources.d.ts +28 -0
  190. package/dist/ui/resources.js +86 -0
  191. package/dist/ui/shared/compact-row.d.ts +11 -0
  192. package/dist/ui/shared/compact-row.js +18 -0
  193. package/dist/ui/shared/escape-html.d.ts +4 -0
  194. package/dist/ui/shared/escape-html.js +11 -0
  195. package/dist/ui/shared/host-context.d.ts +15 -0
  196. package/dist/ui/shared/host-context.js +51 -0
  197. package/dist/ui/shared/tool-bridge.d.ts +30 -0
  198. package/dist/ui/shared/tool-bridge.js +137 -0
  199. package/dist/ui/shared/tool-shell.d.ts +25 -0
  200. package/dist/ui/shared/tool-shell.js +107 -0
  201. package/dist/ui/shared/ui-event-tracker.d.ts +9 -0
  202. package/dist/ui/shared/ui-event-tracker.js +27 -0
  203. package/dist/ui/shared/widget-state.d.ts +33 -0
  204. package/dist/ui/shared/widget-state.js +158 -0
  205. package/dist/utils/ab-test.d.ts +12 -0
  206. package/dist/utils/ab-test.js +104 -0
  207. package/dist/utils/capture.d.ts +35 -0
  208. package/dist/utils/capture.js +481 -0
  209. package/dist/utils/dockerPrompt.d.ts +17 -0
  210. package/dist/utils/dockerPrompt.js +53 -0
  211. package/dist/utils/feature-flags.d.ts +59 -0
  212. package/dist/utils/feature-flags.js +215 -0
  213. package/dist/utils/files/base.d.ts +173 -0
  214. package/dist/utils/files/base.js +5 -0
  215. package/dist/utils/files/binary.d.ts +21 -0
  216. package/dist/utils/files/binary.js +65 -0
  217. package/dist/utils/files/docx.d.ts +47 -0
  218. package/dist/utils/files/docx.js +679 -0
  219. package/dist/utils/files/excel.d.ts +24 -0
  220. package/dist/utils/files/excel.js +437 -0
  221. package/dist/utils/files/factory.d.ts +41 -0
  222. package/dist/utils/files/factory.js +113 -0
  223. package/dist/utils/files/image.d.ts +21 -0
  224. package/dist/utils/files/image.js +78 -0
  225. package/dist/utils/files/index.d.ts +10 -0
  226. package/dist/utils/files/index.js +13 -0
  227. package/dist/utils/files/pdf.d.ts +32 -0
  228. package/dist/utils/files/pdf.js +142 -0
  229. package/dist/utils/files/text.d.ts +63 -0
  230. package/dist/utils/files/text.js +370 -0
  231. package/dist/utils/fuzzySearchLogger.d.ts +30 -0
  232. package/dist/utils/fuzzySearchLogger.js +126 -0
  233. package/dist/utils/lineEndingHandler.d.ts +21 -0
  234. package/dist/utils/lineEndingHandler.js +77 -0
  235. package/dist/utils/logger.d.ts +32 -0
  236. package/dist/utils/logger.js +72 -0
  237. package/dist/utils/mcp-ui-ab-test.d.ts +13 -0
  238. package/dist/utils/mcp-ui-ab-test.js +62 -0
  239. package/dist/utils/open-browser.d.ts +9 -0
  240. package/dist/utils/open-browser.js +42 -0
  241. package/dist/utils/process-detection.d.ts +23 -0
  242. package/dist/utils/process-detection.js +150 -0
  243. package/dist/utils/ripgrep-resolver.d.ts +9 -0
  244. package/dist/utils/ripgrep-resolver.js +74 -0
  245. package/dist/utils/system-info.d.ts +71 -0
  246. package/dist/utils/system-info.js +712 -0
  247. package/dist/utils/toolHistory.d.ts +86 -0
  248. package/dist/utils/toolHistory.js +257 -0
  249. package/dist/utils/trackTools.d.ts +6 -0
  250. package/dist/utils/trackTools.js +54 -0
  251. package/dist/utils/unsupportedParams.d.ts +24 -0
  252. package/dist/utils/unsupportedParams.js +66 -0
  253. package/dist/utils/usageTracker.d.ts +133 -0
  254. package/dist/utils/usageTracker.js +477 -0
  255. package/dist/utils/welcome-onboarding.d.ts +11 -0
  256. package/dist/utils/welcome-onboarding.js +99 -0
  257. package/dist/utils/withTimeout.d.ts +28 -0
  258. package/dist/utils/withTimeout.js +85 -0
  259. package/dist/version.d.ts +1 -0
  260. package/dist/version.js +1 -0
  261. package/package.json +131 -0
@@ -0,0 +1,440 @@
1
+ import { readFile, readMultipleFiles, writeFile, createDirectory, listDirectory, moveFile, getFileInfo, writePdf, getDefaultEditorMetadata } from '../tools/filesystem.js';
2
+ import { withTimeout } from '../utils/withTimeout.js';
3
+ import { createErrorResponse } from '../error-handlers.js';
4
+ import { configManager } from '../config-manager.js';
5
+ import { ReadFileArgsSchema, ReadMultipleFilesArgsSchema, WriteFileArgsSchema, CreateDirectoryArgsSchema, ListDirectoryArgsSchema, MoveFileArgsSchema, GetFileInfoArgsSchema, WritePdfArgsSchema } from '../tools/schemas.js';
6
+ import path from 'path';
7
+ import os from 'os';
8
+ import { resolvePreviewFileType } from '../ui/file-preview/shared/preview-file-types.js';
9
+ /**
10
+ * Expand home directory (~) in a file path
11
+ */
12
+ function expandHome(filePath) {
13
+ if (filePath === '~' || filePath.startsWith('~/') || filePath.startsWith(`~${path.sep}`)) {
14
+ return path.join(os.homedir(), filePath.slice(1));
15
+ }
16
+ return filePath;
17
+ }
18
+ /**
19
+ * Resolve a file path to an absolute path for use in structured content.
20
+ * This ensures "Open in folder" always has a valid absolute path.
21
+ */
22
+ export function resolveAbsolutePath(filePath) {
23
+ const expanded = expandHome(filePath);
24
+ return path.isAbsolute(expanded)
25
+ ? path.resolve(expanded)
26
+ : path.resolve(process.cwd(), expanded);
27
+ }
28
+ /**
29
+ * Helper function to check if path contains an error
30
+ */
31
+ function isErrorPath(filePath) {
32
+ return filePath.startsWith('__ERROR__:');
33
+ }
34
+ /**
35
+ * Extract error message from error path
36
+ */
37
+ function getErrorFromPath(path) {
38
+ return path.substring('__ERROR__:'.length).trim();
39
+ }
40
+ /**
41
+ * Handle read_file command
42
+ */
43
+ export async function handleReadFile(args) {
44
+ // Backstop for the whole handler operation. The real control is the
45
+ // 3-minute cancellable read timeout inside readFileFromDisk; this sits just
46
+ // above it (so that one fires first, with cleanup + a useful error) but
47
+ // still below the MCP client's ~4-minute hard cap, so we never leave the
48
+ // client hanging on an opaque timeout.
49
+ const HANDLER_TIMEOUT = 3.5 * 60 * 1000; // 3m30s
50
+ // Add input validation
51
+ if (args === null || args === undefined) {
52
+ return createErrorResponse('No arguments provided for read_file command');
53
+ }
54
+ const readFileOperation = async () => {
55
+ const parsed = ReadFileArgsSchema.parse(args);
56
+ // Get the configuration for file read limits
57
+ const config = await configManager.getConfig();
58
+ if (!config) {
59
+ return createErrorResponse('Configuration not available');
60
+ }
61
+ const defaultLimit = config.fileReadLineLimit ?? 1000;
62
+ // Convert sheet parameter: numeric strings become numbers for Excel index access
63
+ let sheetParam = parsed.sheet;
64
+ if (parsed.sheet !== undefined && /^\d+$/.test(parsed.sheet)) {
65
+ sheetParam = parseInt(parsed.sheet, 10);
66
+ }
67
+ const options = {
68
+ isUrl: parsed.isUrl,
69
+ offset: parsed.offset ?? 0,
70
+ length: parsed.length ?? defaultLimit,
71
+ sheet: sheetParam,
72
+ range: parsed.range
73
+ };
74
+ // Resolve to absolute path for local files (not URLs) so "Open in folder" works
75
+ const resolvedFilePath = parsed.isUrl
76
+ ? parsed.path
77
+ : resolveAbsolutePath(parsed.path);
78
+ const fileResult = await readFile(parsed.path, options);
79
+ // Handle PDF files
80
+ if (fileResult.metadata?.isPdf) {
81
+ const meta = fileResult.metadata;
82
+ const author = meta?.author ? `, Author: ${meta?.author}` : "";
83
+ const title = meta?.title ? `, Title: ${meta?.title}` : "";
84
+ const pdfContent = fileResult.metadata?.pages?.flatMap((p) => [
85
+ ...(p.images?.map((image) => ({
86
+ type: "image",
87
+ data: image.data,
88
+ mimeType: image.mimeType
89
+ })) ?? []),
90
+ {
91
+ type: "text",
92
+ text: `<!-- Page: ${p.pageNumber} -->\n${p.text}`,
93
+ },
94
+ ]) ?? [];
95
+ return {
96
+ content: [
97
+ {
98
+ type: "text",
99
+ text: `PDF file: ${parsed.path}${author}${title} (${meta?.totalPages} pages) \n`
100
+ },
101
+ ...pdfContent
102
+ ],
103
+ ...(parsed.origin === 'ui' ? {
104
+ structuredContent: {
105
+ fileName: path.basename(resolvedFilePath),
106
+ filePath: resolvedFilePath,
107
+ fileType: 'unsupported',
108
+ ...await getDefaultEditorMetadata(resolvedFilePath),
109
+ },
110
+ } : {}),
111
+ };
112
+ }
113
+ // Handle image files
114
+ if (fileResult.metadata?.isImage) {
115
+ // Return the image bytes in the MCP content array so the host model can
116
+ // actually see the image. The preview widget gets its copy from its own
117
+ // origin:'ui' read — structuredContent stays metadata-only.
118
+ const imageData = typeof fileResult.content === 'string'
119
+ ? fileResult.content
120
+ : fileResult.content.toString('base64');
121
+ const imageSummary = `Image file: ${parsed.path} (${fileResult.mimeType})\n`;
122
+ const imageStructuredContent = {
123
+ fileName: path.basename(resolvedFilePath),
124
+ filePath: resolvedFilePath,
125
+ fileType: 'image',
126
+ ...await getDefaultEditorMetadata(resolvedFilePath),
127
+ mimeType: fileResult.mimeType,
128
+ };
129
+ // Widget pull (origin: 'ui'): return the base64 in a TEXT block, never
130
+ // an image block. An image content block makes the host inline-vision-
131
+ // render the result, which preempts delivery of this RPC response to
132
+ // the widget — leaving the preview stuck on "Preparing preview…" for
133
+ // exactly the host-rendered types (png/jpeg/gif/webp). Text-only lets
134
+ // the RPC response through so the widget can draw the <img>.
135
+ if (parsed.origin === 'ui') {
136
+ return {
137
+ content: [{ type: "text", text: imageData }],
138
+ structuredContent: imageStructuredContent,
139
+ };
140
+ }
141
+ // Model-facing read: keep the image block so the host/model sees it.
142
+ // No structuredContent — the widget renders from its own origin:'ui'
143
+ // read, and nothing else consumes it.
144
+ return {
145
+ content: [
146
+ {
147
+ type: "text",
148
+ text: imageSummary
149
+ },
150
+ {
151
+ type: "image",
152
+ data: imageData,
153
+ mimeType: fileResult.mimeType
154
+ }
155
+ ],
156
+ };
157
+ }
158
+ else {
159
+ // For all other files, return as text.
160
+ // structuredContent carries only file metadata (no content duplication);
161
+ // the widget reads text from the MCP content array (over the RPC read).
162
+ let textContent = typeof fileResult.content === 'string'
163
+ ? fileResult.content
164
+ : fileResult.content.toString('utf8');
165
+ const fileType = fileResult.metadata?.isDirectory ? 'directory' : resolvePreviewFileType(resolvedFilePath);
166
+ // The directory fallback prefixes a "use list_directory instead" hint
167
+ // for the LLM. The widget's own read (a list_directory preview pulls
168
+ // read_file on the dir path) would render that hint as a notice — strip it.
169
+ if (parsed.origin === 'ui' && fileType === 'directory') {
170
+ textContent = textContent.replace(/^This is a directory, not a file\.[^\n]*\n+/, '');
171
+ }
172
+ return {
173
+ content: [{ type: "text", text: textContent }],
174
+ ...(parsed.origin === 'ui' ? {
175
+ structuredContent: {
176
+ fileName: path.basename(resolvedFilePath),
177
+ filePath: resolvedFilePath,
178
+ fileType,
179
+ ...await getDefaultEditorMetadata(resolvedFilePath),
180
+ },
181
+ } : {}),
182
+ };
183
+ }
184
+ };
185
+ // Execute with timeout at the handler level
186
+ const result = await withTimeout(readFileOperation(), HANDLER_TIMEOUT, 'Read file handler operation', null);
187
+ if (result == null) {
188
+ // Handles the impossible case where withTimeout resolves to null instead of throwing
189
+ throw new Error('Failed to read the file');
190
+ }
191
+ return result;
192
+ }
193
+ /**
194
+ * Handle read_multiple_files command
195
+ */
196
+ export async function handleReadMultipleFiles(args) {
197
+ const parsed = ReadMultipleFilesArgsSchema.parse(args);
198
+ const fileResults = await readMultipleFiles(parsed.paths);
199
+ // Create a text summary of all files
200
+ const textSummary = fileResults.map(result => {
201
+ if (result.error) {
202
+ return `${result.path}: Error - ${result.error}`;
203
+ }
204
+ else if (result.isPdf) {
205
+ return `${result.path}: PDF file with ${result.payload?.pages?.length} pages`;
206
+ }
207
+ else if (result.mimeType) {
208
+ return `${result.path}: ${result.mimeType} ${result.isImage ? '(image)' : '(text)'}`;
209
+ }
210
+ else {
211
+ return `${result.path}: Unknown type`;
212
+ }
213
+ }).join("\n");
214
+ // Create content items for each file
215
+ const contentItems = [];
216
+ // Add the text summary
217
+ contentItems.push({ type: "text", text: textSummary });
218
+ // Add each file content
219
+ for (const result of fileResults) {
220
+ if (!result.error && result.content !== undefined) {
221
+ if (result.isPdf) {
222
+ result.payload?.pages.forEach((page, i) => {
223
+ page.images.forEach((image, i) => {
224
+ contentItems.push({
225
+ type: "image",
226
+ data: image.data,
227
+ mimeType: image.mimeType
228
+ });
229
+ });
230
+ contentItems.push({
231
+ type: "text",
232
+ text: page.text,
233
+ });
234
+ });
235
+ }
236
+ else if (result.isImage && result.mimeType) {
237
+ // For image files, add an image content item
238
+ contentItems.push({
239
+ type: "image",
240
+ data: result.content,
241
+ mimeType: result.mimeType
242
+ });
243
+ }
244
+ else {
245
+ // For text files, add a text summary
246
+ contentItems.push({
247
+ type: "text",
248
+ text: `\n--- ${result.path} contents: ---\n${result.content}`
249
+ });
250
+ }
251
+ }
252
+ }
253
+ return { content: contentItems };
254
+ }
255
+ /**
256
+ * Handle write_file command
257
+ */
258
+ export async function handleWriteFile(args) {
259
+ try {
260
+ const modeProvided = !!(args && typeof args === 'object' && 'mode' in args);
261
+ const parsed = WriteFileArgsSchema.parse(args);
262
+ // An omitted `mode` falls back to 'rewrite', which silently destroys
263
+ // the target's existing content. The common failure is an LLM caller
264
+ // intending to append but dropping the optional param (issue #541), so
265
+ // require explicit intent when the target already has content;
266
+ // new/empty files keep the zero-friction default.
267
+ if (!modeProvided) {
268
+ let existing = null;
269
+ try {
270
+ existing = await getFileInfo(parsed.path);
271
+ }
272
+ catch {
273
+ // Missing file or invalid path — nothing to protect; the write
274
+ // itself will surface any real path error.
275
+ }
276
+ if (existing?.isFile && existing.size > 0) {
277
+ return createErrorResponse(`Write rejected to prevent accidental data loss: ${parsed.path} already exists ` +
278
+ `with content (${existing.size} bytes), and no 'mode' was specified — the default ` +
279
+ `mode 'rewrite' would REPLACE the entire file. Retry with an explicit mode: ` +
280
+ `'append' to add your content to the end of the existing file, or 'rewrite' ` +
281
+ `to replace all existing content.`);
282
+ }
283
+ }
284
+ // Get the line limit from configuration
285
+ const config = await configManager.getConfig();
286
+ const MAX_LINES = config.fileWriteLineLimit ?? 50; // Default to 50 if not set
287
+ // Strictly enforce line count limit
288
+ const lines = parsed.content.split('\n');
289
+ const lineCount = lines.length;
290
+ let errorMessage = "";
291
+ if (lineCount > MAX_LINES) {
292
+ errorMessage = `✅ File written successfully! (${lineCount} lines)
293
+
294
+ 💡 Performance tip: For optimal speed, consider chunking files into ≤30 line pieces in future operations.`;
295
+ }
296
+ // Pass the mode parameter to writeFile
297
+ await writeFile(parsed.path, parsed.content, parsed.mode);
298
+ // Provide more informative message based on mode
299
+ const modeMessage = parsed.mode === 'append' ? 'appended to' : 'wrote to';
300
+ // No structuredContent: nothing in the UI calls write_file (the widget
301
+ // previews the write via its own read_file pull at tool-result time).
302
+ return {
303
+ content: [{
304
+ type: "text",
305
+ text: `Successfully ${modeMessage} ${parsed.path} (${lineCount} lines) ${errorMessage}`
306
+ }],
307
+ };
308
+ }
309
+ catch (error) {
310
+ const errorMessage = error instanceof Error ? error.message : String(error);
311
+ return createErrorResponse(errorMessage);
312
+ }
313
+ }
314
+ /**
315
+ * Handle create_directory command
316
+ */
317
+ export async function handleCreateDirectory(args) {
318
+ try {
319
+ const parsed = CreateDirectoryArgsSchema.parse(args);
320
+ await createDirectory(parsed.path);
321
+ return {
322
+ content: [{ type: "text", text: `Successfully created directory ${parsed.path}` }],
323
+ };
324
+ }
325
+ catch (error) {
326
+ const errorMessage = error instanceof Error ? error.message : String(error);
327
+ return createErrorResponse(errorMessage);
328
+ }
329
+ }
330
+ /**
331
+ * Handle list_directory command
332
+ */
333
+ export async function handleListDirectory(args) {
334
+ try {
335
+ const startTime = Date.now();
336
+ const parsed = ListDirectoryArgsSchema.parse(args);
337
+ const entries = await listDirectory(parsed.path, parsed.depth);
338
+ const duration = Date.now() - startTime;
339
+ const resultText = entries.join('\n');
340
+ const resolvedPath = resolveAbsolutePath(parsed.path);
341
+ return {
342
+ content: [{ type: "text", text: resultText }],
343
+ ...(parsed.origin === 'ui' ? {
344
+ structuredContent: {
345
+ fileName: path.basename(resolvedPath),
346
+ filePath: resolvedPath,
347
+ fileType: 'directory',
348
+ },
349
+ } : {}),
350
+ };
351
+ }
352
+ catch (error) {
353
+ const errorMessage = error instanceof Error ? error.message : String(error);
354
+ return createErrorResponse(errorMessage);
355
+ }
356
+ }
357
+ /**
358
+ * Handle move_file command
359
+ */
360
+ export async function handleMoveFile(args) {
361
+ try {
362
+ const parsed = MoveFileArgsSchema.parse(args);
363
+ await moveFile(parsed.source, parsed.destination);
364
+ return {
365
+ content: [{ type: "text", text: `Successfully moved ${parsed.source} to ${parsed.destination}` }],
366
+ };
367
+ }
368
+ catch (error) {
369
+ const errorMessage = error instanceof Error ? error.message : String(error);
370
+ return createErrorResponse(errorMessage);
371
+ }
372
+ }
373
+ /**
374
+ * Format a value for display, handling objects and arrays
375
+ */
376
+ function formatValue(value, indent = '') {
377
+ if (value === null || value === undefined) {
378
+ return String(value);
379
+ }
380
+ if (Array.isArray(value)) {
381
+ if (value.length === 0)
382
+ return '[]';
383
+ // For arrays of objects (like sheets), format each item
384
+ const items = value.map((item, i) => {
385
+ if (typeof item === 'object' && item !== null) {
386
+ const props = Object.entries(item)
387
+ .map(([k, v]) => `${k}: ${v}`)
388
+ .join(', ');
389
+ return `${indent} [${i}] { ${props} }`;
390
+ }
391
+ return `${indent} [${i}] ${item}`;
392
+ });
393
+ return `\n${items.join('\n')}`;
394
+ }
395
+ if (typeof value === 'object') {
396
+ return JSON.stringify(value);
397
+ }
398
+ return String(value);
399
+ }
400
+ /**
401
+ * Handle get_file_info command
402
+ */
403
+ export async function handleGetFileInfo(args) {
404
+ try {
405
+ const parsed = GetFileInfoArgsSchema.parse(args);
406
+ const info = await getFileInfo(parsed.path);
407
+ // Generic formatting for any file type
408
+ const formattedText = Object.entries(info)
409
+ .map(([key, value]) => `${key}: ${formatValue(value)}`)
410
+ .join('\n');
411
+ return {
412
+ content: [{
413
+ type: "text",
414
+ text: formattedText
415
+ }],
416
+ };
417
+ }
418
+ catch (error) {
419
+ const errorMessage = error instanceof Error ? error.message : String(error);
420
+ return createErrorResponse(errorMessage);
421
+ }
422
+ }
423
+ // Use get_config to retrieve the allowedDirectories configuration
424
+ /**
425
+ * Handle write_pdf command
426
+ */
427
+ export async function handleWritePdf(args) {
428
+ try {
429
+ const parsed = WritePdfArgsSchema.parse(args);
430
+ await writePdf(parsed.path, parsed.content, parsed.outputPath, parsed.options);
431
+ const targetPath = parsed.outputPath || parsed.path;
432
+ return {
433
+ content: [{ type: "text", text: `Successfully wrote PDF to ${targetPath}${parsed.outputPath ? `\nOriginal file: ${parsed.path}` : ''}` }],
434
+ };
435
+ }
436
+ catch (error) {
437
+ const errorMessage = error instanceof Error ? error.message : String(error);
438
+ return createErrorResponse(errorMessage);
439
+ }
440
+ }
@@ -0,0 +1,12 @@
1
+ import { ServerResult } from '../types.js';
2
+ type TrackUiEventParams = Record<string, string | number | boolean | null>;
3
+ export declare function buildTrackUiEventCapturePayload(event: string, component: string, params: TrackUiEventParams): Record<string, string | number | boolean | null>;
4
+ /**
5
+ * Handle get_recent_tool_calls command
6
+ */
7
+ export declare function handleGetRecentToolCalls(args: unknown): Promise<ServerResult>;
8
+ /**
9
+ * Handle track_ui_event command
10
+ */
11
+ export declare function handleTrackUiEvent(args: unknown): Promise<ServerResult>;
12
+ export {};
@@ -0,0 +1,67 @@
1
+ import { toolHistory } from '../utils/toolHistory.js';
2
+ import { GetRecentToolCallsArgsSchema, TrackUiEventArgsSchema } from '../tools/schemas.js';
3
+ import { capture_ui_event } from '../utils/capture.js';
4
+ export function buildTrackUiEventCapturePayload(event, component, params) {
5
+ return {
6
+ ...params,
7
+ component,
8
+ event
9
+ };
10
+ }
11
+ /**
12
+ * Handle get_recent_tool_calls command
13
+ */
14
+ export async function handleGetRecentToolCalls(args) {
15
+ try {
16
+ const parsed = GetRecentToolCallsArgsSchema.parse(args);
17
+ // Use formatted version with local timezone
18
+ const calls = toolHistory.getRecentCallsFormatted({
19
+ maxResults: parsed.maxResults,
20
+ toolName: parsed.toolName,
21
+ since: parsed.since
22
+ });
23
+ const stats = toolHistory.getStats();
24
+ // Format the response (excluding file path per user request)
25
+ const summary = `Tool Call History (${calls.length} results, ${stats.totalEntries} total in memory)`;
26
+ const historyJson = JSON.stringify(calls, null, 2);
27
+ return {
28
+ content: [{
29
+ type: "text",
30
+ text: `${summary}\n\n${historyJson}`
31
+ }]
32
+ };
33
+ }
34
+ catch (error) {
35
+ return {
36
+ content: [{
37
+ type: "text",
38
+ text: `Error getting tool history: ${error instanceof Error ? error.message : String(error)}`
39
+ }],
40
+ isError: true
41
+ };
42
+ }
43
+ }
44
+ /**
45
+ * Handle track_ui_event command
46
+ */
47
+ export async function handleTrackUiEvent(args) {
48
+ try {
49
+ const parsed = TrackUiEventArgsSchema.parse(args);
50
+ await capture_ui_event('mcp_ui_event', buildTrackUiEventCapturePayload(parsed.event, parsed.component, parsed.params));
51
+ return {
52
+ content: [{
53
+ type: "text",
54
+ text: `Tracked UI event: ${parsed.event}`
55
+ }]
56
+ };
57
+ }
58
+ catch (error) {
59
+ return {
60
+ content: [{
61
+ type: "text",
62
+ text: `Error tracking UI event: ${error instanceof Error ? error.message : String(error)}`
63
+ }],
64
+ isError: true
65
+ };
66
+ }
67
+ }
@@ -0,0 +1,6 @@
1
+ export * from './filesystem-handlers.js';
2
+ export * from './terminal-handlers.js';
3
+ export * from './process-handlers.js';
4
+ export * from './edit-search-handlers.js';
5
+ export * from './search-handlers.js';
6
+ export * from './history-handlers.js';
@@ -0,0 +1,7 @@
1
+ // Export all handlers from their respective files
2
+ export * from './filesystem-handlers.js';
3
+ export * from './terminal-handlers.js';
4
+ export * from './process-handlers.js';
5
+ export * from './edit-search-handlers.js';
6
+ export * from './search-handlers.js';
7
+ export * from './history-handlers.js';
@@ -0,0 +1,9 @@
1
+ import { ServerResult } from '../types.js';
2
+ /**
3
+ * Handle list_processes command
4
+ */
5
+ export declare function handleListProcesses(): Promise<ServerResult>;
6
+ /**
7
+ * Handle kill_process command
8
+ */
9
+ export declare function handleKillProcess(args: unknown): Promise<ServerResult>;
@@ -0,0 +1,15 @@
1
+ import { listProcesses, killProcess } from '../tools/process.js';
2
+ import { KillProcessArgsSchema } from '../tools/schemas.js';
3
+ /**
4
+ * Handle list_processes command
5
+ */
6
+ export async function handleListProcesses() {
7
+ return listProcesses();
8
+ }
9
+ /**
10
+ * Handle kill_process command
11
+ */
12
+ export async function handleKillProcess(args) {
13
+ const parsed = KillProcessArgsSchema.parse(args);
14
+ return killProcess(parsed);
15
+ }
@@ -0,0 +1,17 @@
1
+ import { ServerResult } from '../types.js';
2
+ /**
3
+ * Handle start_search command
4
+ */
5
+ export declare function handleStartSearch(args: unknown): Promise<ServerResult>;
6
+ /**
7
+ * Handle get_more_search_results command
8
+ */
9
+ export declare function handleGetMoreSearchResults(args: unknown): Promise<ServerResult>;
10
+ /**
11
+ * Handle stop_search command
12
+ */
13
+ export declare function handleStopSearch(args: unknown): Promise<ServerResult>;
14
+ /**
15
+ * Handle list_searches command
16
+ */
17
+ export declare function handleListSearches(): Promise<ServerResult>;