mcp-code-context 2.1.3 → 2.3.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.
Files changed (128) hide show
  1. package/.io/RULES.md +12 -0
  2. package/CHANGELOG.md +118 -58
  3. package/CONTRIBUTING.md +243 -0
  4. package/README.md +58 -7
  5. package/RELEASE_NOTES_v2.2.0.md +286 -0
  6. package/RELEASE_NOTES_v2.3.0.md +228 -0
  7. package/RELEASE_NOTES_v2.3.1.md +110 -0
  8. package/dist/src/ast/writers/safeRename.d.ts +14 -0
  9. package/dist/src/ast/writers/safeRename.js +258 -0
  10. package/dist/src/ast/writers/safeRename.js.map +1 -0
  11. package/dist/src/ast/writers/symbolWriter.d.ts +2 -0
  12. package/dist/src/ast/writers/symbolWriter.js +9 -14
  13. package/dist/src/ast/writers/symbolWriter.js.map +1 -1
  14. package/dist/src/cache/astCache.d.ts +33 -0
  15. package/dist/src/cache/astCache.js +113 -0
  16. package/dist/src/cache/astCache.js.map +1 -0
  17. package/dist/src/handlers/readHandlers.d.ts +70 -0
  18. package/dist/src/handlers/readHandlers.js +431 -0
  19. package/dist/src/handlers/readHandlers.js.map +1 -0
  20. package/dist/src/handlers/utilHandlers.d.ts +31 -0
  21. package/dist/src/handlers/utilHandlers.js +69 -0
  22. package/dist/src/handlers/utilHandlers.js.map +1 -0
  23. package/dist/src/handlers/writeHandlers.d.ts +57 -0
  24. package/dist/src/handlers/writeHandlers.js +475 -0
  25. package/dist/src/handlers/writeHandlers.js.map +1 -0
  26. package/dist/src/index.d.ts +6 -107
  27. package/dist/src/index.js +147 -965
  28. package/dist/src/index.js.map +1 -1
  29. package/dist/src/tools/readFileLines.d.ts +26 -0
  30. package/dist/src/tools/readFileLines.js +77 -0
  31. package/dist/src/tools/readFileLines.js.map +1 -0
  32. package/dist/src/tools/searchCodePattern.d.ts +32 -0
  33. package/dist/src/tools/searchCodePattern.js +80 -0
  34. package/dist/src/tools/searchCodePattern.js.map +1 -0
  35. package/dist/src/utils/arrayUtils.d.ts +12 -0
  36. package/dist/src/utils/arrayUtils.js +27 -0
  37. package/dist/src/utils/arrayUtils.js.map +1 -0
  38. package/dist/src/utils/backupManager.d.ts +13 -6
  39. package/dist/src/utils/backupManager.js +73 -8
  40. package/dist/src/utils/backupManager.js.map +1 -1
  41. package/dist/src/utils/constants.d.ts +46 -0
  42. package/dist/src/utils/constants.js +112 -0
  43. package/dist/src/utils/constants.js.map +1 -0
  44. package/dist/src/utils/ignoreManager.d.ts +8 -0
  45. package/dist/src/utils/ignoreManager.js +49 -0
  46. package/dist/src/utils/ignoreManager.js.map +1 -1
  47. package/dist/src/utils/normalization.d.ts +49 -0
  48. package/dist/src/utils/normalization.js +173 -0
  49. package/dist/src/utils/normalization.js.map +1 -0
  50. package/dist/src/utils/projectRoot.d.ts +17 -0
  51. package/dist/src/utils/projectRoot.js +42 -0
  52. package/dist/src/utils/projectRoot.js.map +1 -0
  53. package/dist/src/utils/secureValidation.d.ts +15 -0
  54. package/dist/src/utils/secureValidation.js +41 -0
  55. package/dist/src/utils/secureValidation.js.map +1 -0
  56. package/dist/src/utils/transactionManager.d.ts +45 -0
  57. package/dist/src/utils/transactionManager.js +102 -0
  58. package/dist/src/utils/transactionManager.js.map +1 -0
  59. package/dist/src/utils/validation.d.ts +87 -0
  60. package/dist/src/utils/validation.js +231 -0
  61. package/dist/src/utils/validation.js.map +1 -0
  62. package/docs/ARCHITECTURE.md +300 -0
  63. package/docs/architecture/ADR-001-modular-handlers.md +119 -0
  64. package/llms.txt +62 -7
  65. package/package.json +5 -5
  66. package/AGENT_INSTRUCTIONS.md +0 -135
  67. package/DEPLOYMENT_INSTRUCTIONS.md +0 -110
  68. package/dist/src/tests/test-confirmation-flow.d.ts +0 -1
  69. package/dist/src/tests/test-confirmation-flow.js +0 -43
  70. package/dist/src/tests/test-confirmation-flow.js.map +0 -1
  71. package/dist/tests/debug-replace.d.ts +0 -1
  72. package/dist/tests/debug-replace.js +0 -17
  73. package/dist/tests/debug-replace.js.map +0 -1
  74. package/dist/tests/test-confirmation-flow.d.ts +0 -1
  75. package/dist/tests/test-confirmation-flow.js +0 -43
  76. package/dist/tests/test-confirmation-flow.js.map +0 -1
  77. package/dist/tests/test-dart.d.ts +0 -1
  78. package/dist/tests/test-dart.js +0 -242
  79. package/dist/tests/test-dart.js.map +0 -1
  80. package/dist/tests/test-php-ast.d.ts +0 -1
  81. package/dist/tests/test-php-ast.js +0 -152
  82. package/dist/tests/test-php-ast.js.map +0 -1
  83. package/dist/tests/test-php.d.ts +0 -1
  84. package/dist/tests/test-php.js +0 -234
  85. package/dist/tests/test-php.js.map +0 -1
  86. package/dist/tests/test-smoke.d.ts +0 -5
  87. package/dist/tests/test-smoke.js +0 -83
  88. package/dist/tests/test-smoke.js.map +0 -1
  89. package/dist/tests/writers/test-crlf-handling.d.ts +0 -4
  90. package/dist/tests/writers/test-crlf-handling.js +0 -73
  91. package/dist/tests/writers/test-crlf-handling.js.map +0 -1
  92. package/dist/tests/writers/test-write-smoke.d.ts +0 -9
  93. package/dist/tests/writers/test-write-smoke.js +0 -346
  94. package/dist/tests/writers/test-write-smoke.js.map +0 -1
  95. package/src/ast/dartCompressor.ts +0 -1013
  96. package/src/ast/phpCompressor.ts +0 -814
  97. package/src/ast/semanticCompressor.ts +0 -808
  98. package/src/ast/writers/dartWriter.ts +0 -648
  99. package/src/ast/writers/phpWriter.ts +0 -508
  100. package/src/ast/writers/pyWriter.ts +0 -446
  101. package/src/ast/writers/symbolWriter.ts +0 -277
  102. package/src/ast/writers/tsWriter.ts +0 -418
  103. package/src/index.ts +0 -1553
  104. package/src/utils/backupManager.ts +0 -66
  105. package/src/utils/confirmationCache.ts +0 -61
  106. package/src/utils/diffEngine.ts +0 -223
  107. package/src/utils/fuzzyMatch.ts +0 -86
  108. package/src/utils/ignoreManager.ts +0 -144
  109. package/tests/test-confirmation-flow.ts +0 -49
  110. package/tests/test-dart.d.ts +0 -1
  111. package/tests/test-dart.js +0 -209
  112. package/tests/test-dart.js.map +0 -1
  113. package/tests/test-dart.ts +0 -265
  114. package/tests/test-php-ast.d.ts +0 -1
  115. package/tests/test-php-ast.js +0 -152
  116. package/tests/test-php-ast.js.map +0 -1
  117. package/tests/test-php-ast.ts +0 -155
  118. package/tests/test-php.d.ts +0 -1
  119. package/tests/test-php.js +0 -234
  120. package/tests/test-php.js.map +0 -1
  121. package/tests/test-php.ts +0 -261
  122. package/tests/test-smoke.d.ts +0 -5
  123. package/tests/test-smoke.js +0 -83
  124. package/tests/test-smoke.js.map +0 -1
  125. package/tests/test-smoke.ts +0 -93
  126. package/tests/writers/test-crlf-handling.ts +0 -100
  127. package/tests/writers/test-write-smoke.ts +0 -568
  128. package/tsconfig.json +0 -19
