@wonderwhy-er/desktop-commander 0.1.39 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -5
- package/dist/config-manager.d.ts +2 -0
- package/dist/config-manager.js +5 -1
- package/dist/config.d.ts +1 -0
- package/dist/config.js +1 -0
- package/dist/handlers/filesystem-handlers.js +37 -3
- package/dist/handlers/fuzzy-search-log-handlers.d.ts +13 -0
- package/dist/handlers/fuzzy-search-log-handlers.js +179 -0
- package/dist/server.js +219 -42
- package/dist/setup-claude-server.js +34 -26
- package/dist/tools/edit.js +55 -7
- package/dist/tools/filesystem.d.ts +7 -5
- package/dist/tools/filesystem.js +97 -25
- package/dist/tools/schemas.d.ts +9 -0
- package/dist/tools/schemas.js +3 -0
- package/dist/utils/fuzzySearchLogger.d.ts +30 -0
- package/dist/utils/fuzzySearchLogger.js +126 -0
- package/dist/utils/trackTools.d.ts +6 -0
- package/dist/utils/trackTools.js +54 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +7 -2
package/README.md
CHANGED
|
@@ -58,6 +58,10 @@ Execute long-running terminal commands on your computer and manage processes thr
|
|
|
58
58
|
- Multiple file support
|
|
59
59
|
- Pattern-based replacements
|
|
60
60
|
- vscode-ripgrep based recursive code or text search in folders
|
|
61
|
+
- Comprehensive audit logging:
|
|
62
|
+
- All tool calls are automatically logged
|
|
63
|
+
- Log rotation with 10MB size limit
|
|
64
|
+
- Detailed timestamps and arguments
|
|
61
65
|
|
|
62
66
|
## Installation
|
|
63
67
|
First, ensure you've downloaded and installed the [Claude Desktop app](https://claude.ai/download) and you have [npm installed](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm).
|
|
@@ -140,24 +144,24 @@ The server provides a comprehensive set of tools organized into several categori
|
|
|
140
144
|
|
|
141
145
|
| Category | Tool | Description |
|
|
142
146
|
|----------|------|-------------|
|
|
143
|
-
| **Configuration** | `get_config` | Get the complete server configuration as JSON (includes blockedCommands, defaultShell, allowedDirectories) |
|
|
144
|
-
| | `set_config_value` | Set a specific configuration value by key. Available settings: <br>• `blockedCommands`: Array of shell commands that cannot be executed<br>• `defaultShell`: Shell to use for commands (e.g., bash, zsh, powershell)<br>• `allowedDirectories`: Array of filesystem paths the server can access for file operations (⚠️ terminal commands can still access files outside these directories) |
|
|
147
|
+
| **Configuration** | `get_config` | Get the complete server configuration as JSON (includes blockedCommands, defaultShell, allowedDirectories, fileReadLineLimit, fileWriteLineLimit, telemetryEnabled) |
|
|
148
|
+
| | `set_config_value` | Set a specific configuration value by key. Available settings: <br>• `blockedCommands`: Array of shell commands that cannot be executed<br>• `defaultShell`: Shell to use for commands (e.g., bash, zsh, powershell)<br>• `allowedDirectories`: Array of filesystem paths the server can access for file operations (⚠️ terminal commands can still access files outside these directories)<br>• `fileReadLineLimit`: Maximum lines to read at once (default: 1000)<br>• `fileWriteLineLimit`: Maximum lines to write at once (default: 50)<br>• `telemetryEnabled`: Enable/disable telemetry (boolean) |
|
|
145
149
|
| **Terminal** | `execute_command` | Execute a terminal command with configurable timeout and shell selection |
|
|
146
150
|
| | `read_output` | Read new output from a running terminal session |
|
|
147
151
|
| | `force_terminate` | Force terminate a running terminal session |
|
|
148
152
|
| | `list_sessions` | List all active terminal sessions |
|
|
149
153
|
| | `list_processes` | List all running processes with detailed information |
|
|
150
154
|
| | `kill_process` | Terminate a running process by PID |
|
|
151
|
-
| **Filesystem** | `read_file` | Read contents from local filesystem or URLs (supports
|
|
155
|
+
| **Filesystem** | `read_file` | Read contents from local filesystem or URLs with line-based pagination (supports offset and length parameters) |
|
|
152
156
|
| | `read_multiple_files` | Read multiple files simultaneously |
|
|
153
|
-
| | `write_file` |
|
|
157
|
+
| | `write_file` | Write file contents with options for rewrite or append mode (uses configurable line limits) |
|
|
154
158
|
| | `create_directory` | Create a new directory or ensure it exists |
|
|
155
159
|
| | `list_directory` | Get detailed listing of files and directories |
|
|
156
160
|
| | `move_file` | Move or rename files and directories |
|
|
157
161
|
| | `search_files` | Find files by name using case-insensitive substring matching |
|
|
158
162
|
| | `search_code` | Search for text/code patterns within file contents using ripgrep |
|
|
159
163
|
| | `get_file_info` | Retrieve detailed metadata about a file or directory |
|
|
160
|
-
| **Text Editing** | `edit_block` | Apply
|
|
164
|
+
| **Text Editing** | `edit_block` | Apply targeted text replacements with enhanced prompting for smaller edits (includes character-level diff feedback) |
|
|
161
165
|
|
|
162
166
|
### Tool Usage Examples
|
|
163
167
|
|
|
@@ -181,6 +185,18 @@ console.log("new message");
|
|
|
181
185
|
>>>>>>> REPLACE
|
|
182
186
|
```
|
|
183
187
|
|
|
188
|
+
### Enhanced Edit Block Features
|
|
189
|
+
|
|
190
|
+
The `edit_block` tool includes several enhancements for better reliability:
|
|
191
|
+
|
|
192
|
+
1. **Improved Prompting**: Tool descriptions now emphasize making multiple small, focused edits rather than one large change
|
|
193
|
+
2. **Fuzzy Search Fallback**: When exact matches fail, it performs fuzzy search and provides detailed feedback
|
|
194
|
+
3. **Character-level Diffs**: Shows exactly what's different using `{-removed-}{+added+}` format
|
|
195
|
+
4. **Multiple Occurrence Support**: Can replace multiple instances with `expected_replacements` parameter
|
|
196
|
+
5. **Comprehensive Logging**: All fuzzy searches are logged for analysis and debugging
|
|
197
|
+
|
|
198
|
+
When a search fails, you'll see detailed information about the closest match found, including similarity percentage, execution time, and character differences. All these details are automatically logged for later analysis using the fuzzy search log tools.
|
|
199
|
+
|
|
184
200
|
### URL Support
|
|
185
201
|
- `read_file` can now fetch content from both local files and URLs
|
|
186
202
|
- Example: `read_file` with `isUrl: true` parameter to read from web resources
|
|
@@ -189,6 +205,69 @@ console.log("new message");
|
|
|
189
205
|
- Claude can see and analyze the actual image content
|
|
190
206
|
- Default 30-second timeout for URL requests
|
|
191
207
|
|
|
208
|
+
## Fuzzy Search Log Analysis (npm scripts)
|
|
209
|
+
|
|
210
|
+
The fuzzy search logging system includes convenient npm scripts for analyzing logs outside of the MCP environment:
|
|
211
|
+
|
|
212
|
+
```bash
|
|
213
|
+
# View recent fuzzy search logs
|
|
214
|
+
npm run logs:view -- --count 20
|
|
215
|
+
|
|
216
|
+
# Analyze patterns and performance
|
|
217
|
+
npm run logs:analyze -- --threshold 0.8
|
|
218
|
+
|
|
219
|
+
# Export logs to CSV or JSON
|
|
220
|
+
npm run logs:export -- --format json --output analysis.json
|
|
221
|
+
|
|
222
|
+
# Clear all logs (with confirmation)
|
|
223
|
+
npm run logs:clear
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
For detailed documentation on these scripts, see [scripts/README.md](scripts/README.md).
|
|
227
|
+
|
|
228
|
+
## Fuzzy Search Logs
|
|
229
|
+
|
|
230
|
+
Desktop Commander includes comprehensive logging for fuzzy search operations in the `edit_block` tool. When an exact match isn't found, the system performs a fuzzy search and logs detailed information for analysis.
|
|
231
|
+
|
|
232
|
+
### What Gets Logged
|
|
233
|
+
|
|
234
|
+
Every fuzzy search operation logs:
|
|
235
|
+
- **Search and found text**: The text you're looking for vs. what was found
|
|
236
|
+
- **Similarity score**: How close the match is (0-100%)
|
|
237
|
+
- **Execution time**: How long the search took
|
|
238
|
+
- **Character differences**: Detailed diff showing exactly what's different
|
|
239
|
+
- **File metadata**: Extension, search/found text lengths
|
|
240
|
+
- **Character codes**: Specific character codes causing differences
|
|
241
|
+
|
|
242
|
+
### Log Location
|
|
243
|
+
|
|
244
|
+
Logs are automatically saved to:
|
|
245
|
+
- **macOS/Linux**: `~/.claude-server-commander-logs/fuzzy-search.log`
|
|
246
|
+
- **Windows**: `%USERPROFILE%\.claude-server-commander-logs\fuzzy-search.log`
|
|
247
|
+
|
|
248
|
+
### What You'll Learn
|
|
249
|
+
|
|
250
|
+
The fuzzy search logs help you understand:
|
|
251
|
+
1. **Why exact matches fail**: Common issues like whitespace differences, line endings, or character encoding
|
|
252
|
+
2. **Performance patterns**: How search complexity affects execution time
|
|
253
|
+
3. **File type issues**: Which file extensions commonly have matching problems
|
|
254
|
+
4. **Character encoding problems**: Specific character codes that cause diffs
|
|
255
|
+
|
|
256
|
+
## Audit Logging
|
|
257
|
+
|
|
258
|
+
Desktop Commander now includes comprehensive logging for all tool calls:
|
|
259
|
+
|
|
260
|
+
### What Gets Logged
|
|
261
|
+
- Every tool call is logged with timestamp, tool name, and arguments (sanitized for privacy)
|
|
262
|
+
- Logs are rotated automatically when they reach 10MB in size
|
|
263
|
+
|
|
264
|
+
### Log Location
|
|
265
|
+
Logs are saved to:
|
|
266
|
+
- **macOS/Linux**: `~/.claude-server-commander/claude_tool_call.log`
|
|
267
|
+
- **Windows**: `%USERPROFILE%\.claude-server-commander\claude_tool_call.log`
|
|
268
|
+
|
|
269
|
+
This audit trail helps with debugging, security monitoring, and understanding how Claude is interacting with your system.
|
|
270
|
+
|
|
192
271
|
## Handling Long-Running Commands
|
|
193
272
|
|
|
194
273
|
For commands that may take a while:
|
|
@@ -297,6 +376,8 @@ This project extends the MCP Filesystem Server to enable:
|
|
|
297
376
|
Created as part of exploring Claude MCPs: https://youtube.com/live/TlbjFDbl5Us
|
|
298
377
|
|
|
299
378
|
## DONE
|
|
379
|
+
- **20-05-2025 v0.1.40 Release** - Added audit logging for all tool calls, improved line-based file operations, enhanced edit_block with better prompting for smaller edits, added explicit telemetry opt-out prompting
|
|
380
|
+
- **05-05-2025 Fuzzy Search Logging** - Added comprehensive logging system for fuzzy search operations with detailed analysis tools, character-level diffs, and performance metrics to help debug edit_block failures
|
|
300
381
|
- **29-04-2025 Telemetry Opt Out through configuration** - There is now setting to disable telemetry in config, ask in chat
|
|
301
382
|
- **23-04-2025 Enhanced edit functionality** - Improved format, added fuzzy search and multi-occurrence replacements, should fail less and use edit block more often
|
|
302
383
|
- **16-04-2025 Better configurations** - Improved settings for allowed paths, commands and shell environments
|
|
@@ -333,11 +414,13 @@ The following features are currently being explored:
|
|
|
333
414
|
<ul style="list-style-type: none; padding: 0;">
|
|
334
415
|
<li>🌟 <a href="https://github.com/sponsors/wonderwhy-er"><strong>GitHub Sponsors</strong></a> - Recurring support</li>
|
|
335
416
|
<li>☕ <a href="https://www.buymeacoffee.com/wonderwhyer"><strong>Buy Me A Coffee</strong></a> - One-time contributions</li>
|
|
417
|
+
<li>💖 <a href="https://www.patreon.com/c/EduardsRuzga"><strong>Patreon</strong></a> - Become a patron and support us monthly</li>
|
|
336
418
|
<li>⭐ <a href="https://github.com/wonderwhy-er/DesktopCommanderMCP"><strong>Star on GitHub</strong></a> - Help others discover the project</li>
|
|
337
419
|
</ul>
|
|
338
420
|
</div>
|
|
339
421
|
</div>
|
|
340
422
|
|
|
423
|
+
|
|
341
424
|
### Supporters Hall of Fame
|
|
342
425
|
|
|
343
426
|
Generous supporters are featured here. Thank you for helping make this project possible!
|
package/dist/config-manager.d.ts
CHANGED
package/dist/config-manager.js
CHANGED
|
@@ -3,6 +3,7 @@ import path from 'path';
|
|
|
3
3
|
import { existsSync } from 'fs';
|
|
4
4
|
import { mkdir } from 'fs/promises';
|
|
5
5
|
import os from 'os';
|
|
6
|
+
import { VERSION } from './version.js';
|
|
6
7
|
import { CONFIG_FILE } from './config.js';
|
|
7
8
|
/**
|
|
8
9
|
* Singleton config manager for the server
|
|
@@ -39,6 +40,7 @@ class ConfigManager {
|
|
|
39
40
|
this.config = this.getDefaultConfig();
|
|
40
41
|
await this.saveConfig();
|
|
41
42
|
}
|
|
43
|
+
this.config['version'] = VERSION;
|
|
42
44
|
this.initialized = true;
|
|
43
45
|
}
|
|
44
46
|
catch (error) {
|
|
@@ -101,7 +103,9 @@ class ConfigManager {
|
|
|
101
103
|
],
|
|
102
104
|
defaultShell: os.platform() === 'win32' ? 'powershell.exe' : 'bash',
|
|
103
105
|
allowedDirectories: [],
|
|
104
|
-
telemetryEnabled: true // Default to opt-out approach (telemetry on by default)
|
|
106
|
+
telemetryEnabled: true, // Default to opt-out approach (telemetry on by default)
|
|
107
|
+
fileWriteLineLimit: 50, // Default line limit for file write operations (changed from 100)
|
|
108
|
+
fileReadLineLimit: 1000 // Default line limit for file read operations (changed from character-based)
|
|
105
109
|
};
|
|
106
110
|
}
|
|
107
111
|
/**
|
package/dist/config.d.ts
CHANGED
package/dist/config.js
CHANGED
|
@@ -6,4 +6,5 @@ const CONFIG_DIR = path.join(USER_HOME, '.claude-server-commander');
|
|
|
6
6
|
// Paths relative to the config directory
|
|
7
7
|
export const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
|
|
8
8
|
export const TOOL_CALL_FILE = path.join(CONFIG_DIR, 'claude_tool_call.log');
|
|
9
|
+
export const TOOL_CALL_FILE_MAX_SIZE = 1024 * 1024 * 10; // 10 MB
|
|
9
10
|
export const DEFAULT_COMMAND_TIMEOUT = 1000; // milliseconds
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readFile, readMultipleFiles, writeFile, createDirectory, listDirectory, moveFile, searchFiles, getFileInfo } from '../tools/filesystem.js';
|
|
2
2
|
import { withTimeout } from '../utils/withTimeout.js';
|
|
3
3
|
import { createErrorResponse } from '../error-handlers.js';
|
|
4
|
+
import { configManager } from '../config-manager.js';
|
|
4
5
|
import { ReadFileArgsSchema, ReadMultipleFilesArgsSchema, WriteFileArgsSchema, CreateDirectoryArgsSchema, ListDirectoryArgsSchema, MoveFileArgsSchema, SearchFilesArgsSchema, GetFileInfoArgsSchema } from '../tools/schemas.js';
|
|
5
6
|
/**
|
|
6
7
|
* Helper function to check if path contains an error
|
|
@@ -19,9 +20,22 @@ function getErrorFromPath(path) {
|
|
|
19
20
|
*/
|
|
20
21
|
export async function handleReadFile(args) {
|
|
21
22
|
const HANDLER_TIMEOUT = 60000; // 60 seconds total operation timeout
|
|
23
|
+
// Add input validation
|
|
24
|
+
if (args === null || args === undefined) {
|
|
25
|
+
return createErrorResponse('No arguments provided for read_file command');
|
|
26
|
+
}
|
|
22
27
|
const readFileOperation = async () => {
|
|
23
28
|
const parsed = ReadFileArgsSchema.parse(args);
|
|
24
|
-
|
|
29
|
+
// Get the configuration for file read limits
|
|
30
|
+
const config = await configManager.getConfig();
|
|
31
|
+
if (!config) {
|
|
32
|
+
return createErrorResponse('Configuration not available');
|
|
33
|
+
}
|
|
34
|
+
const defaultLimit = config.fileReadLineLimit ?? 1000;
|
|
35
|
+
// Use the provided limits or defaults
|
|
36
|
+
const offset = parsed.offset ?? 0;
|
|
37
|
+
const length = parsed.length ?? defaultLimit;
|
|
38
|
+
const fileResult = await readFile(parsed.path, parsed.isUrl, offset, length);
|
|
25
39
|
if (fileResult.isImage) {
|
|
26
40
|
// For image files, return as an image content type
|
|
27
41
|
return {
|
|
@@ -103,9 +117,29 @@ export async function handleReadMultipleFiles(args) {
|
|
|
103
117
|
export async function handleWriteFile(args) {
|
|
104
118
|
try {
|
|
105
119
|
const parsed = WriteFileArgsSchema.parse(args);
|
|
106
|
-
|
|
120
|
+
// Get the line limit from configuration
|
|
121
|
+
const config = await configManager.getConfig();
|
|
122
|
+
const MAX_LINES = config.fileWriteLineLimit ?? 50; // Default to 50 if not set
|
|
123
|
+
// Strictly enforce line count limit
|
|
124
|
+
const lines = parsed.content.split('\n');
|
|
125
|
+
const lineCount = lines.length;
|
|
126
|
+
let errorMessage = "";
|
|
127
|
+
if (lineCount > MAX_LINES) {
|
|
128
|
+
errorMessage = `File was written with warning: Line count limit exceeded: ${lineCount} lines (maximum: ${MAX_LINES}).
|
|
129
|
+
|
|
130
|
+
SOLUTION: Split your content into smaller chunks:
|
|
131
|
+
1. First chunk: write_file(path, firstChunk, {mode: 'rewrite'})
|
|
132
|
+
2. Additional chunks: write_file(path, nextChunk, {mode: 'append'})`;
|
|
133
|
+
}
|
|
134
|
+
// Pass the mode parameter to writeFile
|
|
135
|
+
await writeFile(parsed.path, parsed.content, parsed.mode);
|
|
136
|
+
// Provide more informative message based on mode
|
|
137
|
+
const modeMessage = parsed.mode === 'append' ? 'appended to' : 'wrote to';
|
|
107
138
|
return {
|
|
108
|
-
content: [{
|
|
139
|
+
content: [{
|
|
140
|
+
type: "text",
|
|
141
|
+
text: `Successfully ${modeMessage} ${parsed.path} (${lineCount} lines) ${errorMessage}`
|
|
142
|
+
}],
|
|
109
143
|
};
|
|
110
144
|
}
|
|
111
145
|
catch (error) {
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { ServerResult } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* View recent fuzzy search logs
|
|
4
|
+
*/
|
|
5
|
+
export declare function handleViewFuzzySearchLogs(args: unknown): Promise<ServerResult>;
|
|
6
|
+
/**
|
|
7
|
+
* Analyze fuzzy search logs to identify patterns and issues
|
|
8
|
+
*/
|
|
9
|
+
export declare function handleAnalyzeFuzzySearchLogs(args: unknown): Promise<ServerResult>;
|
|
10
|
+
/**
|
|
11
|
+
* Clear fuzzy search logs
|
|
12
|
+
*/
|
|
13
|
+
export declare function handleClearFuzzySearchLogs(args: unknown): Promise<ServerResult>;
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { fuzzySearchLogger } from '../utils/fuzzySearchLogger.js';
|
|
2
|
+
import { createErrorResponse } from '../error-handlers.js';
|
|
3
|
+
import { ViewFuzzySearchLogsArgsSchema, AnalyzeFuzzySearchLogsArgsSchema, ClearFuzzySearchLogsArgsSchema } from '../tools/schemas.js';
|
|
4
|
+
/**
|
|
5
|
+
* View recent fuzzy search logs
|
|
6
|
+
*/
|
|
7
|
+
export async function handleViewFuzzySearchLogs(args) {
|
|
8
|
+
try {
|
|
9
|
+
const parsed = ViewFuzzySearchLogsArgsSchema.parse(args);
|
|
10
|
+
const logs = await fuzzySearchLogger.getRecentLogs(parsed.count);
|
|
11
|
+
const logPath = await fuzzySearchLogger.getLogPath();
|
|
12
|
+
if (logs.length === 0) {
|
|
13
|
+
return {
|
|
14
|
+
content: [{
|
|
15
|
+
type: "text",
|
|
16
|
+
text: `No fuzzy search logs found. Log file location: ${logPath}`
|
|
17
|
+
}],
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
// Parse and format logs for better readability
|
|
21
|
+
const formattedLogs = logs.map((log, index) => {
|
|
22
|
+
const parts = log.split('\t');
|
|
23
|
+
if (parts.length >= 16) {
|
|
24
|
+
const [timestamp, searchText, foundText, similarity, executionTime, exactMatchCount, expectedReplacements, fuzzyThreshold, belowThreshold, diff, searchLength, foundLength, fileExtension, characterCodes, uniqueCharacterCount, diffLength] = parts;
|
|
25
|
+
return `
|
|
26
|
+
--- Log Entry ${index + 1} ---
|
|
27
|
+
Timestamp: ${timestamp}
|
|
28
|
+
File Extension: ${fileExtension}
|
|
29
|
+
Search Text: ${searchText.replace(/\\n/g, '\n').replace(/\\t/g, '\t')}
|
|
30
|
+
Found Text: ${foundText.replace(/\\n/g, '\n').replace(/\\t/g, '\t')}
|
|
31
|
+
Similarity: ${(parseFloat(similarity) * 100).toFixed(2)}%
|
|
32
|
+
Execution Time: ${parseFloat(executionTime).toFixed(2)}ms
|
|
33
|
+
Exact Match Count: ${exactMatchCount}
|
|
34
|
+
Expected Replacements: ${expectedReplacements}
|
|
35
|
+
Below Threshold: ${belowThreshold}
|
|
36
|
+
Diff: ${diff.replace(/\\n/g, '\n').replace(/\\t/g, '\t')}
|
|
37
|
+
Search Length: ${searchLength}
|
|
38
|
+
Found Length: ${foundLength}
|
|
39
|
+
Character Codes: ${characterCodes}
|
|
40
|
+
Unique Characters: ${uniqueCharacterCount}
|
|
41
|
+
Diff Length: ${diffLength}
|
|
42
|
+
`;
|
|
43
|
+
}
|
|
44
|
+
return `Malformed log entry: ${log}`;
|
|
45
|
+
}).join('\n');
|
|
46
|
+
return {
|
|
47
|
+
content: [{
|
|
48
|
+
type: "text",
|
|
49
|
+
text: `Recent Fuzzy Search Logs (${logs.length} entries):\n\n${formattedLogs}\n\nLog file location: ${logPath}`
|
|
50
|
+
}],
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
return createErrorResponse(`Failed to view fuzzy search logs: ${error instanceof Error ? error.message : String(error)}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Analyze fuzzy search logs to identify patterns and issues
|
|
59
|
+
*/
|
|
60
|
+
export async function handleAnalyzeFuzzySearchLogs(args) {
|
|
61
|
+
try {
|
|
62
|
+
const parsed = AnalyzeFuzzySearchLogsArgsSchema.parse(args);
|
|
63
|
+
const logs = await fuzzySearchLogger.getRecentLogs(100); // Analyze more logs
|
|
64
|
+
const logPath = await fuzzySearchLogger.getLogPath();
|
|
65
|
+
if (logs.length === 0) {
|
|
66
|
+
return {
|
|
67
|
+
content: [{
|
|
68
|
+
type: "text",
|
|
69
|
+
text: `No fuzzy search logs found. Log file location: ${logPath}`
|
|
70
|
+
}],
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
// Parse logs and gather statistics
|
|
74
|
+
let totalEntries = 0;
|
|
75
|
+
let exactMatches = 0;
|
|
76
|
+
let fuzzyMatches = 0;
|
|
77
|
+
let failures = 0;
|
|
78
|
+
let belowThresholdCount = 0;
|
|
79
|
+
const executionTimes = [];
|
|
80
|
+
const similarities = [];
|
|
81
|
+
const fileExtensions = new Map();
|
|
82
|
+
const commonCharacterCodes = new Map();
|
|
83
|
+
for (const log of logs) {
|
|
84
|
+
const parts = log.split('\t');
|
|
85
|
+
if (parts.length >= 16) {
|
|
86
|
+
totalEntries++;
|
|
87
|
+
const [timestamp, searchText, foundText, similarity, executionTime, exactMatchCount, expectedReplacements, fuzzyThreshold, belowThreshold, diff, searchLength, foundLength, fileExtension, characterCodes, uniqueCharacterCount, diffLength] = parts;
|
|
88
|
+
const simValue = parseFloat(similarity);
|
|
89
|
+
const execTime = parseFloat(executionTime);
|
|
90
|
+
const exactCount = parseInt(exactMatchCount);
|
|
91
|
+
const belowThresh = belowThreshold === 'true';
|
|
92
|
+
if (exactCount > 0) {
|
|
93
|
+
exactMatches++;
|
|
94
|
+
}
|
|
95
|
+
else if (simValue >= parsed.failureThreshold) {
|
|
96
|
+
fuzzyMatches++;
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
failures++;
|
|
100
|
+
}
|
|
101
|
+
if (belowThresh) {
|
|
102
|
+
belowThresholdCount++;
|
|
103
|
+
}
|
|
104
|
+
executionTimes.push(execTime);
|
|
105
|
+
similarities.push(simValue);
|
|
106
|
+
// Track file extensions
|
|
107
|
+
fileExtensions.set(fileExtension, (fileExtensions.get(fileExtension) || 0) + 1);
|
|
108
|
+
// Track character codes that appear in diffs
|
|
109
|
+
if (characterCodes && characterCodes !== '') {
|
|
110
|
+
const codes = characterCodes.split(',');
|
|
111
|
+
for (const code of codes) {
|
|
112
|
+
const key = code.split(':')[0];
|
|
113
|
+
commonCharacterCodes.set(key, (commonCharacterCodes.get(key) || 0) + 1);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// Calculate statistics
|
|
119
|
+
const avgExecutionTime = executionTimes.reduce((a, b) => a + b, 0) / executionTimes.length;
|
|
120
|
+
const avgSimilarity = similarities.reduce((a, b) => a + b, 0) / similarities.length;
|
|
121
|
+
// Sort by frequency
|
|
122
|
+
const sortedExtensions = Array.from(fileExtensions.entries()).sort((a, b) => b[1] - a[1]);
|
|
123
|
+
const sortedCharCodes = Array.from(commonCharacterCodes.entries()).sort((a, b) => b[1] - a[1]);
|
|
124
|
+
const analysis = `
|
|
125
|
+
=== Fuzzy Search Analysis ===
|
|
126
|
+
|
|
127
|
+
Total Entries: ${totalEntries}
|
|
128
|
+
Exact Matches: ${exactMatches} (${((exactMatches / totalEntries) * 100).toFixed(2)}%)
|
|
129
|
+
Fuzzy Matches: ${fuzzyMatches} (${((fuzzyMatches / totalEntries) * 100).toFixed(2)}%)
|
|
130
|
+
Failures: ${failures} (${((failures / totalEntries) * 100).toFixed(2)}%)
|
|
131
|
+
Below Threshold: ${belowThresholdCount} (${((belowThresholdCount / totalEntries) * 100).toFixed(2)}%)
|
|
132
|
+
|
|
133
|
+
Performance:
|
|
134
|
+
Average Execution Time: ${avgExecutionTime.toFixed(2)}ms
|
|
135
|
+
Average Similarity: ${(avgSimilarity * 100).toFixed(2)}%
|
|
136
|
+
|
|
137
|
+
File Extensions (Top 5):
|
|
138
|
+
${sortedExtensions.slice(0, 5).map(([ext, count]) => `${ext || 'none'}: ${count} times`).join('\n')}
|
|
139
|
+
|
|
140
|
+
Common Character Codes in Diffs (Top 5):
|
|
141
|
+
${sortedCharCodes.slice(0, 5).map(([code, count]) => {
|
|
142
|
+
const charCode = parseInt(code);
|
|
143
|
+
const char = String.fromCharCode(charCode);
|
|
144
|
+
const display = charCode < 32 || charCode > 126 ? `\\x${charCode.toString(16).padStart(2, '0')}` : char;
|
|
145
|
+
return `${code} [${display}]: ${count} times`;
|
|
146
|
+
}).join('\n')}
|
|
147
|
+
|
|
148
|
+
Log file location: ${logPath}
|
|
149
|
+
`;
|
|
150
|
+
return {
|
|
151
|
+
content: [{
|
|
152
|
+
type: "text",
|
|
153
|
+
text: analysis
|
|
154
|
+
}],
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
return createErrorResponse(`Failed to analyze fuzzy search logs: ${error instanceof Error ? error.message : String(error)}`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Clear fuzzy search logs
|
|
163
|
+
*/
|
|
164
|
+
export async function handleClearFuzzySearchLogs(args) {
|
|
165
|
+
try {
|
|
166
|
+
ClearFuzzySearchLogsArgsSchema.parse(args);
|
|
167
|
+
await fuzzySearchLogger.clearLog();
|
|
168
|
+
const logPath = await fuzzySearchLogger.getLogPath();
|
|
169
|
+
return {
|
|
170
|
+
content: [{
|
|
171
|
+
type: "text",
|
|
172
|
+
text: `Fuzzy search logs cleared. Log file location: ${logPath}`
|
|
173
|
+
}],
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
return createErrorResponse(`Failed to clear fuzzy search logs: ${error instanceof Error ? error.message : String(error)}`);
|
|
178
|
+
}
|
|
179
|
+
}
|