file-organizer-mcp 3.1.3 → 3.1.5

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 (181) hide show
  1. package/ARCHITECTURE.md +607 -582
  2. package/CHANGELOG.md +46 -0
  3. package/CONTRIBUTING.md +314 -312
  4. package/MIGRATION.md +365 -358
  5. package/README.md +76 -49
  6. package/bin/file-organizer-mcp.mjs +141 -0
  7. package/bin/file-organizer-setup.mjs +76 -0
  8. package/dist/config.d.ts +2 -0
  9. package/dist/config.d.ts.map +1 -1
  10. package/dist/config.js +69 -11
  11. package/dist/config.js.map +1 -1
  12. package/dist/constants.d.ts.map +1 -1
  13. package/dist/constants.js +14 -1
  14. package/dist/constants.js.map +1 -1
  15. package/dist/errors.d.ts.map +1 -1
  16. package/dist/errors.js +1 -1
  17. package/dist/errors.js.map +1 -1
  18. package/dist/index.d.ts +2 -2
  19. package/dist/index.js +183 -6
  20. package/dist/index.js.map +1 -1
  21. package/dist/schemas/common.schemas.js.map +1 -1
  22. package/dist/schemas/organize.schemas.js.map +1 -1
  23. package/dist/schemas/rename.schemas.d.ts.map +1 -1
  24. package/dist/schemas/rename.schemas.js +9 -1
  25. package/dist/schemas/rename.schemas.js.map +1 -1
  26. package/dist/schemas/scan.schemas.js.map +1 -1
  27. package/dist/schemas/security.schemas.d.ts.map +1 -1
  28. package/dist/schemas/security.schemas.js.map +1 -1
  29. package/dist/server.js +16 -5
  30. package/dist/server.js.map +1 -1
  31. package/dist/services/auto-organize.service.d.ts +56 -5
  32. package/dist/services/auto-organize.service.d.ts.map +1 -1
  33. package/dist/services/auto-organize.service.js +231 -23
  34. package/dist/services/auto-organize.service.js.map +1 -1
  35. package/dist/services/categorizer.service.d.ts.map +1 -1
  36. package/dist/services/categorizer.service.js +11 -6
  37. package/dist/services/categorizer.service.js.map +1 -1
  38. package/dist/services/duplicate-finder.service.d.ts.map +1 -1
  39. package/dist/services/duplicate-finder.service.js +48 -48
  40. package/dist/services/duplicate-finder.service.js.map +1 -1
  41. package/dist/services/file-scanner.service.d.ts +23 -0
  42. package/dist/services/file-scanner.service.d.ts.map +1 -1
  43. package/dist/services/file-scanner.service.js +56 -14
  44. package/dist/services/file-scanner.service.js.map +1 -1
  45. package/dist/services/hash-calculator.service.d.ts.map +1 -1
  46. package/dist/services/hash-calculator.service.js +8 -3
  47. package/dist/services/hash-calculator.service.js.map +1 -1
  48. package/dist/services/index.d.ts +2 -1
  49. package/dist/services/index.d.ts.map +1 -1
  50. package/dist/services/index.js +2 -1
  51. package/dist/services/index.js.map +1 -1
  52. package/dist/services/metadata.service.d.ts.map +1 -1
  53. package/dist/services/metadata.service.js +3 -5
  54. package/dist/services/metadata.service.js.map +1 -1
  55. package/dist/services/organizer.service.d.ts +16 -0
  56. package/dist/services/organizer.service.d.ts.map +1 -1
  57. package/dist/services/organizer.service.js +70 -39
  58. package/dist/services/organizer.service.js.map +1 -1
  59. package/dist/services/path-validator.service.d.ts +14 -0
  60. package/dist/services/path-validator.service.d.ts.map +1 -1
  61. package/dist/services/path-validator.service.js +25 -27
  62. package/dist/services/path-validator.service.js.map +1 -1
  63. package/dist/services/renaming.service.d.ts.map +1 -1
  64. package/dist/services/renaming.service.js +24 -18
  65. package/dist/services/renaming.service.js.map +1 -1
  66. package/dist/services/rollback.service.d.ts +6 -0
  67. package/dist/services/rollback.service.d.ts.map +1 -1
  68. package/dist/services/rollback.service.js +98 -31
  69. package/dist/services/rollback.service.js.map +1 -1
  70. package/dist/services/scheduler-state.service.d.ts +130 -0
  71. package/dist/services/scheduler-state.service.d.ts.map +1 -0
  72. package/dist/services/scheduler-state.service.js +315 -0
  73. package/dist/services/scheduler-state.service.js.map +1 -0
  74. package/dist/services/security/rate-limiter.service.d.ts.map +1 -1
  75. package/dist/services/security/rate-limiter.service.js +2 -2
  76. package/dist/services/security/rate-limiter.service.js.map +1 -1
  77. package/dist/services/streaming-scanner.service.d.ts.map +1 -1
  78. package/dist/services/streaming-scanner.service.js +4 -4
  79. package/dist/services/streaming-scanner.service.js.map +1 -1
  80. package/dist/tests/test-dryrun.js +3 -3
  81. package/dist/tests/test-dryrun.js.map +1 -1
  82. package/dist/tests/test-duplicate-scoring.js +6 -6
  83. package/dist/tests/test-duplicate-scoring.js.map +1 -1
  84. package/dist/tests/test-edge-cases.js +2 -2
  85. package/dist/tests/test-edge-cases.js.map +1 -1
  86. package/dist/tests/test-filename-conflict.js +8 -6
  87. package/dist/tests/test-filename-conflict.js.map +1 -1
  88. package/dist/tests/test-overwrite-bug.js +6 -4
  89. package/dist/tests/test-overwrite-bug.js.map +1 -1
  90. package/dist/tests/test-pagination.js.map +1 -1
  91. package/dist/tests/test-phase1.js.map +1 -1
  92. package/dist/tests/test-phase3-advanced.js +3 -3
  93. package/dist/tests/test-phase3-advanced.js.map +1 -1
  94. package/dist/tests/test-phase3.js +11 -8
  95. package/dist/tests/test-phase3.js.map +1 -1
  96. package/dist/tests/test-rollback-fix.js +11 -7
  97. package/dist/tests/test-rollback-fix.js.map +1 -1
  98. package/dist/tests/test-security-enhanced.js.map +1 -1
  99. package/dist/tests/test-security.js +2 -1
  100. package/dist/tests/test-security.js.map +1 -1
  101. package/dist/tools/duplicate-management.d.ts.map +1 -1
  102. package/dist/tools/duplicate-management.js +42 -23
  103. package/dist/tools/duplicate-management.js.map +1 -1
  104. package/dist/tools/file-analysis.d.ts.map +1 -1
  105. package/dist/tools/file-analysis.js +8 -2
  106. package/dist/tools/file-analysis.js.map +1 -1
  107. package/dist/tools/file-categorization.d.ts.map +1 -1
  108. package/dist/tools/file-categorization.js +12 -3
  109. package/dist/tools/file-categorization.js.map +1 -1
  110. package/dist/tools/file-duplicates.d.ts.map +1 -1
  111. package/dist/tools/file-duplicates.js +4 -2
  112. package/dist/tools/file-duplicates.js.map +1 -1
  113. package/dist/tools/file-listing.d.ts.map +1 -1
  114. package/dist/tools/file-listing.js +3 -1
  115. package/dist/tools/file-listing.js.map +1 -1
  116. package/dist/tools/file-management.d.ts.map +1 -1
  117. package/dist/tools/file-management.js +21 -15
  118. package/dist/tools/file-management.js.map +1 -1
  119. package/dist/tools/file-organization.d.ts.map +1 -1
  120. package/dist/tools/file-organization.js +11 -4
  121. package/dist/tools/file-organization.js.map +1 -1
  122. package/dist/tools/file-renaming.d.ts.map +1 -1
  123. package/dist/tools/file-renaming.js +21 -12
  124. package/dist/tools/file-renaming.js.map +1 -1
  125. package/dist/tools/file-scanning.d.ts.map +1 -1
  126. package/dist/tools/file-scanning.js +14 -4
  127. package/dist/tools/file-scanning.js.map +1 -1
  128. package/dist/tools/index.d.ts +6 -6
  129. package/dist/tools/index.d.ts.map +1 -1
  130. package/dist/tools/index.js +8 -8
  131. package/dist/tools/index.js.map +1 -1
  132. package/dist/tools/metadata-inspection.d.ts.map +1 -1
  133. package/dist/tools/metadata-inspection.js +4 -2
  134. package/dist/tools/metadata-inspection.js.map +1 -1
  135. package/dist/tools/organization-preview.d.ts.map +1 -1
  136. package/dist/tools/organization-preview.js +11 -4
  137. package/dist/tools/organization-preview.js.map +1 -1
  138. package/dist/tools/rollback.d.ts.map +1 -1
  139. package/dist/tools/rollback.js +12 -7
  140. package/dist/tools/rollback.js.map +1 -1
  141. package/dist/tools/watch.tool.d.ts.map +1 -1
  142. package/dist/tools/watch.tool.js +50 -37
  143. package/dist/tools/watch.tool.js.map +1 -1
  144. package/dist/tui/client-detector.d.ts +49 -0
  145. package/dist/tui/client-detector.d.ts.map +1 -0
  146. package/dist/tui/client-detector.js +486 -0
  147. package/dist/tui/client-detector.js.map +1 -0
  148. package/dist/tui/index.d.ts +2 -2
  149. package/dist/tui/index.js +14 -3
  150. package/dist/tui/index.js.map +1 -1
  151. package/dist/tui/setup-wizard.d.ts +14 -0
  152. package/dist/tui/setup-wizard.d.ts.map +1 -1
  153. package/dist/tui/setup-wizard.js +255 -131
  154. package/dist/tui/setup-wizard.js.map +1 -1
  155. package/dist/types.d.ts.map +1 -1
  156. package/dist/types.js.map +1 -1
  157. package/dist/utils/cron-utils.d.ts +44 -0
  158. package/dist/utils/cron-utils.d.ts.map +1 -0
  159. package/dist/utils/cron-utils.js +301 -0
  160. package/dist/utils/cron-utils.js.map +1 -0
  161. package/dist/utils/diagnostics.d.ts +22 -0
  162. package/dist/utils/diagnostics.d.ts.map +1 -0
  163. package/dist/utils/diagnostics.js +551 -0
  164. package/dist/utils/diagnostics.js.map +1 -0
  165. package/dist/utils/error-handler.js.map +1 -1
  166. package/dist/utils/file-utils.d.ts.map +1 -1
  167. package/dist/utils/file-utils.js.map +1 -1
  168. package/dist/utils/formatters.js.map +1 -1
  169. package/dist/utils/index.d.ts +2 -1
  170. package/dist/utils/index.d.ts.map +1 -1
  171. package/dist/utils/index.js +2 -1
  172. package/dist/utils/index.js.map +1 -1
  173. package/dist/utils/logger.d.ts.map +1 -1
  174. package/dist/utils/logger.js +7 -5
  175. package/dist/utils/logger.js.map +1 -1
  176. package/dist/utils/path-security.d.ts.map +1 -1
  177. package/dist/utils/path-security.js.map +1 -1
  178. package/package.json +25 -9
  179. package/scripts/postinstall.cjs +55 -0
  180. package/scripts/prepare.cjs +65 -0
  181. package/scripts/postinstall.js +0 -38