package/src/index.ts DELETED
@@ -1,1553 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * mcp-code-context — Semantic Code Context Server
5
- *
6
- * A Model Context Protocol (MCP) server that compresses any code repository
7
- * into LLM-ready semantic context and provides surgical code editing.
8
- *
9
- * Read Tools:
10
- * 1. get_semantic_repo_map — Compressed structural map of a repo
11
- * 2. read_file_surgical — Full file or specific symbol extraction
12
- * 3. analyze_impact — Find all dependents of a modified file
13
- *
14
- * Write Tools:
15
- * 4. write_file_surgical — Replace a symbol's code in-place
16
- * 5. insert_symbol — Insert code at precise AST positions
17
- * 6. rename_symbol — Rename across entire repository
18
- * 7. remove_symbol — Safely delete symbols with dep checking
19
- *
20
- * Transport: stdio (JSON-RPC over stdin/stdout)
21
- * Compatible with: Claude Desktop, Cursor, Windsurf, Copilot, Amazon Q, and any MCP client.
22
- */
23
-
24
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
25
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
26
- import {
27
- CallToolRequestSchema,
28
- ListToolsRequestSchema,
29
- } from "@modelcontextprotocol/sdk/types.js";
30
- import { IgnoreManager } from "./utils/ignoreManager.js";
31
- import { compressFile, extractSymbol } from "./ast/semanticCompressor.js";
32
- import {
33
- replaceSymbol,
34
- insertCode,
35
- renameInFile,
36
- renameReferencesInFile,
37
- removeSymbolFromFile,
38
- WRITABLE_EXTENSIONS,
39
- type WriteResult,
40
- type InsertPosition,
41
- } from "./ast/writers/symbolWriter.js";
42
- import { generateDiff, generateMultiFileDiff } from "./utils/diffEngine.js";
43
- import { createBackup, restoreBackup, cleanBackup } from "./utils/backupManager.js";
44
- import { extractFallbackSymbols, findClosestSymbols } from "./utils/fuzzyMatch.js";
45
- import { confirmationCache } from "./utils/confirmationCache.js";
46
- import * as fs from "node:fs";
47
- import * as path from "node:path";
48
-
49
- // ─── Constants ──────────────────────────────────────────────────────
50
-
51
- const SERVER_NAME = "mcp-code-context";
52
- const SERVER_VERSION = "2.0.0";
53
-
54
- /** Extensions we consider source code for analysis */
55
- const SOURCE_EXTENSIONS = new Set([
56
- ".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs", ".cts", ".cjs",
57
- ".py", ".pyi",
58
- ".json", ".yaml", ".yml", ".toml",
59
- ".md", ".txt",
60
- ".css", ".scss", ".less",
61
- ".html", ".vue", ".svelte",
62
- ".rs", ".go", ".java", ".kt", ".dart",
63
- ".c", ".cpp", ".h", ".hpp",
64
- ".rb", ".php", ".swift",
65
- ".sh", ".bash", ".zsh",
66
- ".sql",
67
- ".graphql", ".gql",
68
- ".proto",
69
- ".dockerfile",
70
- ]);
71
-
72
- /** Extensions eligible for import analysis */
73
- const IMPORTABLE_EXTENSIONS = new Set([
74
- ".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs", ".cts", ".cjs",
75
- ".py", ".pyi",
76
- ".php", ".phtml",
77
- ".dart",
78
- ".vue", ".svelte",
79
- ]);
80
-
81
- // ─── MCP Server Instance ────────────────────────────────────────────
82
-
83
- const server = new Server(
84
- { name: SERVER_NAME, version: SERVER_VERSION },
85
- { capabilities: { tools: {} } },
86
- );
87
-
88
- // ─── Tool Definitions ───────────────────────────────────────────────
89
-
90
- const TOOLS = [
91
- {
92
- name: "get_semantic_repo_map",
93
- description:
94
- "Generates a semantically compressed map of a code repository. " +
95
- "Walks the directory tree respecting .gitignore rules, reads source files, " +
96
- "and extracts only structural signatures (functions, classes, interfaces, types) " +
97
- "while stripping implementation bodies. Returns an XML or Markdown document " +
98
- "optimized for LLM consumption with minimal token usage. " +
99
- "Supports TypeScript, JavaScript, PHP (AST-based), Dart, and Python. " +
100
- "Use this to understand the architecture of a large codebase at a glance.",
101
- inputSchema: {
102
- type: "object" as const,
103
- properties: {
104
- directoryPath: {
105
- type: "string",
106
- description:
107
- "Absolute path to the repository root directory to analyze.",
108
- },
109
- format: {
110
- type: "string",
111
- enum: ["xml", "markdown"],
112
- description:
113
- "Output format for the repo map. 'xml' (default) provides structured data, " +
114
- "'markdown' provides human-readable output.",
115
- },
116
- },
117
- required: ["directoryPath"],
118
- },
119
- },
120
- {
121
- name: "read_file_surgical",
122
- description:
123
- "Reads the complete source code of a file, or surgically extracts only " +
124
- "a specific named symbol (function, class, interface, method, type alias). " +
125
- "When a symbol name is provided, only the full source code block for that " +
126
- "symbol is returned — saving tokens compared to reading the entire file. " +
127
- "Supports TypeScript, JavaScript, PHP, Dart, and Python files for symbol extraction.",
128
- inputSchema: {
129
- type: "object" as const,
130
- properties: {
131
- filePath: {
132
- type: "string",
133
- description: "Absolute path to the source file to read.",
134
- },
135
- symbolName: {
136
- type: "string",
137
- description:
138
- "Optional. Name of a specific function, class, interface, method, " +
139
- "or type alias to extract. If omitted, the entire file is returned.",
140
- },
141
- className: {
142
- type: "string",
143
- description:
144
- "Optional. Name of the class to scope the symbol search to. " +
145
- "Use this when multiple classes in the same file have methods with the same name " +
146
- "(e.g., multiple build() methods in Flutter). If omitted, returns the first match.",
147
- },
148
- },
149
- required: ["filePath"],
150
- },
151
- },
152
- {
153
- name: "rollback_file",
154
- description: "Reverts a file to a previous backup state after a surgical write operation. Keeps up to 5 automatic backups. Specify the number of steps to rollback (1 = most recent).",
155
- inputSchema: {
156
- type: "object" as const,
157
- properties: {
158
- filePath: {
159
- type: "string",
160
- description: "Absolute path to the source file to revert.",
161
- },
162
- steps: {
163
- type: "number",
164
- description: "Number of steps back to revert to (1-5). Defaults to 1 (most recent backup).",
165
- }
166
- },
167
- required: ["filePath"],
168
- },
169
- },
170
- {
171
- name: "analyze_impact",
172
- description:
173
- "Analyzes the impact of modifying a given file by discovering all other " +
174
- "files in the repository that import or depend on it. Scans for ES import/export, " +
175
- "CommonJS require(), Python import, PHP use/require_once/include, and Dart import statements. " +
176
- "Returns a structured report listing all dependent files and the specific " +
177
- "import statements that create the dependency. Essential for understanding " +
178
- "blast radius before refactoring.",
179
- inputSchema: {
180
- type: "object" as const,
181
- properties: {
182
- filePath: {
183
- type: "string",
184
- description:
185
- "Absolute path to the file being modified (the dependency target).",
186
- },
187
- rootDir: {
188
- type: "string",
189
- description:
190
- "Optional. Absolute path to the repository root. If omitted, " +
191
- "the server walks up from filePath to find the nearest directory " +
192
- "containing package.json, .git, or similar root markers.",
193
- },
194
- },
195
- required: ["filePath"],
196
- },
197
- },
198
- // ─── Write Tools ────────────────────────────────────────────────────
199
- {
200
- name: "write_file_surgical",
201
- description:
202
- "Surgically replaces the full source code of a named symbol (function, class, " +
203
- "method, interface, type alias) in a file. The AI provides ONLY the replacement " +
204
- "code for that specific symbol — the tool handles locating it via AST parsing " +
205
- "and splicing the replacement into the correct position. Supports TypeScript, " +
206
- "JavaScript, PHP, Dart, and Python. Returns a unified diff of the changes. " +
207
- "Supports dry-run mode to preview changes without modifying the file.",
208
- inputSchema: {
209
- type: "object" as const,
210
- properties: {
211
- filePath: {
212
- type: "string",
213
- description: "Absolute path to the source file to modify.",
214
- },
215
- symbolName: {
216
- type: "string",
217
- description:
218
- "Name of the function, class, method, interface, or type alias to replace.",
219
- },
220
- newContent: {
221
- type: "string",
222
- description:
223
- "The complete replacement source code for the symbol, including its " +
224
- "signature and body. Must be syntactically valid for the target language.",
225
- },
226
- className: {
227
- type: "string",
228
- description:
229
- "Optional. Name of the class to scope the symbol search to. " +
230
- "Use when multiple classes have methods with the same name.",
231
- },
232
- confirmationToken: {
233
- type: "string",
234
- description:
235
- "Required for Phase 2. The token provided from the Phase 1 Dry-Run preview.",
236
- },
237
- confirm: {
238
- type: "boolean",
239
- description:
240
- "Required for Phase 2. Set to true to confirm and apply the changes.",
241
- },
242
- createBackup: {
243
- type: "boolean",
244
- description:
245
- "If true, creates a .bak copy of the file before modifying it. " +
246
- "Defaults to false (opt-in).",
247
- },
248
- },
249
- required: ["filePath", "symbolName", "newContent"],
250
- },
251
- },
252
- {
253
- name: "insert_symbol",
254
- description:
255
- "Inserts new code at a precise location relative to an existing symbol in a file. " +
256
- "Can insert before or after a symbol, or inside a class/interface at the start or end. " +
257
- "If no anchor symbol is provided, inserts at the end of the file. " +
258
- "Supports TypeScript, JavaScript, PHP, Dart, and Python. " +
259
- "Automatically matches the surrounding indentation style.",
260
- inputSchema: {
261
- type: "object" as const,
262
- properties: {
263
- filePath: {
264
- type: "string",
265
- description: "Absolute path to the source file to modify.",
266
- },
267
- code: {
268
- type: "string",
269
- description: "The new code to insert. Must be syntactically valid.",
270
- },
271
- anchorSymbol: {
272
- type: "string",
273
- description:
274
- "Name of an existing symbol to position relative to. " +
275
- "If omitted, code is inserted at the end of the file.",
276
- },
277
- position: {
278
- type: "string",
279
- enum: ["before", "after", "inside_start", "inside_end"],
280
- description:
281
- "Where to insert relative to the anchor. 'before' and 'after' insert " +
282
- "outside the symbol. 'inside_start' and 'inside_end' insert as members " +
283
- "inside a class or interface. Defaults to 'after'.",
284
- },
285
- className: {
286
- type: "string",
287
- description:
288
- "Optional. Name of the class to scope the anchor symbol search to. " +
289
- "Use when multiple classes have methods with the same name.",
290
- },
291
- dryRun: {
292
- type: "boolean",
293
- description: "If true, preview changes without modifying the file.",
294
- },
295
- createBackup: {
296
- type: "boolean",
297
- description: "If true, backup the file before modifying.",
298
- },
299
- },
300
- required: ["filePath", "code"],
301
- },
302
- },
303
- {
304
- name: "rename_symbol",
305
- description:
306
- "Renames a symbol across an entire repository. Renames the definition in the " +
307
- "source file AND updates all files that import or reference it. Uses AST-aware " +
308
- "whole-word replacement to avoid false matches. Supports TypeScript, JavaScript, " +
309
- "PHP, Dart, and Python. Returns a multi-file diff showing all changes. " +
310
- "Essential for safe refactoring.",
311
- inputSchema: {
312
- type: "object" as const,
313
- properties: {
314
- filePath: {
315
- type: "string",
316
- description:
317
- "Absolute path to the file where the symbol is defined.",
318
- },
319
- oldName: {
320
- type: "string",
321
- description: "The current name of the symbol.",
322
- },
323
- newName: {
324
- type: "string",
325
- description: "The new name for the symbol.",
326
- },
327
- rootDir: {
328
- type: "string",
329
- description:
330
- "Optional. Absolute path to the repository root. " +
331
- "If omitted, auto-detected from the file path.",
332
- },
333
- confirmationToken: {
334
- type: "string",
335
- description:
336
- "Required for Phase 2. The token provided from the Phase 1 Dry-Run preview.",
337
- },
338
- confirm: {
339
- type: "boolean",
340
- description:
341
- "Required for Phase 2. Set to true to confirm and apply the changes.",
342
- },
343
- createBackup: {
344
- type: "boolean",
345
- description: "If true, backup each modified file before changing it.",
346
- },
347
- },
348
- required: ["filePath", "oldName", "newName"],
349
- },
350
- },
351
- {
352
- name: "remove_symbol",
353
- description:
354
- "Removes a named symbol from a file. By default, checks for dependents first " +
355
- "and refuses to remove if other files import or reference the symbol. " +
356
- "Use force=true to skip the dependency check and remove anyway. " +
357
- "Supports TypeScript, JavaScript, PHP, Dart, and Python. " +
358
- "Returns a diff showing what was removed.",
359
- inputSchema: {
360
- type: "object" as const,
361
- properties: {
362
- filePath: {
363
- type: "string",
364
- description: "Absolute path to the source file.",
365
- },
366
- symbolName: {
367
- type: "string",
368
- description: "Name of the symbol to remove.",
369
- },
370
- className: {
371
- type: "string",
372
- description:
373
- "Optional. Name of the class to scope the symbol search to. " +
374
- "Use when multiple classes have methods with the same name.",
375
- },
376
- force: {
377
- type: "boolean",
378
- description:
379
- "If true, skip the dependency check and remove the symbol even if " +
380
- "other files reference it. Defaults to false.",
381
- },
382
- dryRun: {
383
- type: "boolean",
384
- description: "If true, preview the removal without modifying the file.",
385
- },
386
- createBackup: {
387
- type: "boolean",
388
- description: "If true, backup the file before modifying.",
389
- },
390
- },
391
- required: ["filePath", "symbolName"],
392
- },
393
- },
394
- ];
395
-
396
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
397
- tools: TOOLS,
398
- }));
399
-
400
- // ─── Tool Dispatcher ────────────────────────────────────────────────
401
-
402
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
403
- const { name, arguments: args } = request.params;
404
-
405
- try {
406
- switch (name) {
407
- case "get_semantic_repo_map":
408
- return await handleGetSemanticRepoMap(
409
- args as Record<string, unknown>,
410
- );
411
- case "read_file_surgical":
412
- return await handleReadFileSurgical(
413
- args as Record<string, unknown>,
414
- );
415
- case "analyze_impact":
416
- return await handleAnalyzeImpact(args as Record<string, unknown>);
417
- case "write_file_surgical":
418
- return await handleWriteFileSurgical(
419
- args as Record<string, unknown>,
420
- );
421
- case "insert_symbol":
422
- return await handleInsertSymbol(
423
- args as Record<string, unknown>,
424
- );
425
- case "rename_symbol":
426
- return await handleRenameSymbol(
427
- args as Record<string, unknown>,
428
- );
429
- case "remove_symbol":
430
- return await handleRemoveSymbol(
431
- args as Record<string, unknown>,
432
- );
433
- case "rollback_file":
434
- return await handleRollbackFile(
435
- args as Record<string, unknown>,
436
- );
437
- default:
438
- return errorResponse(`Unknown tool: "${name}"`);
439
- }
440
- } catch (error: unknown) {
441
- const message =
442
- error instanceof Error ? error.message : String(error);
443
- return errorResponse(`Unhandled error in tool "${name}": ${message}`);
444
- }
445
- });
446
-
447
- // ─── Tool 1: get_semantic_repo_map ──────────────────────────────────
448
-
449
- export async function handleGetSemanticRepoMap(args: Record<string, unknown>) {
450
- const directoryPath = args.directoryPath as string;
451
- const format = (args.format as string) || "xml";
452
-
453
- if (!directoryPath) {
454
- return errorResponse("Missing required parameter: directoryPath");
455
- }
456
-
457
- const resolvedPath = path.resolve(directoryPath);
458
-
459
- if (!fs.existsSync(resolvedPath)) {
460
- return errorResponse(`Directory not found: ${resolvedPath}`);
461
- }
462
-
463
- const stat = fs.statSync(resolvedPath);
464
- if (!stat.isDirectory()) {
465
- return errorResponse(`Path is not a directory: ${resolvedPath}`);
466
- }
467
-
468
- const ignoreManager = new IgnoreManager(resolvedPath);
469
- const files = ignoreManager.walkDirectory();
470
- const projectName = path.basename(resolvedPath);
471
-
472
- const entries: FileEntry[] = [];
473
- let skippedCount = 0;
474
-
475
- for (const file of files) {
476
- const ext = path.extname(file).toLowerCase();
477
- if (!SOURCE_EXTENSIONS.has(ext)) {
478
- skippedCount++;
479
- continue;
480
- }
481
-
482
- let content: string;
483
- try {
484
- content = fs.readFileSync(file, "utf-8");
485
- } catch {
486
- skippedCount++;
487
- continue;
488
- }
489
-
490
- // Skip files with null bytes (binary masquerading as text)
491
- if (content.includes("\0")) {
492
- skippedCount++;
493
- continue;
494
- }
495
-
496
- const relativePath = path
497
- .relative(resolvedPath, file)
498
- .replace(/\\/g, "/");
499
- const language = getLanguageName(ext);
500
- const compressed = compressFile(file, content);
501
-
502
- entries.push({ relativePath, language, compressed });
503
- }
504
-
505
- const output =
506
- format === "markdown"
507
- ? formatAsMarkdown(projectName, resolvedPath, entries, skippedCount)
508
- : formatAsXml(projectName, resolvedPath, entries, skippedCount);
509
-
510
- return {
511
- content: [{ type: "text" as const, text: output }],
512
- };
513
- }
514
-
515
- // ─── Tool 2: read_file_surgical ─────────────────────────────────────
516
-
517
- export async function handleReadFileSurgical(args: Record<string, unknown>) {
518
- const filePath = args.filePath as string;
519
- const symbolName = args.symbolName as string | undefined;
520
- const className = args.className as string | undefined;
521
-
522
- if (!filePath) {
523
- return errorResponse("Missing required parameter: filePath");
524
- }
525
-
526
- const resolvedPath = path.resolve(filePath);
527
-
528
- if (!fs.existsSync(resolvedPath)) {
529
- return errorResponse(`File not found: ${resolvedPath}`);
530
- }
531
-
532
- let content: string;
533
- try {
534
- content = fs.readFileSync(resolvedPath, "utf-8");
535
- } catch (error: unknown) {
536
- const msg = error instanceof Error ? error.message : String(error);
537
- return errorResponse(`Failed to read file: ${msg}`);
538
- }
539
-
540
- // If no symbol requested, return the full file
541
- if (!symbolName) {
542
- return {
543
- content: [
544
- {
545
- type: "text" as const,
546
- text: `// File: ${resolvedPath}\n// Lines: ${content.split("\n").length}\n\n${content}`,
547
- },
548
- ],
549
- };
550
- }
551
-
552
- // Attempt surgical extraction
553
- const extracted = extractSymbol(content, symbolName, resolvedPath, className);
554
-
555
- if (extracted === null) {
556
- // Symbol not found — use fuzzy matching to return suggestions
557
- const available = extractFallbackSymbols(content);
558
- const closest = findClosestSymbols(symbolName, available, 5);
559
-
560
- const availableFormatted = available.slice(0, 15).map(s => `${s.name} (${s.type}${s.className ? ` in ${s.className}` : ''})`);
561
- if (available.length > 15) availableFormatted.push(`...and ${available.length - 15} more`);
562
-
563
- const suggestions = [];
564
- if (className) {
565
- // Check if it exists in another class
566
- const inOtherClass = available.find(s => s.name === symbolName && s.className !== className);
567
- if (inOtherClass) suggestions.push(`Did you mean '${symbolName}' in class '${inOtherClass.className}'? Update your className parameter.`);
568
- } else {
569
- // Check if it requires a class scope
570
- const needsScope = available.filter(s => s.name === symbolName && s.className);
571
- if (needsScope.length > 0) suggestions.push(`Symbol '${symbolName}' exists inside multiple scopes. Did you mean to use className: '${needsScope[0].className}'?`);
572
- }
573
-
574
- if (closest.length > 0) {
575
- suggestions.push(`Similar symbols: ${closest.map(s => s.name).join(', ')}`);
576
- }
577
-
578
- const errorPayload = {
579
- error: `Symbol '${symbolName}' not found in ${path.basename(resolvedPath)}`,
580
- available_symbols: availableFormatted,
581
- suggestions
582
- };
583
-
584
- return {
585
- isError: true,
586
- content: [
587
- {
588
- type: "text" as const,
589
- text: JSON.stringify(errorPayload, null, 2),
590
- },
591
- ],
592
- };
593
- }
594
-
595
- return {
596
- content: [
597
- {
598
- type: "text" as const,
599
- text:
600
- `// Symbol: ${symbolName}\n` +
601
- `// File: ${resolvedPath}\n\n${extracted}`,
602
- },
603
- ],
604
- };
605
- }
606
-
607
- // ─── Tool 3: analyze_impact ─────────────────────────────────────────
608
-
609
- export async function handleAnalyzeImpact(args: Record<string, unknown>) {
610
- const filePath = args.filePath as string;
611
- let rootDir = args.rootDir as string | undefined;
612
-
613
- if (!filePath) {
614
- return errorResponse("Missing required parameter: filePath");
615
- }
616
-
617
- const resolvedPath = path.resolve(filePath);
618
-
619
- if (!fs.existsSync(resolvedPath)) {
620
- return errorResponse(`File not found: ${resolvedPath}`);
621
- }
622
-
623
- // Discover project root if not provided
624
- if (!rootDir) {
625
- rootDir = findProjectRoot(resolvedPath);
626
- }
627
-
628
- if (!rootDir || !fs.existsSync(rootDir)) {
629
- return errorResponse(
630
- `Could not determine project root for ${resolvedPath}. ` +
631
- `Provide rootDir explicitly.`,
632
- );
633
- }
634
-
635
- rootDir = path.resolve(rootDir);
636
-
637
- const ignoreManager = new IgnoreManager(rootDir);
638
- const allFiles = ignoreManager.walkDirectory();
639
-
640
- const targetRelative = path
641
- .relative(rootDir, resolvedPath)
642
- .replace(/\\/g, "/");
643
-
644
- // Import pattern regexes
645
- const importPatterns: RegExp[] = [
646
- // ES static import: import ... from "path"
647
- /import\s+(?:[\s\S]*?)\s+from\s+['"]([^'"]+)['"]/gm,
648
- // ES dynamic import: import("path")
649
- /import\s*\(\s*['"]([^'"]+)['"]\s*\)/gm,
650
- // CommonJS: require("path")
651
- /require\s*\(\s*['"]([^'"]+)['"]\s*\)/gm,
652
- // Python: from package import ...
653
- /from\s+(\S+)\s+import/gm,
654
- // Python: import package
655
- /^import\s+(\S+)/gm,
656
- // PHP: use Namespace\Class
657
- /^\s*use\s+([\w\\]+)/gm,
658
- // PHP: require_once / require / include_once / include
659
- /(?:require_once|require|include_once|include)\s*\(?\s*['"]([^'"]+)['"]\s*\)?/gm,
660
- // Dart: import 'package:...' or import '../...';
661
- /^\s*import\s+['"]([^'"]+)['"]\s*;/gm,
662
- ];
663
-
664
- const dependents: Dependent[] = [];
665
-
666
- for (const file of allFiles) {
667
- // Skip the target file itself
668
- if (path.resolve(file) === resolvedPath) continue;
669
-
670
- // Only scan importable file types
671
- const ext = path.extname(file).toLowerCase();
672
- if (!IMPORTABLE_EXTENSIONS.has(ext)) continue;
673
-
674
- let content: string;
675
- try {
676
- content = fs.readFileSync(file, "utf-8");
677
- } catch {
678
- continue;
679
- }
680
-
681
- let isDependent = false;
682
- const matchedImports: string[] = [];
683
-
684
- for (const pattern of importPatterns) {
685
- const regex = new RegExp(pattern.source, pattern.flags);
686
- let match: RegExpExecArray | null;
687
-
688
- while ((match = regex.exec(content)) !== null) {
689
- const importPath = match[1];
690
- if (
691
- resolveImportMatch(importPath, resolvedPath, file, rootDir)
692
- ) {
693
- matchedImports.push(match[0].trim());
694
- isDependent = true;
695
- }
696
- }
697
- }
698
-
699
- if (isDependent) {
700
- dependents.push({
701
- file: path.relative(rootDir, file).replace(/\\/g, "/"),
702
- imports: [...new Set(matchedImports)], // deduplicate
703
- });
704
- }
705
- }
706
-
707
- // Build the report
708
- const report = buildImpactReport(
709
- targetRelative,
710
- rootDir,
711
- dependents,
712
- );
713
-
714
- return {
715
- content: [{ type: "text" as const, text: report }],
716
- };
717
- }
718
-
719
- // ─── Tool 4: write_file_surgical ────────────────────────────────────
720
-
721
- export async function handleWriteFileSurgical(args: Record<string, unknown>) {
722
- const filePath = args.filePath as string;
723
- const symbolName = args.symbolName as string;
724
- const newContent = args.newContent as string;
725
- const className = args.className as string | undefined;
726
- const shouldBackup = (args.createBackup as boolean) || false;
727
-
728
- const confirmationToken = args.confirmationToken as string | undefined;
729
- const confirm = args.confirm as boolean | undefined;
730
-
731
- if (!filePath) return errorResponse("Missing required parameter: filePath");
732
-
733
- // PHASE 2: Apply the change
734
- if (confirmationToken && confirm) {
735
- const pending = confirmationCache.consume(confirmationToken);
736
- if (!pending || pending.operation !== "write_file_surgical") {
737
- return errorResponse("Invalid or expired confirmation token. Please run the operation again to generate a new preview.");
738
- }
739
-
740
- const resolvedPath = pending.filePath;
741
- try {
742
- createBackup(resolvedPath);
743
- } catch (error: unknown) {
744
- return errorResponse(`Failed to create backup: ${error instanceof Error ? error.message : String(error)}`);
745
- }
746
-
747
- try {
748
- fs.writeFileSync(resolvedPath, pending.payload.newContentFull, "utf-8");
749
- } catch (error: unknown) {
750
- restoreBackup(resolvedPath);
751
- return errorResponse(`Failed to write file: ${error instanceof Error ? error.message : String(error)}`);
752
- }
753
-
754
- return {
755
- content: [
756
- {
757
- type: "text" as const,
758
- text: `// ✅ Symbol "${pending.payload.symbolName}" replaced successfully\n// File: ${resolvedPath}\n\n${pending.payload.diff}`,
759
- },
760
- ],
761
- };
762
- }
763
-
764
- // PHASE 1: Dry-Run Preview
765
- if (!symbolName) return errorResponse("Missing required parameter: symbolName");
766
- if (!newContent) return errorResponse("Missing required parameter: newContent");
767
-
768
- const resolvedPath = path.resolve(filePath);
769
-
770
- if (!fs.existsSync(resolvedPath)) {
771
- return errorResponse(`File not found: ${resolvedPath}`);
772
- }
773
-
774
- const ext = path.extname(resolvedPath).toLowerCase();
775
- if (!WRITABLE_EXTENSIONS.has(ext)) {
776
- return errorResponse(
777
- `Unsupported file type "${ext}" for surgical writing. ` +
778
- `Supported: .ts, .tsx, .js, .jsx, .mts, .mjs, .cts, .cjs, .php, .phtml, .dart, .py, .pyi`
779
- );
780
- }
781
-
782
- let content: string;
783
- try {
784
- content = fs.readFileSync(resolvedPath, "utf-8");
785
- } catch (error: unknown) {
786
- return errorResponse(`Failed to read file: ${error instanceof Error ? error.message : String(error)}`);
787
- }
788
-
789
- // Perform the replacement memory-only
790
- const result: WriteResult = replaceSymbol(resolvedPath, content, symbolName, newContent, className);
791
-
792
- if (!result.success) {
793
- const isNotFoundError = result.error && (result.error.includes("not found") || result.error.includes("Could not locate"));
794
- if (isNotFoundError) {
795
- const available = extractFallbackSymbols(content);
796
- const closest = findClosestSymbols(symbolName, available, 5);
797
-
798
- const availableFormatted = available.slice(0, 15).map(s => `${s.name} (${s.type}${s.className ? ` in ${s.className}` : ''})`);
799
- if (available.length > 15) availableFormatted.push(`...and ${available.length - 15} more`);
800
-
801
- const suggestions = [];
802
- if (className) {
803
- const inOtherClass = available.find(s => s.name === symbolName && s.className !== className);
804
- if (inOtherClass) suggestions.push(`Did you mean '${symbolName}' in class '${inOtherClass.className}'? Update your className parameter.`);
805
- } else {
806
- const needsScope = available.filter(s => s.name === symbolName && s.className);
807
- if (needsScope.length > 0) suggestions.push(`Symbol '${symbolName}' exists inside multiple scopes. Did you mean to use className: '${needsScope[0].className}'?`);
808
- }
809
-
810
- if (closest.length > 0) {
811
- suggestions.push(`Similar symbols: ${closest.map(s => s.name).join(', ')}`);
812
- }
813
-
814
- return {
815
- isError: true,
816
- content: [
817
- {
818
- type: "text" as const,
819
- text: JSON.stringify({
820
- error: result.error,
821
- available_symbols: availableFormatted,
822
- suggestions
823
- }, null, 2),
824
- },
825
- ],
826
- };
827
- }
828
- return errorResponse(result.error || "Unknown error during symbol replacement");
829
- }
830
-
831
- const diff = generateDiff(content, result.newContent, resolvedPath);
832
-
833
- const token = confirmationCache.add("write_file_surgical", resolvedPath, {
834
- symbolName,
835
- newContentFull: result.newContent,
836
- diff,
837
- });
838
-
839
- return {
840
- content: [
841
- {
842
- type: "text" as const,
843
- text: `// 🔍 ACTION REQUIRED (DRY-RUN DEFAULT)\n// To apply these changes, you MUST call this tool again with:\n// confirmationToken: "${token}"\n// confirm: true\n\n${diff}`,
844
- },
845
- ],
846
- };
847
- }
848
-
849
- // ─── Tool 5: insert_symbol ──────────────────────────────────────────
850
-
851
- export async function handleInsertSymbol(args: Record<string, unknown>) {
852
- const filePath = args.filePath as string;
853
- const code = args.code as string;
854
- const anchorSymbol = (args.anchorSymbol as string) || null;
855
- const position = (args.position as InsertPosition) || "after";
856
- const className = args.className as string | undefined;
857
- const shouldBackup = (args.createBackup as boolean) || false;
858
-
859
- const confirmationToken = args.confirmationToken as string | undefined;
860
- const confirm = args.confirm as boolean | undefined;
861
-
862
- if (!filePath) return errorResponse("Missing required parameter: filePath");
863
-
864
- // PHASE 2: Apply the change
865
- if (confirmationToken && confirm) {
866
- const pending = confirmationCache.consume(confirmationToken);
867
- if (!pending || pending.operation !== "insert_symbol") {
868
- return errorResponse("Invalid or expired confirmation token. Please run the operation again to generate a new preview.");
869
- }
870
-
871
- const resolvedPath = pending.filePath;
872
- try {
873
- createBackup(resolvedPath);
874
- } catch (error: unknown) {
875
- return errorResponse(`Failed to create backup: ${error instanceof Error ? error.message : String(error)}`);
876
- }
877
-
878
- try {
879
- fs.writeFileSync(resolvedPath, pending.payload.newContentFull, "utf-8");
880
- } catch (error: unknown) {
881
- restoreBackup(resolvedPath);
882
- return errorResponse(`Failed to write file: ${error instanceof Error ? error.message : String(error)}`);
883
- }
884
-
885
- return {
886
- content: [
887
- {
888
- type: "text" as const,
889
- text: `// ✅ Code inserted successfully\n// File: ${resolvedPath}\n// Anchor: ${pending.payload.anchorSymbol || "(end of file)"}\n// Position: ${pending.payload.position}\n\n${pending.payload.diff}`,
890
- },
891
- ],
892
- };
893
- }
894
-
895
- // PHASE 1: Dry-Run
896
- if (!code) return errorResponse("Missing required parameter: code");
897
-
898
- const resolvedPath = path.resolve(filePath);
899
-
900
- if (!fs.existsSync(resolvedPath)) {
901
- return errorResponse(`File not found: ${resolvedPath}`);
902
- }
903
-
904
- const ext = path.extname(resolvedPath).toLowerCase();
905
- if (!WRITABLE_EXTENSIONS.has(ext)) {
906
- return errorResponse(`Unsupported file type "${ext}" for code insertion.`);
907
- }
908
-
909
- let fileContent: string;
910
- try {
911
- fileContent = fs.readFileSync(resolvedPath, "utf-8");
912
- } catch (error: unknown) {
913
- return errorResponse(`Failed to read file: ${error instanceof Error ? error.message : String(error)}`);
914
- }
915
-
916
- const result: WriteResult = insertCode(resolvedPath, fileContent, code, anchorSymbol, position, className);
917
-
918
- if (!result.success) {
919
- return errorResponse(result.error || "Unknown error during code insertion");
920
- }
921
-
922
- const diff = generateDiff(fileContent, result.newContent, resolvedPath);
923
-
924
- const token = confirmationCache.add("insert_symbol", resolvedPath, {
925
- newContentFull: result.newContent,
926
- diff,
927
- anchorSymbol,
928
- position
929
- });
930
-
931
- return {
932
- content: [
933
- {
934
- type: "text" as const,
935
- text: `// 🔍 ACTION REQUIRED (DRY-RUN DEFAULT)\n// To apply these changes, you MUST call this tool again with:\n// confirmationToken: "${token}"\n// confirm: true\n\n${diff}`,
936
- },
937
- ],
938
- };
939
- }
940
-
941
- // ─── Tool 6: rename_symbol ──────────────────────────────────────────
942
-
943
- export async function handleRenameSymbol(args: Record<string, unknown>) {
944
- const filePath = args.filePath as string;
945
- const oldName = args.oldName as string;
946
- const newName = args.newName as string;
947
- const rootDir = args.rootDir as string | undefined;
948
- const shouldBackup = (args.createBackup as boolean) || false;
949
-
950
- const confirmationToken = args.confirmationToken as string | undefined;
951
- const confirm = args.confirm as boolean | undefined;
952
-
953
- if (!filePath) return errorResponse("Missing required parameter: filePath");
954
-
955
- // PHASE 2
956
- if (confirmationToken && confirm) {
957
- const pending = confirmationCache.consume(confirmationToken);
958
- if (!pending || pending.operation !== "rename_symbol") {
959
- return errorResponse("Invalid or expired confirmation token.");
960
- }
961
-
962
- const results = pending.payload.results;
963
- for (const res of results) {
964
- try { createBackup(res.filePath); } catch (e) {}
965
- }
966
-
967
- try {
968
- for (const res of results) {
969
- fs.writeFileSync(res.filePath, res.newContent, "utf-8");
970
- }
971
- } catch (error: unknown) {
972
- return errorResponse(`Failed to write files during rename: ${error instanceof Error ? error.message : String(error)}`);
973
- }
974
-
975
- return {
976
- content: [{
977
- type: "text" as const,
978
- text: `// ✅ Rename applied successfully.\n\n${pending.payload.diff}`,
979
- }],
980
- };
981
- }
982
-
983
- // PHASE 1
984
- if (!oldName) return errorResponse("Missing required parameter: oldName");
985
- if (!newName) return errorResponse("Missing required parameter: newName");
986
-
987
- const resolvedPath = path.resolve(filePath);
988
- if (!fs.existsSync(resolvedPath)) {
989
- return errorResponse(`File not found: ${resolvedPath}`);
990
- }
991
-
992
- let sourceContent: string;
993
- try {
994
- sourceContent = fs.readFileSync(resolvedPath, "utf-8");
995
- } catch (error: unknown) {
996
- return errorResponse(`Failed to read file: ${error instanceof Error ? error.message : String(error)}`);
997
- }
998
-
999
- // 1. Rename in the source file
1000
- const sourceResult = renameInFile(resolvedPath, sourceContent, oldName, newName);
1001
- if (!sourceResult.success) {
1002
- return errorResponse(sourceResult.error || `Could not find definition for "${oldName}" in ${path.basename(resolvedPath)}.`);
1003
- }
1004
-
1005
- const results: { filePath: string; oldContent: string; newContent: string }[] = [
1006
- {
1007
- filePath: resolvedPath,
1008
- oldContent: sourceContent,
1009
- newContent: sourceResult.newContent,
1010
- },
1011
- ];
1012
-
1013
- // 2. Discover and rename in dependent files
1014
- const projectRoot = rootDir ? path.resolve(rootDir) : findProjectRoot(resolvedPath);
1015
- if (projectRoot) {
1016
- const ignoreManager = new IgnoreManager(projectRoot);
1017
- const allFiles = ignoreManager.walkDirectory();
1018
-
1019
- for (const dependentFile of allFiles) {
1020
- if (path.resolve(dependentFile) === resolvedPath) continue;
1021
-
1022
- const ext = path.extname(dependentFile).toLowerCase();
1023
- if (!IMPORTABLE_EXTENSIONS.has(ext)) continue;
1024
-
1025
- let depContent: string;
1026
- try {
1027
- depContent = fs.readFileSync(dependentFile, "utf-8");
1028
- } catch {
1029
- continue;
1030
- }
1031
-
1032
- // Quick check if file contains oldName before attempting heavy rename
1033
- const escaped = oldName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1034
- const regex = new RegExp(`(?<=^|[^a-zA-Z0-9_$])(${escaped})(?=[^a-zA-Z0-9_$]|$)`);
1035
- if (!regex.test(depContent)) continue;
1036
-
1037
- const depResult = renameReferencesInFile(dependentFile, depContent, oldName, newName);
1038
- if (depResult.success && depResult.newContent !== depContent) {
1039
- results.push({
1040
- filePath: path.resolve(dependentFile),
1041
- oldContent: depContent,
1042
- newContent: depResult.newContent,
1043
- });
1044
- }
1045
- }
1046
- }
1047
-
1048
- const multiDiff = generateMultiFileDiff(results);
1049
-
1050
- const token = confirmationCache.add("rename_symbol", resolvedPath, {
1051
- results,
1052
- diff: multiDiff
1053
- });
1054
-
1055
- return {
1056
- content: [{
1057
- type: "text" as const,
1058
- text: `// 🔍 ACTION REQUIRED (DRY-RUN DEFAULT)\n// To apply these changes, you MUST call this tool again with:\n// confirmationToken: "${token}"\n// confirm: true\n\n${multiDiff}`,
1059
- }],
1060
- };
1061
- }
1062
-
1063
- // ─── Tool 7: remove_symbol ──────────────────────────────────────────
1064
-
1065
- export async function handleRemoveSymbol(args: Record<string, unknown>) {
1066
- const filePath = args.filePath as string;
1067
- const symbolName = args.symbolName as string;
1068
- const className = args.className as string | undefined;
1069
- const force = (args.force as boolean) || false;
1070
- const shouldBackup = (args.createBackup as boolean) || false;
1071
-
1072
- const confirmationToken = args.confirmationToken as string | undefined;
1073
- const confirm = args.confirm as boolean | undefined;
1074
-
1075
- if (!filePath) return errorResponse("Missing required parameter: filePath");
1076
-
1077
- // PHASE 2
1078
- if (confirmationToken && confirm) {
1079
- const pending = confirmationCache.consume(confirmationToken);
1080
- if (!pending || pending.operation !== "remove_symbol") {
1081
- return errorResponse("Invalid or expired confirmation token.");
1082
- }
1083
-
1084
- const resolvedPath = pending.filePath;
1085
- try { createBackup(resolvedPath); } catch (e) {}
1086
-
1087
- try {
1088
- fs.writeFileSync(resolvedPath, pending.payload.newContentFull, "utf-8");
1089
- } catch (error: unknown) {
1090
- restoreBackup(resolvedPath);
1091
- return errorResponse(`Failed to write file: ${error instanceof Error ? error.message : String(error)}`);
1092
- }
1093
-
1094
- return {
1095
- content: [{
1096
- type: "text" as const,
1097
- text: `// ✅ Symbol "${pending.payload.symbolName}" removed successfully.\n\n${pending.payload.diff}`,
1098
- }],
1099
- };
1100
- }
1101
-
1102
- if (!symbolName) return errorResponse("Missing required parameter: symbolName");
1103
-
1104
- const resolvedPath = path.resolve(filePath);
1105
- if (!fs.existsSync(resolvedPath)) {
1106
- return errorResponse(`File not found: ${resolvedPath}`);
1107
- }
1108
-
1109
- let fileContent: string;
1110
- try {
1111
- fileContent = fs.readFileSync(resolvedPath, "utf-8");
1112
- } catch (error: unknown) {
1113
- return errorResponse(`Failed to read file: ${error instanceof Error ? error.message : String(error)}`);
1114
- }
1115
-
1116
- // Safety check: Don't remove if dependents exist unless forced
1117
- if (!force) {
1118
- const projectRoot = findProjectRoot(resolvedPath);
1119
- if (projectRoot) {
1120
- const ignoreManager = new IgnoreManager(projectRoot);
1121
- const allFiles = ignoreManager.walkDirectory();
1122
- const targetRel = path.relative(projectRoot, resolvedPath).replace(/\\/g, "/");
1123
-
1124
- for (const f of allFiles) {
1125
- if (path.resolve(f) === resolvedPath) continue;
1126
- const fExt = path.extname(f).toLowerCase();
1127
- if (!IMPORTABLE_EXTENSIONS.has(fExt)) continue;
1128
-
1129
- try {
1130
- const fContent = fs.readFileSync(f, "utf-8");
1131
- const escaped = symbolName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1132
- const regex = new RegExp(`(?<=^|[^a-zA-Z0-9_$])(${escaped})(?=[^a-zA-Z0-9_$]|$)`);
1133
-
1134
- if (regex.test(fContent)) {
1135
- return errorResponse(`Symbol "${symbolName}" might be used in ${path.relative(projectRoot, f)}. Use force: true to delete anyway.`);
1136
- }
1137
- } catch {}
1138
- }
1139
- }
1140
- }
1141
-
1142
- const result = removeSymbolFromFile(resolvedPath, fileContent, symbolName, className);
1143
- if (!result.success) {
1144
- return errorResponse(result.error || "Unknown error during symbol removal");
1145
- }
1146
-
1147
- const diff = generateDiff(fileContent, result.newContent, resolvedPath);
1148
-
1149
- const token = confirmationCache.add("remove_symbol", resolvedPath, {
1150
- symbolName,
1151
- newContentFull: result.newContent,
1152
- diff
1153
- });
1154
-
1155
- return {
1156
- content: [{
1157
- type: "text" as const,
1158
- text: `// 🔍 ACTION REQUIRED (DRY-RUN DEFAULT)\n// To apply these changes, you MUST call this tool again with:\n// confirmationToken: "${token}"\n// confirm: true\n\n${diff}`,
1159
- }],
1160
- };
1161
- }
1162
-
1163
- // ─── Import Resolution Logic ────────────────────────────────────────
1164
-
1165
- function resolveImportMatch(
1166
- importPath: string,
1167
- targetFile: string,
1168
- sourceFile: string,
1169
- rootDir: string,
1170
- ): boolean {
1171
- const normalized = importPath.replace(/\\/g, "/");
1172
- const targetResolved = path.resolve(targetFile);
1173
- const targetWithoutExt = targetResolved.replace(/\.[^.]+$/, "");
1174
- const targetBaseName = path.basename(
1175
- targetFile,
1176
- path.extname(targetFile),
1177
- );
1178
-
1179
- // Relative imports (./foo, ../bar)
1180
- if (normalized.startsWith(".")) {
1181
- const sourceDir = path.dirname(sourceFile);
1182
- const resolved = path.resolve(sourceDir, normalized);
1183
-
1184
- // Try exact match, then with common extensions, then /index variants
1185
- const candidates = [
1186
- resolved,
1187
- resolved + ".ts",
1188
- resolved + ".tsx",
1189
- resolved + ".js",
1190
- resolved + ".jsx",
1191
- resolved + ".mts",
1192
- resolved + ".mjs",
1193
- resolved + ".dart",
1194
- path.join(resolved, "index.ts"),
1195
- path.join(resolved, "index.tsx"),
1196
- path.join(resolved, "index.js"),
1197
- path.join(resolved, "index.mjs"),
1198
- ];
1199
-
1200
- for (const candidate of candidates) {
1201
- if (
1202
- path.resolve(candidate) === targetResolved ||
1203
- path.resolve(candidate) === targetWithoutExt
1204
- ) {
1205
- return true;
1206
- }
1207
- }
1208
- return false;
1209
- }
1210
-
1211
- // Non-relative imports (aliases, packages)
1212
- // Check if the import path ends with the target's relative path or basename
1213
- const targetRelative = path
1214
- .relative(rootDir, targetFile)
1215
- .replace(/\\/g, "/")
1216
- .replace(/\.[^.]+$/, ""); // strip extension
1217
-
1218
- if (
1219
- normalized === targetBaseName ||
1220
- normalized.endsWith("/" + targetBaseName) ||
1221
- normalized === targetRelative ||
1222
- normalized.endsWith(targetRelative)
1223
- ) {
1224
- return true;
1225
- }
1226
-
1227
- // Python-style dotted imports: convert dots to path separators
1228
- const dottedPath = normalized.replace(/\./g, "/");
1229
- if (
1230
- dottedPath === targetBaseName ||
1231
- dottedPath.endsWith("/" + targetBaseName) ||
1232
- dottedPath === targetRelative ||
1233
- dottedPath.endsWith(targetRelative)
1234
- ) {
1235
- return true;
1236
- }
1237
-
1238
- return false;
1239
- }
1240
-
1241
- // ─── Project Root Discovery ─────────────────────────────────────────
1242
-
1243
- function findProjectRoot(filePath: string): string | undefined {
1244
- const ROOT_MARKERS = [
1245
- "package.json",
1246
- ".git",
1247
- "pyproject.toml",
1248
- "setup.py",
1249
- "Cargo.toml",
1250
- "go.mod",
1251
- "pom.xml",
1252
- "build.gradle",
1253
- "CMakeLists.txt",
1254
- ".gitignore",
1255
- "Gemfile",
1256
- "composer.json",
1257
- "pubspec.yaml",
1258
- ];
1259
-
1260
- let current = path.dirname(path.resolve(filePath));
1261
- const root = path.parse(current).root;
1262
-
1263
- while (current !== root) {
1264
- for (const marker of ROOT_MARKERS) {
1265
- if (fs.existsSync(path.join(current, marker))) {
1266
- return current;
1267
- }
1268
- }
1269
- current = path.dirname(current);
1270
- }
1271
-
1272
- return undefined;
1273
- }
1274
-
1275
- // ─── Output Formatting ─────────────────────────────────────────────
1276
-
1277
- interface FileEntry {
1278
- relativePath: string;
1279
- language: string;
1280
- compressed: string;
1281
- }
1282
-
1283
- interface Dependent {
1284
- file: string;
1285
- imports: string[];
1286
- }
1287
-
1288
- function formatAsXml(
1289
- projectName: string,
1290
- projectPath: string,
1291
- entries: FileEntry[],
1292
- skippedCount: number,
1293
- ): string {
1294
- const lines: string[] = [
1295
- `<?xml version="1.0" encoding="UTF-8"?>`,
1296
- `<repository name="${esc(projectName)}" path="${esc(projectPath)}" files="${entries.length}" skipped="${skippedCount}">`,
1297
- ``,
1298
- ` <file_tree>`,
1299
- ];
1300
-
1301
- for (const entry of entries) {
1302
- lines.push(
1303
- ` <file path="${esc(entry.relativePath)}" language="${esc(entry.language)}" />`,
1304
- );
1305
- }
1306
-
1307
- lines.push(` </file_tree>`);
1308
- lines.push(``);
1309
-
1310
- for (const entry of entries) {
1311
- lines.push(
1312
- ` <file path="${esc(entry.relativePath)}" language="${esc(entry.language)}">`,
1313
- );
1314
- lines.push(`<compressed>`);
1315
- lines.push(entry.compressed);
1316
- lines.push(`</compressed>`);
1317
- lines.push(` </file>`);
1318
- lines.push(``);
1319
- }
1320
-
1321
- lines.push(`</repository>`);
1322
- return lines.join("\n");
1323
- }
1324
-
1325
- function formatAsMarkdown(
1326
- projectName: string,
1327
- projectPath: string,
1328
- entries: FileEntry[],
1329
- skippedCount: number,
1330
- ): string {
1331
- const lines: string[] = [
1332
- `# Repository Map: ${projectName}`,
1333
- ``,
1334
- `> **Path:** \`${projectPath}\` `,
1335
- `> **Source files:** ${entries.length} | **Skipped:** ${skippedCount}`,
1336
- ``,
1337
- `## File Tree`,
1338
- ``,
1339
- ];
1340
-
1341
- for (const entry of entries) {
1342
- lines.push(`- \`${entry.relativePath}\` *(${entry.language})*`);
1343
- }
1344
-
1345
- lines.push(``);
1346
- lines.push(`---`);
1347
- lines.push(``);
1348
-
1349
- for (const entry of entries) {
1350
- const langId = getLangId(entry.language);
1351
- lines.push(`### ${entry.relativePath}`);
1352
- lines.push("```" + langId);
1353
- lines.push(entry.compressed);
1354
- lines.push("```");
1355
- lines.push(``);
1356
- }
1357
-
1358
- return lines.join("\n");
1359
- }
1360
-
1361
- function buildImpactReport(
1362
- targetRelative: string,
1363
- rootDir: string,
1364
- dependents: Dependent[],
1365
- ): string {
1366
- const lines: string[] = [
1367
- `# Impact Analysis`,
1368
- ``,
1369
- `## Target`,
1370
- `- **File:** \`${targetRelative}\``,
1371
- `- **Project root:** \`${rootDir}\``,
1372
- `- **Dependent files:** ${dependents.length}`,
1373
- ``,
1374
- ];
1375
-
1376
- if (dependents.length === 0) {
1377
- lines.push(
1378
- `> No files in this repository import or depend on the target file.`,
1379
- );
1380
- lines.push(``);
1381
- lines.push(
1382
- `This could mean the file is a leaf module, an entry point, ` +
1383
- `or uses non-standard import patterns not detected by this analysis.`,
1384
- );
1385
- } else {
1386
- lines.push(`## Dependent Files`);
1387
- lines.push(``);
1388
-
1389
- for (const dep of dependents) {
1390
- lines.push(`### \`${dep.file}\``);
1391
- for (const imp of dep.imports) {
1392
- lines.push(`- \`${imp}\``);
1393
- }
1394
- lines.push(``);
1395
- }
1396
-
1397
- lines.push(`---`);
1398
- lines.push(``);
1399
- lines.push(
1400
- `> **⚠️ Blast radius:** Modifying \`${targetRelative}\` may affect ` +
1401
- `**${dependents.length}** file(s). Review the import statements above ` +
1402
- `to understand what each dependent file consumes from the target.`,
1403
- );
1404
- }
1405
-
1406
- return lines.join("\n");
1407
- }
1408
-
1409
- // ─── Utility ────────────────────────────────────────────────────────
1410
-
1411
- function getLanguageName(ext: string): string {
1412
- const map: Record<string, string> = {
1413
- ".ts": "TypeScript",
1414
- ".tsx": "TypeScript JSX",
1415
- ".mts": "TypeScript",
1416
- ".cts": "TypeScript",
1417
- ".js": "JavaScript",
1418
- ".jsx": "JavaScript JSX",
1419
- ".mjs": "JavaScript",
1420
- ".cjs": "JavaScript",
1421
- ".py": "Python",
1422
- ".pyi": "Python Stub",
1423
- ".json": "JSON",
1424
- ".yaml": "YAML",
1425
- ".yml": "YAML",
1426
- ".toml": "TOML",
1427
- ".md": "Markdown",
1428
- ".txt": "Text",
1429
- ".css": "CSS",
1430
- ".scss": "SCSS",
1431
- ".less": "LESS",
1432
- ".html": "HTML",
1433
- ".vue": "Vue",
1434
- ".svelte": "Svelte",
1435
- ".rs": "Rust",
1436
- ".go": "Go",
1437
- ".java": "Java",
1438
- ".kt": "Kotlin",
1439
- ".c": "C",
1440
- ".cpp": "C++",
1441
- ".h": "C Header",
1442
- ".hpp": "C++ Header",
1443
- ".rb": "Ruby",
1444
- ".php": "PHP",
1445
- ".dart": "Dart",
1446
- ".swift": "Swift",
1447
- ".sh": "Shell",
1448
- ".bash": "Bash",
1449
- ".zsh": "Zsh",
1450
- ".sql": "SQL",
1451
- ".graphql": "GraphQL",
1452
- ".gql": "GraphQL",
1453
- ".proto": "Protocol Buffers",
1454
- ".dockerfile": "Dockerfile",
1455
- };
1456
- return map[ext] || ext.substring(1).toUpperCase();
1457
- }
1458
-
1459
- function getLangId(language: string): string {
1460
- const map: Record<string, string> = {
1461
- TypeScript: "typescript",
1462
- "TypeScript JSX": "tsx",
1463
- JavaScript: "javascript",
1464
- "JavaScript JSX": "jsx",
1465
- Python: "python",
1466
- "Python Stub": "python",
1467
- JSON: "json",
1468
- YAML: "yaml",
1469
- TOML: "toml",
1470
- Markdown: "markdown",
1471
- CSS: "css",
1472
- SCSS: "scss",
1473
- LESS: "less",
1474
- HTML: "html",
1475
- Vue: "vue",
1476
- Svelte: "svelte",
1477
- Rust: "rust",
1478
- Go: "go",
1479
- Java: "java",
1480
- Kotlin: "kotlin",
1481
- C: "c",
1482
- "C++": "cpp",
1483
- Ruby: "ruby",
1484
- PHP: "php",
1485
- Dart: "dart",
1486
- Swift: "swift",
1487
- Shell: "bash",
1488
- SQL: "sql",
1489
- GraphQL: "graphql",
1490
- };
1491
- return map[language] || language.toLowerCase();
1492
- }
1493
-
1494
- function esc(str: string): string {
1495
- return str
1496
- .replace(/&/g, "&amp;")
1497
- .replace(/</g, "&lt;")
1498
- .replace(/>/g, "&gt;")
1499
- .replace(/"/g, "&quot;")
1500
- .replace(/'/g, "&apos;");
1501
- }
1502
-
1503
- export async function handleRollbackFile(args: Record<string, unknown>) {
1504
- const filePath = args.filePath as string;
1505
- const steps = (args.steps as number) || 1;
1506
-
1507
- if (!filePath) return errorResponse("Missing required parameter: filePath");
1508
-
1509
- const resolvedPath = path.resolve(filePath);
1510
-
1511
- if (steps < 1 || steps > 5) {
1512
- return errorResponse("Steps must be between 1 and 5.");
1513
- }
1514
-
1515
- const success = restoreBackup(resolvedPath, steps);
1516
-
1517
- if (!success) {
1518
- return errorResponse(`No backup found for step ${steps} at ${resolvedPath}`);
1519
- }
1520
-
1521
- return {
1522
- content: [{
1523
- type: "text" as const,
1524
- text: `// ⏪ Rollback successful!\n// Reverted ${path.basename(resolvedPath)} to state from ${steps} step(s) ago.\n// File: ${resolvedPath}`,
1525
- }],
1526
- };
1527
- }
1528
-
1529
- function errorResponse(message: string) {
1530
- return {
1531
- content: [{ type: "text" as const, text: `❌ ${message}` }],
1532
- isError: true,
1533
- };
1534
- }
1535
-
1536
- // ─── Bootstrap ──────────────────────────────────────────────────────
1537
-
1538
- async function main(): Promise<void> {
1539
- const transport = new StdioServerTransport();
1540
- await server.connect(transport);
1541
- console.error(
1542
- `🚀 ${SERVER_NAME} v${SERVER_VERSION} running on stdio transport`,
1543
- );
1544
- }
1545
-
1546
- import { fileURLToPath, pathToFileURL } from "node:url";
1547
-
1548
- if (import.meta.url === pathToFileURL(process.argv[1]).href) {
1549
- main().catch((error) => {
1550
- console.error("Fatal error starting MCP server:", error);
1551
- process.exit(1);
1552
- });
1553
- }