package/ARCHITECTURE.md CHANGED
@@ -1,582 +1,607 @@
1
- # Architecture Documentation
2
-
3
- ## 🏗️ System Overview
4
-
5
- File Organizer MCP is a security-hardened Model Context Protocol (MCP) server that provides intelligent file organization capabilities to Large Language Models (LLMs). The architecture follows a layered service pattern with comprehensive security validation at every level.
6
-
7
- ### Core Principles
8
-
9
- 1. **Security First** - Multi-layer validation and sanitization
10
- 2. **Service Isolation** - Clear separation of concerns
11
- 3. **Type Safety** - Strict TypeScript with Zod validation
12
- 4. **Testability** - Dependency injection and modular design
13
- 5. **Performance** - Streaming operations and resource limits
14
-
15
- ## 📐 Architecture Layers
16
-
17
- ```
18
- ┌─────────────────────────────────────────────────────────────┐
19
- │ MCP Client (LLM) │
20
- └─────────────────────────┬───────────────────────────────────┘
21
- │ JSON-RPC 2.0
22
- ┌─────────────────────────▼───────────────────────────────────┐
23
- │ MCP Server Layer │
24
- │ (server.ts - Protocol Handler) │
25
- └─────────────────────────┬───────────────────────────────────┘
26
-
27
- ┌─────────────────────────▼───────────────────────────────────┐
28
- │ Tools Layer │
29
- │ ┌──────────┬──────────┬───────────┬─────────────┐ │
30
- │ │ Scan │ Organize │ Duplicate │ Categorize │ │
31
- │ │ Files │ Files │ Find │ Files │ │
32
- │ └──────────┴──────────┴───────────┴─────────────┘ │
33
- └─────────────────────────┬───────────────────────────────────┘
34
-
35
- ┌─────────────────────────▼───────────────────────────────────┐
36
- │ Services Layer │
37
- │ ┌────────────┬──────────────┬─────────────┬──────────┐ │
38
- │ │ Path │ Organizer │ Hash │ Scanner │ │
39
- │ │ Validator │ Service │ Calculator │ Service │ │
40
- │ └────────────┴──────────────┴─────────────┴──────────┘ │
41
- └─────────────────────────┬───────────────────────────────────┘
42
-
43
- ┌─────────────────────────▼───────────────────────────────────┐
44
- │ Utils Layer │
45
- │ ┌──────────┬──────────┬───────────┬──────────┐ │
46
- │ │ Logger │ Error │ File │ Format- │ │
47
- │ │ │ Handler │ Utils │ ters │ │
48
- │ └──────────┴──────────┴───────────┴──────────┘ │
49
- └─────────────────────────┬───────────────────────────────────┘
50
-
51
- ┌─────────────────────────▼───────────────────────────────────┐
52
- │ File System │
53
- └─────────────────────────────────────────────────────────────┘
54
- ```
55
-
56
- ## 🔐 Security Architecture
57
-
58
- ### 8-Layer Path Validation Pipeline
59
-
60
- Every file path goes through these validation layers:
61
-
62
- ```typescript
63
- Input Path
64
-
65
- 1. Type Validation (Zod Schema)
66
-
67
- 2. Null Byte & Basic Sanitization
68
-
69
- 3. Path Normalization & Windows Case Adjustment
70
-
71
- 4. Traversal Sequence Prevention (../)
72
-
73
- 5. Absolute Path Resolution
74
-
75
- 6. Security Check (Whitelist & Blacklist)
76
-
77
- 7. Symlink Resolution & Target Validation
78
-
79
- 8. Existence & Access Check
80
-
81
- Validated Path ✅
82
- ```
83
-
84
- **Implementation:** [`src/services/path-validator.service.ts`](file:///c:/Users/NewAdmin/Desktop/File-Organizer-MCP/src/services/path-validator.service.ts)
85
-
86
- ### Race Condition Mitigation (TOCTOU Protection)
87
-
88
- **Problem:** Time-of-Check-Time-of-Use vulnerabilities can occur when a file is checked, then used later, allowing an attacker to swap the file between operations.
89
-
90
- **Solution:** Multi-layered approach:
91
-
92
- ```typescript
93
- // Layer 1: File Descriptor Validation
94
- // Open file with O_NOFOLLOW to prevent symlink following
95
- const handle = await fs.open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
96
-
97
- // Layer 2: Atomic Copy Operations
98
- // Use COPYFILE_EXCL to ensure destination doesn't exist
99
- await fs.copyFile(source, dest, constants.COPYFILE_EXCL);
100
-
101
- // Layer 3: Safe Overwrites
102
- // Move existing file to backup before replacing
103
- const backupPath = path.join('.file-organizer-backups', `${Date.now()}_overwrite_${basename}`);
104
- await fs.rename(existingFile, backupPath);
105
- ```
106
-
107
- **Limitations:**
108
- - File deletion on Windows uses path-based locking (not file descriptor)
109
- - Symlinks are blocked for security but may limit legitimate use cases
110
-
111
- ### Resource Protection
112
-
113
- ```typescript
114
- // Security Constants
115
- const SECURITY_LIMITS = {
116
- MAX_FILE_SIZE: 100 * 1024 * 1024, // 100 MB
117
- MAX_FILES: 10000, // Per operation
118
- MAX_DEPTH: 10, // Directory recursion
119
- MAX_PATH_LENGTH: 4096 // Characters
120
- };
121
- ```
122
-
123
- ## 📦 Core Components
124
-
125
- ### 1. Server Layer (`server.ts`)
126
-
127
- **Responsibility:** MCP protocol handling and tool registration
128
-
129
- ```typescript
130
- // Key responsibilities:
131
- - Initialize MCP server
132
- - Register tools with schemas
133
- - Handle tool invocations
134
- - Manage error responses
135
- - Coordinate with services
136
- ```
137
-
138
- **Key Features:**
139
- - Automatic tool discovery from `tools/` directory
140
- - Structured response formatting (JSON/Markdown)
141
- - Centralized error handling
142
-
143
- ### 2. Tools Layer (`tools/`)
144
-
145
- **Responsibility:** MCP tool implementations (user-facing API)
146
-
147
- Each tool follows this pattern:
148
-
149
- ```typescript
150
- export const toolDefinition: ToolDefinition = {
151
- name: 'tool_name',
152
- description: 'What it does',
153
- inputSchema: ZodSchema // Validation
154
- };
155
-
156
- export async function handleTool(args: ToolArgs): Promise<ToolResponse> {
157
- // 1. Validate inputs (Zod)
158
- // 2. Validate security (PathValidator)
159
- // 3. Call service layer
160
- // 4. Format response
161
- // 5. Handle errors
162
- }
163
- ```
164
-
165
- **Available Tools:**
166
- 1. **List Files in Directory** (`file_organizer_list_files`)
167
- 2. **Scan Directory for Detailed Info** (`file_organizer_scan_directory`)
168
- 3. **Categorize Files by Type** (`file_organizer_categorize_files`)
169
- 4. **Find Largest Files** (`file_organizer_find_largest_files`)
170
- 5. **Find Duplicate Files** (`file_organizer_find_duplicate_files`)
171
- 6. **Preview File Organization Plan** (`file_organizer_preview_organization`)
172
- 7. **Get Available File Categories** (`file_organizer_get_categories`)
173
- 8. **Analyze Duplicate Files with Smart Recommendations** (`file_organizer_analyze_duplicates`)
174
- 9. **Organize Files** (`file_organizer_organize_files`)
175
- 10. **Set Custom Organization Rules** (`file_organizer_set_custom_rules`)
176
- 11. **Delete Duplicate Files** (`file_organizer_delete_duplicates`)
177
- 12. **Undo Last Organization Operation** (`file_organizer_undo_last_operation`)
178
-
179
- ### 3. Services Layer (`services/`)
180
-
181
- **Responsibility:** Core business logic
182
-
183
- #### PathValidatorService
184
- ```typescript
185
- class PathValidatorService {
186
- // Multi-layer path validation
187
- async validateStrictPath(inputPath: unknown, options?: ValidatePathOptions): Promise<string>
188
-
189
- // Symlink resolution
190
- async resolvePath(path: string): Promise<string>
191
-
192
- // Containment checking
193
- isPathWithinRoots(path: string, roots: string[]): boolean
194
- }
195
- ```
196
-
197
- #### OrganizerService
198
- ```typescript
199
- class OrganizerService {
200
- // Generate organization plan
201
- async generateOrganizationPlan(
202
- directory: string,
203
- files: FileWithSize[],
204
- strategy?: ConflictStrategy // 'rename' | 'skip' | 'overwrite' | 'overwrite_if_newer'
205
- ): Promise<OrganizationPlan>
206
-
207
- // Execute organization with safety guarantees
208
- async organize(
209
- directory: string,
210
- files: FileWithSize[],
211
- options?: OrganizeOptions
212
- ): Promise<OrganizeResult>
213
-
214
- // Safety mechanisms:
215
- // 1. File descriptor validation before move
216
- // 2. Atomic copy with COPYFILE_EXCL (race-safe)
217
- // 3. Automatic backup to .file-organizer-backups/ on overwrite
218
- // 4. Retry loop for race condition recovery
219
- }
220
- ```
221
-
222
- #### HashCalculatorService
223
- ```typescript
224
- class HashCalculatorService {
225
- // Streaming hash calculation
226
- async calculateHash(filePath: string): Promise<string>
227
-
228
- // Find duplicates (memory-safe)
229
- async findDuplicates(files: FileWithSize[]): Promise<DuplicateGroup[]>
230
- }
231
- ```
232
-
233
- #### FileScannerService
234
- ```typescript
235
- class FileScannerService {
236
- // Recursive directory scanning
237
- async getAllFiles(
238
- directory: string,
239
- options?: ScanOptions
240
- ): Promise<FileWithSize[]>
241
-
242
- // Size calculation
243
- async calculateDirectorySize(directory: string): Promise<number>
244
- }
245
- ```
246
-
247
- #### CategorizerService
248
- ```typescript
249
- class CategorizerService {
250
- // File categorization
251
- getCategory(fileName: string): CategoryName
252
-
253
- // Custom rules support
254
- setCustomRules(rules: CategoryRule[]): void
255
-
256
- // Category statistics
257
- categorizeFiles(files: FileWithSize[]): CategoryBreakdown
258
- }
259
- ```
260
-
261
- #### RollbackService
262
- ```typescript
263
- class RollbackService {
264
- // Create rollback manifest
265
- async createManifest(actions: OrganizeAction[]): Promise<string>
266
-
267
- // Execute rollback
268
- async rollback(manifestId: string): Promise<RollbackResult>
269
-
270
- // List available rollbacks
271
- async listRollbacks(): Promise<RollbackManifest[]>
272
- }
273
- ```
274
-
275
- ### 4. Utils Layer (`utils/`)
276
-
277
- **Responsibility:** Shared utility functions
278
-
279
- #### Logger
280
- ```typescript
281
- class Logger {
282
- // Structured JSON logging to stderr (MCP stdio protocol)
283
- debug(message: string, context?: Record<string, any>): void
284
- info(message: string, context?: Record<string, any>): void
285
- warn(message: string, context?: Record<string, any>): void
286
- error(message: string, error?: Error, context?: Record<string, any>): void
287
-
288
- // Features:
289
- // - ISO 8601 timestamps
290
- // - Configurable log levels (debug/info/warn/error)
291
- // - Error stack traces for error logs
292
- // - JSON format for machine parsing
293
- }
294
- ```
295
-
296
- - **error-handler.ts** - Centralized error handling
297
- - **file-utils.ts** - File system helpers
298
- - **formatters.ts** - Data formatting (bytes, dates, etc.)
299
-
300
- ### 5. Schemas Layer (`schemas/`)
301
-
302
- **Responsibility:** Input validation using Zod
303
-
304
- ```typescript
305
- // Example: Path validation
306
- export const PathSchema = z.string()
307
- .min(1, 'Path cannot be empty')
308
- .max(4096, 'Path exceeds maximum length')
309
- .refine(
310
- (path) => !path.includes('\0'),
311
- 'Path contains null bytes'
312
- );
313
- ```
314
-
315
- ## 🔄 Data Flow
316
-
317
- ### Example: Organize Files Operation
318
-
319
- ```
320
- 1. LLM Request
321
-
322
- 2. MCP Server (server.ts)
323
- - Parse JSON-RPC request
324
- - Route to organize tool
325
-
326
- 3. Tool Handler (tools/file-organization.ts)
327
- - Validate args with Zod
328
- - Call PathValidatorService
329
-
330
- 4. PathValidatorService
331
- - 7-layer validation
332
- - Return validated path
333
-
334
- 5. FileScannerService
335
- - Scan directory
336
- - Apply resource limits
337
-
338
- 6. CategorizerService
339
- - Categorize each file
340
-
341
- 7. OrganizerService
342
- - Generate organization plan
343
- - Check conflicts
344
- - Execute moves (if not dry run)
345
-
346
- 8. RollbackService
347
- - Create rollback manifest
348
-
349
- 9. Tool Handler
350
- - Format response (JSON/Markdown)
351
-
352
- 10. MCP Server
353
- - Send JSON-RPC response
354
-
355
- 11. LLM receives result
356
- ```
357
-
358
- ## 💾 File Organization
359
-
360
- ### Source Structure
361
-
362
- ```
363
- src/
364
- ├── server.ts # MCP server entry point
365
- ├── index.ts # Main entry point
366
- ├── types.ts # TypeScript type definitions
367
- ├── constants.ts # Application constants
368
- ├── config.ts # Configuration management
369
-
370
- ├── services/ # Core business logic
371
- ├── path-validator.service.ts
372
- ├── organizer.service.ts
373
- │ ├── hash-calculator.service.ts
374
- ├── file-scanner.service.ts
375
- ├── categorizer.service.ts
376
- │ └── rollback.service.ts
377
-
378
- ├── tools/ # MCP tool implementations
379
- │ ├── file-scanning.ts
380
- │ ├── file-organization.ts
381
- │ ├── file-duplicates.ts
382
- │ ├── file-categorization.ts
383
- │ └── ...
384
-
385
- ├── schemas/ # Zod validation schemas
386
- │ ├── security.schemas.ts
387
- │ ├── common.schemas.ts
388
- ├── scan.schemas.ts
389
- │ └── organize.schemas.ts
390
-
391
- └── utils/ # Shared utilities
392
- ├── logger.ts
393
- ├── error-handler.ts
394
- ├── file-utils.ts
395
- └── formatters.ts
396
- ```
397
-
398
- ## 🧪 Testing Architecture
399
-
400
- ### Test Structure
401
-
402
- ```
403
- tests/
404
- ├── unit/ # Unit tests for services
405
- │ ├── services/
406
- ├── path-validator.test.ts
407
- │ ├── organizer.test.ts
408
- │ └── ...
409
- │ └── utils/
410
-
411
- ├── integration/ # Integration tests for tools
412
- │ ├── tools/
413
- └── organize.test.ts
414
- └── edge-cases.test.ts
415
-
416
- └── performance/ # Performance benchmarks
417
- └── performance.test.ts
418
- ```
419
-
420
- ### Test Philosophy
421
-
422
- 1. **Unit Tests** - Test services in isolation
423
- 2. **Integration Tests** - Test complete workflows
424
- 3. **Security Tests** - Validate all security controls
425
- 4. **Performance Tests** - Ensure scalability
426
-
427
- ## 🚀 Performance Considerations
428
-
429
- ### Streaming Operations
430
-
431
- Large files are processed using streams to avoid memory exhaustion:
432
-
433
- ```typescript
434
- // Hash calculation uses streams
435
- const hash = crypto.createHash('sha256');
436
- const stream = createReadStream(filePath, { highWaterMark: 64 * 1024 });
437
- stream.on('data', (chunk) => hash.update(chunk));
438
- ```
439
-
440
- ### Resource Limits
441
-
442
- ```typescript
443
- // Enforced at multiple levels:
444
- - File size: Skip files > 100MB for hashing
445
- - File count: Max 10,000 files per operation
446
- - Recursion depth: Max 10 levels
447
- - Path length: Max 4,096 characters
448
- ```
449
-
450
- ### Caching Strategy
451
-
452
- - Category mappings cached in-memory
453
- - File stats cached during single operation
454
- - No persistent caching (stateless design)
455
-
456
- ## 🔧 Configuration
457
-
458
- ### Configuration System (`config.ts`)
459
-
460
- The server uses a platform-aware configuration system that combines hardcoded defaults with user customization.
461
-
462
- **Structure:**
463
- ```typescript
464
- export const CONFIG = {
465
- VERSION: '3.0.0',
466
-
467
- security: {
468
- enablePathValidation: true,
469
- allowCustomDirectories: true,
470
- logAccess: true,
471
- maxScanDepth: 10,
472
- maxFilesPerOperation: 10000
473
- },
474
-
475
- paths: {
476
- defaultAllowed: getDefaultAllowedDirs(), // Platform-aware safe directories
477
- customAllowed: loadCustomAllowedDirs(), // User-defined from config.json
478
- alwaysBlocked: getAlwaysBlockedPatterns() // System protection patterns
479
- }
480
- };
481
- ```
482
-
483
- **Default Allowed Directories:**
484
- - **Windows:** Desktop, Documents, Downloads, Pictures, Videos, Music, OneDrive, Projects
485
- - **macOS:** Desktop, Documents, Downloads, Movies, Music, Pictures, iCloud Drive, Projects
486
- - **Linux:** Desktop, Documents, Downloads, Music, Pictures, Videos, ~/dev, ~/workspace
487
-
488
- **User Configuration:**
489
- - **Windows:** `%APPDATA%\file-organizer-mcp\config.json`
490
- - **macOS:** `~/Library/Application Support/file-organizer-mcp/config.json`
491
- - **Linux:** `~/.config/file-organizer-mcp/config.json`
492
-
493
- **Config File Format:**
494
- ```json
495
- {
496
- "customAllowedDirectories": [
497
- "C:\\Users\\Name\\CustomFolder",
498
- "D:\\Projects"
499
- ],
500
- "settings": {
501
- "maxScanDepth": 10,
502
- "logAccess": true
503
- }
504
- }
505
- ```
506
-
507
- ## 🎯 Design Patterns
508
-
509
- ### Dependency Injection
510
-
511
- ```typescript
512
- // Services receive dependencies via constructor
513
- class OrganizerService {
514
- constructor(
515
- private categorizer: CategorizerService,
516
- private rollback?: RollbackService
517
- ) {}
518
- }
519
- ```
520
-
521
- ### Error Handling
522
-
523
- ```typescript
524
- // Centralized error handling
525
- try {
526
- const result = await operation();
527
- } catch (error) {
528
- return createErrorResponse(error);
529
- }
530
- ```
531
-
532
- ### Type Safety
533
-
534
- ```typescript
535
- // Strict types with Zod runtime validation
536
- const ArgsSchema = z.object({
537
- directory: PathSchema,
538
- dry_run: z.boolean().optional()
539
- });
540
-
541
- type Args = z.infer<typeof ArgsSchema>;
542
- ```
543
-
544
- ## 📊 Monitoring & Logging
545
-
546
- ### Structured Logging
547
-
548
- ```json
549
- {
550
- "timestamp": "2026-02-02T14:09:04.413Z",
551
- "level": "info",
552
- "message": "Created rollback manifest: uuid (6 actions)"
553
- }
554
- ```
555
-
556
- ### Log Levels
557
-
558
- - `error` - Critical failures
559
- - `warn` - Recoverable issues (e.g., skipped files)
560
- - `info` - Operation milestones
561
- - `debug` - Detailed diagnostics
562
-
563
- ## 🔮 Future Architecture Changes
564
-
565
- ### Planned Improvements
566
-
567
- 1. **Plugin System** - Allow custom categorization rules
568
- 2. **Database Layer** - Persistent state for large operations
569
- 3. **Queue System** - Background processing for large directories
570
- 4. **Metrics Collection** - Performance monitoring
571
- 5. **Multi-language Support** - i18n infrastructure
572
-
573
- ## 📚 References
574
-
575
- - [Model Context Protocol Spec](https://modelcontextprotocol.io)
576
- - [Zod Documentation](https://zod.dev)
577
- - [TypeScript Handbook](https://www.typescriptlang.org/docs)
578
-
579
- ---
580
-
581
- **Last Updated:** February 3, 2026
582
- **Version:** 3.0.0
1
+ # Architecture Documentation
2
+
3
+ ## 🏗️ System Overview
4
+
5
+ File Organizer MCP is a security-hardened Model Context Protocol (MCP) server that provides intelligent file organization capabilities to Large Language Models (LLMs). The architecture follows a layered service pattern with comprehensive security validation at every level.
6
+
7
+ ### Core Principles
8
+
9
+ 1. **Security First** - Multi-layer validation and sanitization
10
+ 2. **Service Isolation** - Clear separation of concerns
11
+ 3. **Type Safety** - Strict TypeScript with Zod validation
12
+ 4. **Testability** - Dependency injection and modular design
13
+ 5. **Performance** - Streaming operations and resource limits
14
+
15
+ ## 📐 Architecture Layers
16
+
17
+ ```
18
+ ┌─────────────────────────────────────────────────────────────┐
19
+ │ MCP Client (LLM) │
20
+ └─────────────────────────┬───────────────────────────────────┘
21
+ │ JSON-RPC 2.0
22
+ ┌─────────────────────────▼───────────────────────────────────┐
23
+ │ MCP Server Layer │
24
+ │ (server.ts - Protocol Handler) │
25
+ └─────────────────────────┬───────────────────────────────────┘
26
+
27
+ ┌─────────────────────────▼───────────────────────────────────┐
28
+ │ Tools Layer │
29
+ │ ┌──────────┬──────────┬───────────┬─────────────┐ │
30
+ │ │ Scan │ Organize │ Duplicate │ Categorize │ │
31
+ │ │ Files │ Files │ Find │ Files │ │
32
+ │ └──────────┴──────────┴───────────┴─────────────┘ │
33
+ └─────────────────────────┬───────────────────────────────────┘
34
+
35
+ ┌─────────────────────────▼───────────────────────────────────┐
36
+ │ Services Layer │
37
+ │ ┌────────────┬──────────────┬─────────────┬──────────┐ │
38
+ │ │ Path │ Organizer │ Hash │ Scanner │ │
39
+ │ │ Validator │ Service │ Calculator │ Service │ │
40
+ │ └────────────┴──────────────┴─────────────┴──────────┘ │
41
+ └─────────────────────────┬───────────────────────────────────┘
42
+
43
+ ┌─────────────────────────▼───────────────────────────────────┐
44
+ │ Utils Layer │
45
+ │ ┌──────────┬──────────┬───────────┬──────────┐ │
46
+ │ │ Logger │ Error │ File │ Format- │ │
47
+ │ │ │ Handler │ Utils │ ters │ │
48
+ │ └──────────┴──────────┴───────────┴──────────┘ │
49
+ └─────────────────────────┬───────────────────────────────────┘
50
+
51
+ ┌─────────────────────────▼───────────────────────────────────┐
52
+ │ File System │
53
+ └─────────────────────────────────────────────────────────────┘
54
+ ```
55
+
56
+ ## 🔐 Security Architecture
57
+
58
+ ### 8-Layer Path Validation Pipeline
59
+
60
+ Every file path goes through these validation layers:
61
+
62
+ ```typescript
63
+ Input Path
64
+
65
+ 1. Type Validation (Zod Schema)
66
+
67
+ 2. Null Byte & Basic Sanitization
68
+
69
+ 3. Path Normalization & Windows Case Adjustment
70
+
71
+ 4. Traversal Sequence Prevention (../)
72
+
73
+ 5. Absolute Path Resolution
74
+
75
+ 6. Security Check (Whitelist & Blacklist)
76
+
77
+ 7. Symlink Resolution & Target Validation
78
+
79
+ 8. Existence & Access Check
80
+
81
+ Validated Path ✅
82
+ ```
83
+
84
+ **Implementation:** [`src/services/path-validator.service.ts`](file:///c:/Users/NewAdmin/Desktop/File-Organizer-MCP/src/services/path-validator.service.ts)
85
+
86
+ ### Race Condition Mitigation (TOCTOU Protection) - v3.1.4 Updates
87
+
88
+ **Problem:** Time-of-Check-Time-of-Use vulnerabilities can occur when a file is checked, then used later, allowing an attacker to swap the file between operations.
89
+
90
+ **v3.1.4 TOCTOU Fixes and Race Condition Prevention:**
91
+
92
+ 1. **File Descriptor Validation**
93
+ - Open files with `O_NOFOLLOW` flag to prevent symlink attacks
94
+ - Use file descriptors directly rather than path strings after initial validation
95
+ - Release file handles immediately after use to minimize attack window
96
+
97
+ 2. **Atomic File Operations**
98
+ - Use `COPYFILE_EXCL` flag for atomic copy operations (fails if destination exists)
99
+ - Use `O_EXCL` flag when creating files to prevent race conditions
100
+ - Utilize `rename()` for atomic moves within the same filesystem
101
+
102
+ 3. **Retry Logic with Jitter**
103
+ - Implement exponential backoff with random jitter for retry operations
104
+ - Maximum 3 retries with increasing delays (10ms, 50ms, 100ms)
105
+ - Fail fast after retries to prevent denial-of-service
106
+
107
+ 4. **Safe Overwrite Pattern**
108
+ - Write to temporary file in target directory first
109
+ - Sync file to disk before atomic rename
110
+ - Move existing file to backup before replacing
111
+
112
+ ```typescript
113
+ // Safe overwrite with atomic rename
114
+ const tempPath = path.join(targetDir, `.tmp_${Date.now()}_${basename}`);
115
+ await fs.writeFile(tempPath, content);
116
+ await fs.rename(tempPath, targetPath); // Atomic on same filesystem
117
+ ```
118
+
119
+ 5. **Verification After Operations**
120
+ - Re-validate file stats after critical operations
121
+ - Verify file hash matches expected value after write
122
+ - Check file permissions haven't changed unexpectedly
123
+
124
+ **Limitations:**
125
+
126
+ - File deletion on Windows uses path-based locking (not file descriptor)
127
+ - Symlinks are blocked for security but may limit legitimate use cases
128
+
129
+ ### Resource Protection
130
+
131
+ ```typescript
132
+ // Security Constants
133
+ const SECURITY_LIMITS = {
134
+ MAX_FILE_SIZE: 100 * 1024 * 1024, // 100 MB
135
+ MAX_FILES: 10000, // Per operation
136
+ MAX_DEPTH: 10, // Directory recursion
137
+ MAX_PATH_LENGTH: 4096, // Characters
138
+ };
139
+ ```
140
+
141
+ ## 📦 Core Components
142
+
143
+ ### 1. Server Layer (`server.ts`)
144
+
145
+ **Responsibility:** MCP protocol handling and tool registration
146
+
147
+ ```typescript
148
+ // Key responsibilities:
149
+ - Initialize MCP server
150
+ - Register tools with schemas
151
+ - Handle tool invocations
152
+ - Manage error responses
153
+ - Coordinate with services
154
+ ```
155
+
156
+ **Key Features:**
157
+
158
+ - Automatic tool discovery from `tools/` directory
159
+ - Structured response formatting (JSON/Markdown)
160
+ - Centralized error handling
161
+
162
+ ### 2. Tools Layer (`tools/`)
163
+
164
+ **Responsibility:** MCP tool implementations (user-facing API)
165
+
166
+ Each tool follows this pattern:
167
+
168
+ ```typescript
169
+ export const toolDefinition: ToolDefinition = {
170
+ name: 'tool_name',
171
+ description: 'What it does',
172
+ inputSchema: ZodSchema, // Validation
173
+ };
174
+
175
+ export async function handleTool(args: ToolArgs): Promise<ToolResponse> {
176
+ // 1. Validate inputs (Zod)
177
+ // 2. Validate security (PathValidator)
178
+ // 3. Call service layer
179
+ // 4. Format response
180
+ // 5. Handle errors
181
+ }
182
+ ```
183
+
184
+ **Available Tools:**
185
+
186
+ 1. **List Files in Directory** (`file_organizer_list_files`)
187
+ 2. **Scan Directory for Detailed Info** (`file_organizer_scan_directory`)
188
+ 3. **Categorize Files by Type** (`file_organizer_categorize_files`)
189
+ 4. **Find Largest Files** (`file_organizer_find_largest_files`)
190
+ 5. **Find Duplicate Files** (`file_organizer_find_duplicate_files`)
191
+ 6. **Preview File Organization Plan** (`file_organizer_preview_organization`)
192
+ 7. **Get Available File Categories** (`file_organizer_get_categories`)
193
+ 8. **Analyze Duplicate Files with Smart Recommendations** (`file_organizer_analyze_duplicates`)
194
+ 9. **Organize Files** (`file_organizer_organize_files`)
195
+ 10. **Set Custom Organization Rules** (`file_organizer_set_custom_rules`)
196
+ 11. **Delete Duplicate Files** (`file_organizer_delete_duplicates`)
197
+ 12. **Undo Last Organization Operation** (`file_organizer_undo_last_operation`)
198
+
199
+ ### 3. Services Layer (`services/`)
200
+
201
+ **Responsibility:** Core business logic
202
+
203
+ **Service Versions:** All services v3.1.3 or v3.1.4
204
+
205
+ #### PathValidatorService (v3.1.3)
206
+
207
+ ```typescript
208
+ class PathValidatorService {
209
+ // Multi-layer path validation
210
+ async validateStrictPath(inputPath: unknown, options?: ValidatePathOptions): Promise<string>;
211
+
212
+ // Symlink resolution
213
+ async resolvePath(path: string): Promise<string>;
214
+
215
+ // Containment checking
216
+ isPathWithinRoots(path: string, roots: string[]): boolean;
217
+ }
218
+ ```
219
+
220
+ #### OrganizerService (v3.1.4)
221
+
222
+ ```typescript
223
+ class OrganizerService {
224
+ // Generate organization plan
225
+ async generateOrganizationPlan(
226
+ directory: string,
227
+ files: FileWithSize[],
228
+ strategy?: ConflictStrategy // 'rename' | 'skip' | 'overwrite' | 'overwrite_if_newer'
229
+ ): Promise<OrganizationPlan>;
230
+
231
+ // Execute organization with safety guarantees
232
+ async organize(
233
+ directory: string,
234
+ files: FileWithSize[],
235
+ options?: OrganizeOptions
236
+ ): Promise<OrganizeResult>;
237
+
238
+ // Safety mechanisms:
239
+ // 1. File descriptor validation before move
240
+ // 2. Atomic copy with COPYFILE_EXCL (race-safe)
241
+ // 3. Automatic backup to .file-organizer-backups/ on overwrite
242
+ // 4. Retry loop for race condition recovery
243
+ }
244
+ ```
245
+
246
+ #### HashCalculatorService
247
+
248
+ ```typescript
249
+ class HashCalculatorService {
250
+ // Streaming hash calculation
251
+ async calculateHash(filePath: string): Promise<string>;
252
+
253
+ // Find duplicates (memory-safe)
254
+ async findDuplicates(files: FileWithSize[]): Promise<DuplicateGroup[]>;
255
+ }
256
+ ```
257
+
258
+ #### FileScannerService (v3.1.4)
259
+
260
+ ```typescript
261
+ class FileScannerService {
262
+ // Recursive directory scanning
263
+ async getAllFiles(directory: string, options?: ScanOptions): Promise<FileWithSize[]>;
264
+
265
+ // Size calculation
266
+ async calculateDirectorySize(directory: string): Promise<number>;
267
+ }
268
+ ```
269
+
270
+ #### CategorizerService
271
+
272
+ ```typescript
273
+ class CategorizerService {
274
+ // File categorization
275
+ getCategory(fileName: string): CategoryName;
276
+
277
+ // Custom rules support
278
+ setCustomRules(rules: CategoryRule[]): void;
279
+
280
+ // Category statistics
281
+ categorizeFiles(files: FileWithSize[]): CategoryBreakdown;
282
+ }
283
+ ```
284
+
285
+ #### RollbackService (v3.1.4)
286
+
287
+ ```typescript
288
+ class RollbackService {
289
+ // Create rollback manifest
290
+ async createManifest(actions: OrganizeAction[]): Promise<string>;
291
+
292
+ // Execute rollback
293
+ async rollback(manifestId: string): Promise<RollbackResult>;
294
+
295
+ // List available rollbacks
296
+ async listRollbacks(): Promise<RollbackManifest[]>;
297
+ }
298
+ ```
299
+
300
+ ### 4. Utils Layer (`utils/`)
301
+
302
+ **Responsibility:** Shared utility functions
303
+
304
+ #### Logger
305
+
306
+ ```typescript
307
+ class Logger {
308
+ // Structured JSON logging to stderr (MCP stdio protocol)
309
+ debug(message: string, context?: Record<string, any>): void;
310
+ info(message: string, context?: Record<string, any>): void;
311
+ warn(message: string, context?: Record<string, any>): void;
312
+ error(message: string, error?: Error, context?: Record<string, any>): void;
313
+
314
+ // Features:
315
+ // - ISO 8601 timestamps
316
+ // - Configurable log levels (debug/info/warn/error)
317
+ // - Error stack traces for error logs
318
+ // - JSON format for machine parsing
319
+ }
320
+ ```
321
+
322
+ - **error-handler.ts** - Centralized error handling
323
+ - **file-utils.ts** - File system helpers
324
+ - **formatters.ts** - Data formatting (bytes, dates, etc.)
325
+
326
+ ### 5. Schemas Layer (`schemas/`)
327
+
328
+ **Responsibility:** Input validation using Zod
329
+
330
+ ```typescript
331
+ // Example: Path validation
332
+ export const PathSchema = z
333
+ .string()
334
+ .min(1, 'Path cannot be empty')
335
+ .max(4096, 'Path exceeds maximum length')
336
+ .refine((path) => !path.includes('\0'), 'Path contains null bytes');
337
+ ```
338
+
339
+ ## 🔄 Data Flow
340
+
341
+ ### Example: Organize Files Operation
342
+
343
+ ```
344
+ 1. LLM Request
345
+
346
+ 2. MCP Server (server.ts)
347
+ - Parse JSON-RPC request
348
+ - Route to organize tool
349
+
350
+ 3. Tool Handler (tools/file-organization.ts)
351
+ - Validate args with Zod
352
+ - Call PathValidatorService
353
+
354
+ 4. PathValidatorService
355
+ - 7-layer validation
356
+ - Return validated path
357
+
358
+ 5. FileScannerService
359
+ - Scan directory
360
+ - Apply resource limits
361
+
362
+ 6. CategorizerService
363
+ - Categorize each file
364
+
365
+ 7. OrganizerService
366
+ - Generate organization plan
367
+ - Check conflicts
368
+ - Execute moves (if not dry run)
369
+
370
+ 8. RollbackService
371
+ - Create rollback manifest
372
+
373
+ 9. Tool Handler
374
+ - Format response (JSON/Markdown)
375
+
376
+ 10. MCP Server
377
+ - Send JSON-RPC response
378
+
379
+ 11. LLM receives result
380
+ ```
381
+
382
+ ## 💾 File Organization
383
+
384
+ ### Source Structure
385
+
386
+ ```
387
+ src/
388
+ ├── server.ts # MCP server entry point
389
+ ├── index.ts # Main entry point
390
+ ├── types.ts # TypeScript type definitions
391
+ ├── constants.ts # Application constants
392
+ ├── config.ts # Configuration management
393
+
394
+ ├── services/ # Core business logic
395
+ │ ├── path-validator.service.ts
396
+ │ ├── organizer.service.ts
397
+ │ ├── hash-calculator.service.ts
398
+ │ ├── file-scanner.service.ts
399
+ │ ├── categorizer.service.ts
400
+ │ └── rollback.service.ts
401
+
402
+ ├── tools/ # MCP tool implementations
403
+ │ ├── file-scanning.ts
404
+ ├── file-organization.ts
405
+ │ ├── file-duplicates.ts
406
+ │ ├── file-categorization.ts
407
+ └── ...
408
+
409
+ ├── schemas/ # Zod validation schemas
410
+ ├── security.schemas.ts
411
+ ├── common.schemas.ts
412
+ │ ├── scan.schemas.ts
413
+ │ └── organize.schemas.ts
414
+
415
+ └── utils/ # Shared utilities
416
+ ├── logger.ts
417
+ ├── error-handler.ts
418
+ ├── file-utils.ts
419
+ └── formatters.ts
420
+ ```
421
+
422
+ ## 🧪 Testing Architecture
423
+
424
+ ### Test Structure
425
+
426
+ ```
427
+ tests/
428
+ ├── unit/ # Unit tests for services
429
+ │ ├── services/
430
+ │ │ ├── path-validator.test.ts
431
+ │ │ ├── organizer.test.ts
432
+ │ │ └── ...
433
+ │ └── utils/
434
+
435
+ ├── integration/ # Integration tests for tools
436
+ │ ├── tools/
437
+ │ │ └── organize.test.ts
438
+ │ └── edge-cases.test.ts
439
+
440
+ └── performance/ # Performance benchmarks
441
+ └── performance.test.ts
442
+ ```
443
+
444
+ ### Test Philosophy
445
+
446
+ 1. **Unit Tests** - Test services in isolation
447
+ 2. **Integration Tests** - Test complete workflows
448
+ 3. **Security Tests** - Validate all security controls
449
+ 4. **Performance Tests** - Ensure scalability
450
+
451
+ ## 🚀 Performance Considerations
452
+
453
+ ### Streaming Operations
454
+
455
+ Large files are processed using streams to avoid memory exhaustion:
456
+
457
+ ```typescript
458
+ // Hash calculation uses streams
459
+ const hash = crypto.createHash('sha256');
460
+ const stream = createReadStream(filePath, { highWaterMark: 64 * 1024 });
461
+ stream.on('data', (chunk) => hash.update(chunk));
462
+ ```
463
+
464
+ ### Resource Limits
465
+
466
+ ```typescript
467
+ // Enforced at multiple levels:
468
+ - File size: Skip files > 100MB for hashing
469
+ - File count: Max 10,000 files per operation
470
+ - Recursion depth: Max 10 levels
471
+ - Path length: Max 4,096 characters
472
+ ```
473
+
474
+ ### Caching Strategy
475
+
476
+ - Category mappings cached in-memory
477
+ - File stats cached during single operation
478
+ - No persistent caching (stateless design)
479
+
480
+ ## 🔧 Configuration
481
+
482
+ ### Configuration System (`config.ts`)
483
+
484
+ The server uses a platform-aware configuration system that combines hardcoded defaults with user customization.
485
+
486
+ **Structure:**
487
+
488
+ ```typescript
489
+ export const CONFIG = {
490
+ VERSION: '3.1.5',
491
+
492
+ security: {
493
+ enablePathValidation: true,
494
+ allowCustomDirectories: true,
495
+ logAccess: true,
496
+ maxScanDepth: 10,
497
+ maxFilesPerOperation: 10000,
498
+ },
499
+
500
+ paths: {
501
+ defaultAllowed: getDefaultAllowedDirs(), // Platform-aware safe directories
502
+ customAllowed: loadCustomAllowedDirs(), // User-defined from config.json
503
+ alwaysBlocked: getAlwaysBlockedPatterns(), // System protection patterns
504
+ },
505
+ };
506
+ ```
507
+
508
+ **Default Allowed Directories:**
509
+
510
+ - **Windows:** Desktop, Documents, Downloads, Pictures, Videos, Music, OneDrive, Projects
511
+ - **macOS:** Desktop, Documents, Downloads, Movies, Music, Pictures, iCloud Drive, Projects
512
+ - **Linux:** Desktop, Documents, Downloads, Music, Pictures, Videos, ~/dev, ~/workspace
513
+
514
+ **User Configuration:**
515
+
516
+ - **Windows:** `%APPDATA%\file-organizer-mcp\config.json`
517
+ - **macOS:** `~/Library/Application Support/file-organizer-mcp/config.json`
518
+ - **Linux:** `~/.config/file-organizer-mcp/config.json`
519
+
520
+ **Config File Format:**
521
+
522
+ ```json
523
+ {
524
+ "customAllowedDirectories": ["C:\\Users\\Name\\CustomFolder", "D:\\Projects"],
525
+ "settings": {
526
+ "maxScanDepth": 10,
527
+ "logAccess": true
528
+ }
529
+ }
530
+ ```
531
+
532
+ ## 🎯 Design Patterns
533
+
534
+ ### Dependency Injection
535
+
536
+ ```typescript
537
+ // Services receive dependencies via constructor
538
+ class OrganizerService {
539
+ constructor(
540
+ private categorizer: CategorizerService,
541
+ private rollback?: RollbackService
542
+ ) {}
543
+ }
544
+ ```
545
+
546
+ ### Error Handling
547
+
548
+ ```typescript
549
+ // Centralized error handling
550
+ try {
551
+ const result = await operation();
552
+ } catch (error) {
553
+ return createErrorResponse(error);
554
+ }
555
+ ```
556
+
557
+ ### Type Safety
558
+
559
+ ```typescript
560
+ // Strict types with Zod runtime validation
561
+ const ArgsSchema = z.object({
562
+ directory: PathSchema,
563
+ dry_run: z.boolean().optional(),
564
+ });
565
+
566
+ type Args = z.infer<typeof ArgsSchema>;
567
+ ```
568
+
569
+ ## 📊 Monitoring & Logging
570
+
571
+ ### Structured Logging
572
+
573
+ ```json
574
+ {
575
+ "timestamp": "2026-02-08T00:00:00.000Z",
576
+ "level": "info",
577
+ "message": "Created rollback manifest: uuid (6 actions)"
578
+ }
579
+ ```
580
+
581
+ ### Log Levels
582
+
583
+ - `error` - Critical failures
584
+ - `warn` - Recoverable issues (e.g., skipped files)
585
+ - `info` - Operation milestones
586
+ - `debug` - Detailed diagnostics
587
+
588
+ ## 🔮 Future Architecture Changes
589
+
590
+ ### Planned Improvements
591
+
592
+ 1. **Plugin System** - Allow custom categorization rules
593
+ 2. **Database Layer** - Persistent state for large operations
594
+ 3. **Queue System** - Background processing for large directories
595
+ 4. **Metrics Collection** - Performance monitoring
596
+ 5. **Multi-language Support** - i18n infrastructure
597
+
598
+ ## 📚 References
599
+
600
+ - [Model Context Protocol Spec](https://modelcontextprotocol.io)
601
+ - [Zod Documentation](https://zod.dev)
602
+ - [TypeScript Handbook](https://www.typescriptlang.org/docs)
603
+
604
+ ---
605
+
606
+ **Last Updated:** February 8, 2026
607
+ **Version:** 3.1.5