@nexiq/cli 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.ts ADDED
@@ -0,0 +1,1710 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import {
4
+ CallToolRequestSchema,
5
+ ListToolsRequestSchema,
6
+ } from "@modelcontextprotocol/sdk/types.js";
7
+ import {
8
+ ProjectManager,
9
+ SymbolInfo,
10
+ type SymbolSearchResult,
11
+ } from "./projectManager.js";
12
+ import {
13
+ getDisplayName,
14
+ type BackendRequestMap,
15
+ type BackendMessageType,
16
+ } from "@nexiq/shared";
17
+ import { WebSocketServer, WebSocket } from "ws";
18
+ import { minimatch } from "minimatch";
19
+ import path from "node:path";
20
+
21
+ export interface OpenProjectArgs {
22
+ projectPath: string;
23
+ subProject?: string;
24
+ }
25
+
26
+ export interface GetSymbolInfoArgs {
27
+ projectPath: string;
28
+ subProject?: string;
29
+ query: string;
30
+ strict?: boolean;
31
+ props?: boolean;
32
+ usages?: boolean;
33
+ loc?: boolean;
34
+ exclude?: string[];
35
+ fields?: string[];
36
+ }
37
+
38
+ export interface GetSymbolUsagesWithContextArgs {
39
+ projectPath: string;
40
+ subProject?: string;
41
+ query: string;
42
+ strict?: boolean;
43
+ contextLines?: number;
44
+ exclude?: string[];
45
+ fields?: string[];
46
+ }
47
+
48
+ export interface FindFilesArgs {
49
+ projectPath: string;
50
+ subProject?: string;
51
+ pattern: string;
52
+ fields?: string[];
53
+ }
54
+
55
+ export interface GetFileImportsArgs {
56
+ projectPath: string;
57
+ subProject?: string;
58
+ filePath: string;
59
+ fields?: string[];
60
+ }
61
+
62
+ export interface GetProjectTreeArgs {
63
+ projectPath: string;
64
+ subProject?: string;
65
+ maxDepth?: number;
66
+ fields?: string[];
67
+ }
68
+
69
+ export interface GetComponentHierarchyArgs {
70
+ projectPath: string;
71
+ subProject?: string;
72
+ componentName: string;
73
+ depth?: number;
74
+ fields?: string[];
75
+ }
76
+
77
+ export interface GetSymbolLocationArgs {
78
+ projectPath: string;
79
+ subProject?: string;
80
+ query: string;
81
+ fields?: string[];
82
+ }
83
+
84
+ export interface GetSymbolContentArgs {
85
+ projectPath: string;
86
+ subProject?: string;
87
+ query: string;
88
+ fields?: string[];
89
+ }
90
+
91
+ export interface AddLabelArgs {
92
+ projectPath: string;
93
+ subProject?: string;
94
+ id: string;
95
+ label: string;
96
+ }
97
+
98
+ export interface ListLabelsArgs {
99
+ projectPath: string;
100
+ subProject?: string;
101
+ }
102
+
103
+ export interface SearchByLabelArgs {
104
+ projectPath: string;
105
+ subProject?: string;
106
+ label: string;
107
+ }
108
+
109
+ export interface ListDirectoryArgs {
110
+ projectPath: string;
111
+ subProject?: string;
112
+ dirPath: string;
113
+ }
114
+
115
+ export interface GetFileOutlineArgs {
116
+ projectPath: string;
117
+ subProject?: string;
118
+ filePath: string;
119
+ fields?: string[];
120
+ }
121
+
122
+ export interface ReadFileArgs {
123
+ projectPath: string;
124
+ subProject?: string;
125
+ filePath: string;
126
+ }
127
+
128
+ export interface GrepSearchArgs {
129
+ projectPath: string;
130
+ subProject?: string;
131
+ pattern: string;
132
+ exclude?: string[];
133
+ }
134
+
135
+ export interface RunShellCommandArgs {
136
+ projectPath: string;
137
+ subProject?: string;
138
+ command: string;
139
+ }
140
+
141
+ export interface ListFilesArgs {
142
+ projectPath: string;
143
+ subProject?: string;
144
+ fields?: string[];
145
+ exclude?: string[];
146
+ }
147
+
148
+ export interface GetPropDefinitionsArgs {
149
+ projectPath: string;
150
+ subProject?: string;
151
+ componentName: string;
152
+ fields?: string[];
153
+ }
154
+
155
+ export interface WriteFileArgs {
156
+ projectPath: string;
157
+ subProject?: string;
158
+ filePath: string;
159
+ content: string;
160
+ }
161
+
162
+ export interface ReplaceFileContentArgs {
163
+ projectPath: string;
164
+ subProject?: string;
165
+ filePath: string;
166
+ oldString: string;
167
+ newString: string;
168
+ }
169
+
170
+ export interface MultiReplaceFileContentArgs {
171
+ projectPath: string;
172
+ subProject?: string;
173
+ filePath: string;
174
+ replacements: { oldString: string; newString: string }[];
175
+ }
176
+
177
+ export interface ToolArgsMap {
178
+ open_project: OpenProjectArgs;
179
+ get_symbol_info: GetSymbolInfoArgs;
180
+ get_symbol_usages_with_context: GetSymbolUsagesWithContextArgs;
181
+ get_prop_definitions: GetPropDefinitionsArgs;
182
+ find_files: FindFilesArgs;
183
+ get_file_imports: GetFileImportsArgs;
184
+ get_project_tree: GetProjectTreeArgs;
185
+ list_files: ListFilesArgs;
186
+ get_component_hierarchy: GetComponentHierarchyArgs;
187
+ get_symbol_location: GetSymbolLocationArgs;
188
+ get_symbol_content: GetSymbolContentArgs;
189
+ add_label: AddLabelArgs;
190
+ list_labels: ListLabelsArgs;
191
+ search_by_label: SearchByLabelArgs;
192
+ list_directory: ListDirectoryArgs;
193
+ get_file_outline: GetFileOutlineArgs;
194
+ read_file: ReadFileArgs;
195
+ grep_search: GrepSearchArgs;
196
+ run_shell_command: RunShellCommandArgs;
197
+ write_file: WriteFileArgs;
198
+ replace_file_content: ReplaceFileContentArgs;
199
+ multi_replace_file_content: MultiReplaceFileContentArgs;
200
+ }
201
+
202
+ type KnownToolCall = {
203
+ [K in keyof ToolArgsMap]: {
204
+ name: K;
205
+ args: ToolArgsMap[K];
206
+ };
207
+ }[keyof ToolArgsMap];
208
+
209
+ type UnknownToolCall = {
210
+ name: Exclude<string, keyof ToolArgsMap>;
211
+ args: Record<string, unknown>;
212
+ };
213
+
214
+ type ToolCall = KnownToolCall | UnknownToolCall;
215
+
216
+ export type SymbolInfoResult =
217
+ | {
218
+ type: "definition";
219
+ kind: string;
220
+ name: string;
221
+ file: string;
222
+ loc: { line: number; column: number };
223
+ props?: unknown[];
224
+ in?: string;
225
+ }
226
+ | {
227
+ type: "usage";
228
+ kind: string;
229
+ name: string;
230
+ in: string;
231
+ file: string;
232
+ loc: { line: number; column: number };
233
+ };
234
+
235
+ type WsMessage = {
236
+ [K in BackendMessageType]: {
237
+ type: K;
238
+ payload: BackendRequestMap[K]["payload"];
239
+ requestId?: string;
240
+ };
241
+ }[BackendMessageType];
242
+
243
+ const DEFAULT_EXCLUDES = [
244
+ "**/node_modules/**",
245
+ "**/dist/**",
246
+ "**/build/**",
247
+ "**/test/**",
248
+ "**/__tests__/**",
249
+ "**/*.test.*",
250
+ "**/__snapshots__/**",
251
+ "**/.react-map/**",
252
+ ];
253
+
254
+ export class BackendServer {
255
+ private mcpServer: Server;
256
+ private wss: WebSocketServer | null = null;
257
+ private uiConnections = 0;
258
+ private mcpConnected = false;
259
+ private exitTimeout: NodeJS.Timeout | null = null;
260
+
261
+ constructor(
262
+ private projectManager: ProjectManager,
263
+ private port: number = 3030,
264
+ ) {
265
+ this.mcpServer = new Server(
266
+ {
267
+ name: "react-map-mcp",
268
+ version: "0.2.0",
269
+ },
270
+ {
271
+ capabilities: {
272
+ tools: {},
273
+ },
274
+ },
275
+ );
276
+
277
+ this.setupMcpHandlers();
278
+ }
279
+
280
+ private setupMcpHandlers() {
281
+ this.mcpServer.setRequestHandler(ListToolsRequestSchema, async () => {
282
+ const baseTools = [
283
+ {
284
+ name: "open_project",
285
+ description:
286
+ "Open a project and start analysis. Returns project status.",
287
+ inputSchema: {
288
+ type: "object",
289
+ properties: {
290
+ projectPath: {
291
+ type: "string",
292
+ description: "Absolute path to the project root",
293
+ },
294
+ subProject: {
295
+ type: "string",
296
+ description: "Optional sub-project path for monorepos",
297
+ },
298
+ },
299
+ required: ["projectPath"],
300
+ },
301
+ },
302
+ {
303
+ name: "get_symbol_info",
304
+ description:
305
+ "Get detailed information about a symbol (component or hook), including its definition and all usages/call sites across the project.",
306
+ inputSchema: {
307
+ type: "object",
308
+ properties: {
309
+ projectPath: {
310
+ type: "string",
311
+ description: "Absolute path to the project root",
312
+ },
313
+ subProject: {
314
+ type: "string",
315
+ description: "Optional sub-project path",
316
+ },
317
+ query: {
318
+ type: "string",
319
+ description: "The name of the component or hook to find",
320
+ },
321
+ strict: {
322
+ type: "boolean",
323
+ description:
324
+ "If true, only return symbols that exactly match the query. Defaults to true.",
325
+ },
326
+ props: {
327
+ type: "boolean",
328
+ description:
329
+ "If true, include props in the definition. Defaults to false.",
330
+ },
331
+ usages: {
332
+ type: "boolean",
333
+ description:
334
+ "If true, include usages across the project. Defaults to false.",
335
+ },
336
+ loc: {
337
+ type: "boolean",
338
+ description:
339
+ "If true, include location information (line, column). Defaults to false.",
340
+ },
341
+ exclude: {
342
+ type: "array",
343
+ items: { type: "string" },
344
+ description:
345
+ "List of glob patterns to exclude from results (e.g. ['**/test/**', '**/*.test.tsx']).",
346
+ },
347
+ fields: {
348
+ type: "array",
349
+ items: { type: "string" },
350
+ description:
351
+ "Optional list of fields to return (e.g., ['definitions']). Omit to return all fields.",
352
+ },
353
+ },
354
+ required: ["projectPath", "query"],
355
+ },
356
+ },
357
+ {
358
+ name: "get_symbol_usages_with_context",
359
+ description:
360
+ "Find all usages of a symbol and return them with a few lines of surrounding code context. Highly token-efficient for understanding how a symbol is used.",
361
+ inputSchema: {
362
+ type: "object",
363
+ properties: {
364
+ projectPath: {
365
+ type: "string",
366
+ description: "Absolute path to the project root",
367
+ },
368
+ subProject: {
369
+ type: "string",
370
+ description: "Optional sub-project path",
371
+ },
372
+ query: {
373
+ type: "string",
374
+ description: "The name of the component or hook to find",
375
+ },
376
+ strict: {
377
+ type: "boolean",
378
+ description:
379
+ "If true, only return symbols that exactly match the query. Defaults to true.",
380
+ },
381
+ contextLines: {
382
+ type: "number",
383
+ description:
384
+ "Number of context lines to show around the match. Defaults to 2.",
385
+ },
386
+ exclude: {
387
+ type: "array",
388
+ items: { type: "string" },
389
+ description:
390
+ "List of glob patterns to exclude from results (e.g. ['**/test/**', '**/*.test.tsx']).",
391
+ },
392
+ fields: {
393
+ type: "array",
394
+ items: { type: "string" },
395
+ description:
396
+ "Optional list of fields to return. Omit to return all fields.",
397
+ },
398
+ },
399
+ required: ["projectPath", "query"],
400
+ },
401
+ },
402
+ {
403
+ name: "get_prop_definitions",
404
+ description:
405
+ "Get the prop definitions for a component. Returns a clean summary of props (name, type, required, documentation).",
406
+ inputSchema: {
407
+ type: "object",
408
+ properties: {
409
+ projectPath: {
410
+ type: "string",
411
+ description: "Absolute path to the project root",
412
+ },
413
+ subProject: {
414
+ type: "string",
415
+ description: "Optional sub-project path",
416
+ },
417
+ componentName: {
418
+ type: "string",
419
+ description: "The name of the component",
420
+ },
421
+ fields: {
422
+ type: "array",
423
+ items: { type: "string" },
424
+ description:
425
+ "Optional list of fields to return. Omit to return all fields.",
426
+ },
427
+ },
428
+ required: ["projectPath", "componentName"],
429
+ },
430
+ },
431
+ {
432
+ name: "find_files",
433
+ description:
434
+ "Search for files by name or pattern (glob or regex) across the project.",
435
+ inputSchema: {
436
+ type: "object",
437
+ properties: {
438
+ projectPath: {
439
+ type: "string",
440
+ description: "Absolute path to the project root",
441
+ },
442
+ subProject: {
443
+ type: "string",
444
+ description: "Optional sub-project path",
445
+ },
446
+ pattern: {
447
+ type: "string",
448
+ description:
449
+ "Pattern to match against file paths or basenames (e.g., 'App*', 'src/**/*.tsx', 'auth')",
450
+ },
451
+ fields: {
452
+ type: "array",
453
+ items: { type: "string" },
454
+ description:
455
+ "Optional list of fields to return. Omit to return all fields.",
456
+ },
457
+ },
458
+ required: ["projectPath", "pattern"],
459
+ },
460
+ },
461
+ {
462
+ name: "get_file_imports",
463
+ description:
464
+ "Get the list of imports for a specific file from the analysis data. More token-efficient than reading the full file.",
465
+ inputSchema: {
466
+ type: "object",
467
+ properties: {
468
+ projectPath: {
469
+ type: "string",
470
+ description: "Absolute path to the project root",
471
+ },
472
+ subProject: {
473
+ type: "string",
474
+ description: "Optional sub-project path",
475
+ },
476
+ filePath: {
477
+ type: "string",
478
+ description: "Relative path from project root",
479
+ },
480
+ fields: {
481
+ type: "array",
482
+ items: { type: "string" },
483
+ description:
484
+ "Optional list of fields to return. Omit to return all fields.",
485
+ },
486
+ },
487
+ required: ["projectPath", "filePath"],
488
+ },
489
+ },
490
+ {
491
+ name: "get_project_tree",
492
+ description:
493
+ "Get a tree structure of the project directories and files up to a specified depth.",
494
+ inputSchema: {
495
+ type: "object",
496
+ properties: {
497
+ projectPath: {
498
+ type: "string",
499
+ description: "Absolute path to the project root",
500
+ },
501
+ subProject: {
502
+ type: "string",
503
+ description: "Optional sub-project path",
504
+ },
505
+ maxDepth: {
506
+ type: "number",
507
+ description: "Maximum depth to traverse (default: 3)",
508
+ },
509
+ fields: {
510
+ type: "array",
511
+ items: { type: "string" },
512
+ description:
513
+ "Optional list of fields to return. Omit to return all fields.",
514
+ },
515
+ },
516
+ required: ["projectPath"],
517
+ },
518
+ },
519
+ {
520
+ name: "list_files",
521
+ description:
522
+ "List files in the project. For large projects, this returns a summary. Use list_directory for exploring specific folders and get_file_outline for details of a single file.",
523
+ inputSchema: {
524
+ type: "object",
525
+ properties: {
526
+ projectPath: {
527
+ type: "string",
528
+ description: "Absolute path to the project root",
529
+ },
530
+ subProject: {
531
+ type: "string",
532
+ description: "Optional sub-project path",
533
+ },
534
+ fields: {
535
+ type: "array",
536
+ items: { type: "string" },
537
+ description:
538
+ "Optional list of fields to return for each file (e.g., ['path']). Omit to return all fields.",
539
+ },
540
+ exclude: {
541
+ type: "array",
542
+ items: { type: "string" },
543
+ description:
544
+ "List of glob patterns to exclude from results (e.g. ['**/test/**', '**/*.test.tsx']).",
545
+ },
546
+ },
547
+ required: ["projectPath"],
548
+ },
549
+ },
550
+ {
551
+ name: "get_component_hierarchy",
552
+ description:
553
+ "Get the render hierarchy starting from a specific component (who it renders and who renders it).",
554
+ inputSchema: {
555
+ type: "object",
556
+ properties: {
557
+ projectPath: {
558
+ type: "string",
559
+ description: "Absolute path to the project root",
560
+ },
561
+ subProject: {
562
+ type: "string",
563
+ description: "Optional sub-project path",
564
+ },
565
+ componentName: {
566
+ type: "string",
567
+ description: "The name of the component to start from",
568
+ },
569
+ depth: {
570
+ type: "number",
571
+ description:
572
+ "How many levels up and down to traverse (default: 2)",
573
+ },
574
+ fields: {
575
+ type: "array",
576
+ items: { type: "string" },
577
+ description:
578
+ "Optional list of fields to return. Omit to return all fields.",
579
+ },
580
+ },
581
+ required: ["projectPath", "componentName"],
582
+ },
583
+ },
584
+ {
585
+ name: "get_symbol_location",
586
+ description:
587
+ "Get the exact file and location (line/column) of a symbol's definition, including its body scope if it's a function or hook.",
588
+ inputSchema: {
589
+ type: "object",
590
+ properties: {
591
+ projectPath: {
592
+ type: "string",
593
+ description: "Absolute path to the project root",
594
+ },
595
+ subProject: {
596
+ type: "string",
597
+ description: "Optional sub-project path",
598
+ },
599
+ query: {
600
+ type: "string",
601
+ description: "The name of the symbol to find",
602
+ },
603
+ fields: {
604
+ type: "array",
605
+ items: { type: "string" },
606
+ description:
607
+ "Optional list of fields to return. Omit to return all fields.",
608
+ },
609
+ },
610
+ required: ["projectPath", "query"],
611
+ },
612
+ },
613
+ {
614
+ name: "get_symbol_content",
615
+ description: "Get the source code content of a symbol's definition.",
616
+ inputSchema: {
617
+ type: "object",
618
+ properties: {
619
+ projectPath: {
620
+ type: "string",
621
+ description: "Absolute path to the project root",
622
+ },
623
+ subProject: {
624
+ type: "string",
625
+ description: "Optional sub-project path",
626
+ },
627
+ query: {
628
+ type: "string",
629
+ description: "The name of the symbol to find",
630
+ },
631
+ fields: {
632
+ type: "array",
633
+ items: { type: "string" },
634
+ description:
635
+ "Optional list of fields to return. Omit to return all fields.",
636
+ },
637
+ },
638
+ required: ["projectPath", "query"],
639
+ },
640
+ },
641
+ {
642
+ name: "add_label",
643
+ description:
644
+ "Add a persistent label/tag to a file, folder, or variable ID for instant retrieval later.",
645
+ inputSchema: {
646
+ type: "object",
647
+ properties: {
648
+ projectPath: { type: "string" },
649
+ subProject: { type: "string" },
650
+ id: {
651
+ type: "string",
652
+ description:
653
+ "The ID or path to label (e.g. file path or graph ID)",
654
+ },
655
+ label: { type: "string", description: "The label to attach" },
656
+ },
657
+ required: ["projectPath", "id", "label"],
658
+ },
659
+ },
660
+ {
661
+ name: "list_labels",
662
+ description: "List all persistent labels in the project.",
663
+ inputSchema: {
664
+ type: "object",
665
+ properties: {
666
+ projectPath: { type: "string" },
667
+ subProject: { type: "string" },
668
+ },
669
+ required: ["projectPath"],
670
+ },
671
+ },
672
+ {
673
+ name: "search_by_label",
674
+ description:
675
+ "Find entities (files, folders, variables) by their associated label.",
676
+ inputSchema: {
677
+ type: "object",
678
+ properties: {
679
+ projectPath: { type: "string" },
680
+ subProject: { type: "string" },
681
+ label: { type: "string" },
682
+ },
683
+ required: ["projectPath", "label"],
684
+ },
685
+ },
686
+ {
687
+ name: "list_directory",
688
+ description:
689
+ "List files and subdirectories in a specific folder. Use this to explore the project structure efficiently.",
690
+ inputSchema: {
691
+ type: "object",
692
+ properties: {
693
+ projectPath: { type: "string" },
694
+ subProject: { type: "string" },
695
+ dirPath: {
696
+ type: "string",
697
+ description: "Relative path from project root",
698
+ },
699
+ },
700
+ required: ["projectPath", "dirPath"],
701
+ },
702
+ },
703
+ {
704
+ name: "get_file_outline",
705
+ description:
706
+ "Get a structured outline of a single file, including components, hooks, states, and their line numbers.",
707
+ inputSchema: {
708
+ type: "object",
709
+ properties: {
710
+ projectPath: { type: "string" },
711
+ subProject: { type: "string" },
712
+ filePath: {
713
+ type: "string",
714
+ description: "Relative path from project root",
715
+ },
716
+ fields: {
717
+ type: "array",
718
+ items: { type: "string" },
719
+ description:
720
+ "Optional list of fields to return (e.g., ['name', 'line']). Omit to return all fields.",
721
+ },
722
+ },
723
+ required: ["projectPath", "filePath"],
724
+ },
725
+ },
726
+ {
727
+ name: "read_file",
728
+ description: "Read the full content of a file.",
729
+ inputSchema: {
730
+ type: "object",
731
+ properties: {
732
+ projectPath: { type: "string" },
733
+ subProject: { type: "string" },
734
+ filePath: {
735
+ type: "string",
736
+ description: "Relative path from project root",
737
+ },
738
+ },
739
+ required: ["projectPath", "filePath"],
740
+ },
741
+ },
742
+ {
743
+ name: "grep_search",
744
+ description: "Search for a pattern across all files in the project.",
745
+ inputSchema: {
746
+ type: "object",
747
+ properties: {
748
+ projectPath: { type: "string" },
749
+ subProject: { type: "string" },
750
+ pattern: {
751
+ type: "string",
752
+ description: "Regex pattern to search for",
753
+ },
754
+ exclude: {
755
+ type: "array",
756
+ items: { type: "string" },
757
+ description:
758
+ "List of glob patterns to exclude from results (e.g. ['**/test/**', '**/*.test.tsx']).",
759
+ },
760
+ },
761
+ required: ["projectPath", "pattern"],
762
+ },
763
+ },
764
+ {
765
+ name: "run_shell_command",
766
+ description:
767
+ "Execute a shell command in the project directory. Use this for terminal tasks. For searching code, prefer 'grep_search'. If using 'grep' manually, ensure you exclude '.git', 'node_modules', and '.react-map' directories to avoid noise.",
768
+ inputSchema: {
769
+ type: "object",
770
+ properties: {
771
+ projectPath: { type: "string" },
772
+ subProject: { type: "string" },
773
+ command: {
774
+ type: "string",
775
+ description: "The command to execute",
776
+ },
777
+ },
778
+ required: ["projectPath", "command"],
779
+ },
780
+ },
781
+ {
782
+ name: "write_file",
783
+ description:
784
+ "Write content to a file. Useful for creating or overwriting files.",
785
+ inputSchema: {
786
+ type: "object",
787
+ properties: {
788
+ projectPath: { type: "string" },
789
+ subProject: { type: "string" },
790
+ filePath: {
791
+ type: "string",
792
+ description: "Relative path from project root",
793
+ },
794
+ content: { type: "string" },
795
+ },
796
+ required: ["projectPath", "filePath", "content"],
797
+ },
798
+ },
799
+ {
800
+ name: "replace_file_content",
801
+ description: "Replace a string in a file with another string.",
802
+ inputSchema: {
803
+ type: "object",
804
+ properties: {
805
+ projectPath: { type: "string" },
806
+ subProject: { type: "string" },
807
+ filePath: {
808
+ type: "string",
809
+ description: "Relative path from project root",
810
+ },
811
+ oldString: { type: "string" },
812
+ newString: { type: "string" },
813
+ },
814
+ required: ["projectPath", "filePath", "oldString", "newString"],
815
+ },
816
+ },
817
+ {
818
+ name: "multi_replace_file_content",
819
+ description: "Perform multiple string replacements in a single file.",
820
+ inputSchema: {
821
+ type: "object",
822
+ properties: {
823
+ projectPath: { type: "string" },
824
+ subProject: { type: "string" },
825
+ filePath: {
826
+ type: "string",
827
+ description: "Relative path from project root",
828
+ },
829
+ replacements: {
830
+ type: "array",
831
+ items: {
832
+ type: "object",
833
+ properties: {
834
+ oldString: { type: "string" },
835
+ newString: { type: "string" },
836
+ },
837
+ required: ["oldString", "newString"],
838
+ },
839
+ },
840
+ },
841
+ required: ["projectPath", "filePath", "replacements"],
842
+ },
843
+ },
844
+ ];
845
+
846
+ const extensions = this.projectManager.getAllExtensions();
847
+ const extensionTools = extensions.flatMap((ext) =>
848
+ (ext.mcpTools || []).map((tool) => ({
849
+ name: `${ext.id}_${tool.name}`,
850
+ description: tool.description,
851
+ inputSchema: tool.inputSchema,
852
+ })),
853
+ );
854
+
855
+ return {
856
+ tools: [...baseTools, ...extensionTools],
857
+ };
858
+ });
859
+
860
+ this.mcpServer.setRequestHandler(CallToolRequestSchema, async (request) => {
861
+ const { name, arguments: args } = request.params;
862
+ try {
863
+ const result = await this.handleCallTool({
864
+ name: name as keyof ToolArgsMap,
865
+ args: args as unknown as ToolArgsMap[keyof ToolArgsMap],
866
+ } as ToolCall);
867
+ return result;
868
+ } catch (error: unknown) {
869
+ const errorMessage =
870
+ error instanceof Error ? error.message : "Unknown error";
871
+ return {
872
+ isError: true,
873
+ content: [{ type: "text", text: errorMessage }],
874
+ };
875
+ }
876
+ });
877
+ }
878
+
879
+ public async handleCallTool(toolCall: ToolCall) {
880
+ // Handle extension tools
881
+ const extensions = this.projectManager.getAllExtensions();
882
+ for (const ext of extensions) {
883
+ if (toolCall.name.startsWith(`${ext.id}_`)) {
884
+ const toolName = toolCall.name.replace(`${ext.id}_`, "");
885
+ const tool = (ext.mcpTools || []).find((t) => t.name === toolName);
886
+ if (tool) {
887
+ const result = await tool.handler({
888
+ ...toolCall.args,
889
+ projectManager: this.projectManager,
890
+ });
891
+ return {
892
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
893
+ };
894
+ }
895
+ }
896
+ }
897
+
898
+ return await this.handleKnownToolCall(toolCall as KnownToolCall);
899
+ }
900
+
901
+ private async handleKnownToolCall(knownCall: KnownToolCall) {
902
+ switch (knownCall.name) {
903
+ case "open_project": {
904
+ const { projectPath, subProject } = knownCall.args;
905
+ await this.projectManager.openProject(projectPath, subProject);
906
+ return {
907
+ content: [
908
+ {
909
+ type: "text",
910
+ text: `Project ${subProject || projectPath} opened and analyzed successfully.`,
911
+ },
912
+ ],
913
+ };
914
+ }
915
+ case "get_symbol_info": {
916
+ const {
917
+ projectPath,
918
+ subProject,
919
+ query,
920
+ strict,
921
+ props,
922
+ usages,
923
+ loc,
924
+ exclude,
925
+ fields,
926
+ } = knownCall.args;
927
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
928
+
929
+ const includeUsage = usages === true; // Default to false
930
+
931
+ const results = await this.projectManager.findSymbol(
932
+ resolvedPath,
933
+ query,
934
+ subProject,
935
+ strict !== false, // Default to strict true
936
+ props === true, // Default to false
937
+ includeUsage,
938
+ exclude || DEFAULT_EXCLUDES,
939
+ );
940
+
941
+ const includeLoc = loc === true;
942
+
943
+ const processItem = (item: SymbolSearchResult) => {
944
+ const processed = { ...item };
945
+ if (!includeLoc) {
946
+ delete (processed as Partial<SymbolSearchResult>).loc;
947
+ }
948
+ if (processed.usages) {
949
+ processed.usages = processed.usages.map((u) => processItem(u));
950
+ }
951
+
952
+ return processed;
953
+ };
954
+
955
+ const result: SymbolInfo = {
956
+ definitions: results.definitions.map((d) => processItem(d)),
957
+ };
958
+
959
+ if (includeUsage) {
960
+ result.externalUsages = (results.externalUsages ?? []).map((u) =>
961
+ processItem(u),
962
+ );
963
+ }
964
+
965
+ return {
966
+ content: [
967
+ {
968
+ type: "text",
969
+ text: JSON.stringify(this.filterFields(result, fields), null, 2),
970
+ },
971
+ ],
972
+ };
973
+ }
974
+ case "get_symbol_usages_with_context": {
975
+ const {
976
+ projectPath,
977
+ subProject,
978
+ query,
979
+ strict,
980
+ contextLines,
981
+ exclude,
982
+ fields,
983
+ } = knownCall.args;
984
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
985
+ const results = await this.projectManager.getSymbolUsagesWithContext(
986
+ resolvedPath,
987
+ query,
988
+ subProject,
989
+ strict !== false,
990
+ contextLines ?? 2,
991
+ exclude || DEFAULT_EXCLUDES,
992
+ );
993
+
994
+ return {
995
+ content: [
996
+ {
997
+ type: "text",
998
+ text: JSON.stringify(this.filterFields(results, fields), null, 2),
999
+ },
1000
+ ],
1001
+ };
1002
+ }
1003
+ case "get_prop_definitions": {
1004
+ const { projectPath, subProject, componentName, fields } =
1005
+ knownCall.args;
1006
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1007
+ const results = await this.projectManager.getPropDefinitions(
1008
+ resolvedPath,
1009
+ componentName,
1010
+ subProject,
1011
+ );
1012
+
1013
+ return {
1014
+ content: [
1015
+ {
1016
+ type: "text",
1017
+ text: JSON.stringify(this.filterFields(results, fields), null, 2),
1018
+ },
1019
+ ],
1020
+ };
1021
+ }
1022
+ case "find_files": {
1023
+ const { projectPath, subProject, pattern, fields } = knownCall.args;
1024
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1025
+ const results = await this.projectManager.findFiles(
1026
+ resolvedPath,
1027
+ pattern,
1028
+ subProject,
1029
+ );
1030
+
1031
+ return {
1032
+ content: [
1033
+ {
1034
+ type: "text",
1035
+ text: JSON.stringify(this.filterFields(results, fields), null, 2),
1036
+ },
1037
+ ],
1038
+ };
1039
+ }
1040
+
1041
+ case "get_file_imports": {
1042
+ const { projectPath, subProject, filePath, fields } = knownCall.args;
1043
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1044
+ const results = await this.projectManager.getFileImports(
1045
+ resolvedPath,
1046
+ filePath,
1047
+ subProject,
1048
+ );
1049
+
1050
+ return {
1051
+ content: [
1052
+ {
1053
+ type: "text",
1054
+ text: JSON.stringify(this.filterFields(results, fields), null, 2),
1055
+ },
1056
+ ],
1057
+ };
1058
+ }
1059
+
1060
+ case "get_project_tree": {
1061
+ const { projectPath, subProject, maxDepth, fields } = knownCall.args;
1062
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1063
+ const results = await this.projectManager.getProjectTree(
1064
+ resolvedPath,
1065
+ subProject,
1066
+ maxDepth,
1067
+ );
1068
+
1069
+ return {
1070
+ content: [
1071
+ {
1072
+ type: "text",
1073
+ text: JSON.stringify(this.filterFields(results, fields), null, 2),
1074
+ },
1075
+ ],
1076
+ };
1077
+ }
1078
+
1079
+ case "list_files": {
1080
+ const { projectPath, subProject, exclude, fields } = knownCall.args;
1081
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1082
+ const project = await this.projectManager.openProject(
1083
+ resolvedPath,
1084
+ subProject,
1085
+ );
1086
+
1087
+ const excludePatterns = exclude || DEFAULT_EXCLUDES;
1088
+ const isExcluded = (filePath: string) => {
1089
+ return excludePatterns.some(
1090
+ (pattern) =>
1091
+ minimatch(filePath, pattern, { dot: true, nocase: true }) ||
1092
+ minimatch(path.basename(filePath), pattern, {
1093
+ dot: true,
1094
+ nocase: true,
1095
+ }),
1096
+ );
1097
+ };
1098
+
1099
+ const files = Object.entries(project.graph!.files).filter(
1100
+ ([path]) => !isExcluded(path),
1101
+ );
1102
+ const totalFiles = files.length;
1103
+ const MAX_FILES = 50;
1104
+ const displayedFiles = files.slice(0, MAX_FILES);
1105
+
1106
+ let fileSummary: {
1107
+ path: string;
1108
+ exports?: { name: string; kind: string }[];
1109
+ }[];
1110
+
1111
+ if (totalFiles > MAX_FILES) {
1112
+ // Large project: return only paths for a subset to save tokens
1113
+ fileSummary = displayedFiles.map(([path]) => ({ path }));
1114
+ } else {
1115
+ fileSummary = displayedFiles.map(([path, file]) => {
1116
+ return {
1117
+ path,
1118
+ exports: Object.values(file.var || {}).map((v) => ({
1119
+ name: getDisplayName(v.name),
1120
+ kind: v.kind,
1121
+ })),
1122
+ };
1123
+ });
1124
+ }
1125
+
1126
+ return {
1127
+ content: [
1128
+ {
1129
+ type: "text",
1130
+ text: JSON.stringify(
1131
+ {
1132
+ totalFiles,
1133
+ displayedCount: fileSummary.length,
1134
+ files: this.filterFields(fileSummary, fields),
1135
+ hint:
1136
+ totalFiles > MAX_FILES
1137
+ ? `Project has ${totalFiles} files. Showing first ${MAX_FILES}. Use 'list_directory' to explore folders or 'find_files' to search for specific files.`
1138
+ : undefined,
1139
+ },
1140
+ null,
1141
+ 2,
1142
+ ),
1143
+ },
1144
+ ],
1145
+ };
1146
+ }
1147
+
1148
+ case "get_component_hierarchy": {
1149
+ const { projectPath, subProject, componentName, depth, fields } =
1150
+ knownCall.args;
1151
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1152
+ const result = await this.projectManager.getComponentHierarchy(
1153
+ resolvedPath,
1154
+ componentName,
1155
+ subProject,
1156
+ depth,
1157
+ );
1158
+ return {
1159
+ content: [
1160
+ {
1161
+ type: "text",
1162
+ text: JSON.stringify(this.filterFields(result, fields), null, 2),
1163
+ },
1164
+ ],
1165
+ };
1166
+ }
1167
+
1168
+ case "get_symbol_location": {
1169
+ const { projectPath, subProject, query, fields } = knownCall.args;
1170
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1171
+ const result = await this.projectManager.getSymbolLocation(
1172
+ resolvedPath,
1173
+ query,
1174
+ subProject,
1175
+ );
1176
+ return {
1177
+ content: [
1178
+ {
1179
+ type: "text",
1180
+ text: JSON.stringify(this.filterFields(result, fields), null, 2),
1181
+ },
1182
+ ],
1183
+ };
1184
+ }
1185
+
1186
+ case "get_symbol_content": {
1187
+ const { projectPath, subProject, query, fields } = knownCall.args;
1188
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1189
+ const result = await this.projectManager.getSymbolContent(
1190
+ resolvedPath,
1191
+ query,
1192
+ subProject,
1193
+ );
1194
+ return {
1195
+ content: [
1196
+ {
1197
+ type: "text",
1198
+ text: JSON.stringify(this.filterFields(result, fields), null, 2),
1199
+ },
1200
+ ],
1201
+ };
1202
+ }
1203
+
1204
+ case "add_label": {
1205
+ const { projectPath, subProject, id, label } = knownCall.args;
1206
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1207
+ const result = await this.projectManager.addLabel(
1208
+ resolvedPath,
1209
+ id,
1210
+ label,
1211
+ subProject,
1212
+ );
1213
+ return {
1214
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1215
+ };
1216
+ }
1217
+
1218
+ case "list_labels": {
1219
+ const { projectPath, subProject } = knownCall.args;
1220
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1221
+ const result = await this.projectManager.getLabels(
1222
+ resolvedPath,
1223
+ subProject,
1224
+ );
1225
+ return {
1226
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1227
+ };
1228
+ }
1229
+
1230
+ case "search_by_label": {
1231
+ const { projectPath, subProject, label } = knownCall.args;
1232
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1233
+ const result = await this.projectManager.findEntitiesByLabel(
1234
+ resolvedPath,
1235
+ label,
1236
+ subProject,
1237
+ );
1238
+ return {
1239
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1240
+ };
1241
+ }
1242
+
1243
+ case "list_directory": {
1244
+ const { projectPath, subProject, dirPath } = knownCall.args;
1245
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1246
+ const result = await this.projectManager.listDirectory(
1247
+ resolvedPath,
1248
+ dirPath,
1249
+ subProject,
1250
+ );
1251
+ return {
1252
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1253
+ };
1254
+ }
1255
+
1256
+ case "get_file_outline": {
1257
+ const { projectPath, subProject, filePath, fields } = knownCall.args;
1258
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1259
+ const result = await this.projectManager.getFileOutline(
1260
+ resolvedPath,
1261
+ filePath,
1262
+ subProject,
1263
+ );
1264
+ return {
1265
+ content: [
1266
+ {
1267
+ type: "text",
1268
+ text: JSON.stringify(this.filterFields(result, fields), null, 2),
1269
+ },
1270
+ ],
1271
+ };
1272
+ }
1273
+
1274
+ case "read_file": {
1275
+ const { projectPath, subProject, filePath } = knownCall.args;
1276
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1277
+ const result = await this.projectManager.readFile(
1278
+ resolvedPath,
1279
+ filePath,
1280
+ subProject,
1281
+ );
1282
+ return { content: [{ type: "text", text: result }] };
1283
+ }
1284
+
1285
+ case "grep_search": {
1286
+ const { projectPath, subProject, pattern, exclude } = knownCall.args;
1287
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1288
+ const result = await this.projectManager.grepSearch(
1289
+ resolvedPath,
1290
+ pattern,
1291
+ subProject,
1292
+ exclude || DEFAULT_EXCLUDES,
1293
+ );
1294
+ return {
1295
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1296
+ };
1297
+ }
1298
+
1299
+ case "run_shell_command": {
1300
+ const { projectPath, subProject, command } = knownCall.args;
1301
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1302
+ const result = await this.projectManager.runShellCommand(
1303
+ resolvedPath,
1304
+ command,
1305
+ subProject,
1306
+ );
1307
+ return {
1308
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1309
+ };
1310
+ }
1311
+
1312
+ case "write_file": {
1313
+ const { projectPath, subProject, filePath, content } = knownCall.args;
1314
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1315
+ const success = await this.projectManager.writeFile(
1316
+ resolvedPath,
1317
+ filePath,
1318
+ content,
1319
+ );
1320
+ return {
1321
+ content: [{ type: "text", text: JSON.stringify({ success }) }],
1322
+ };
1323
+ }
1324
+
1325
+ case "replace_file_content": {
1326
+ const { projectPath, subProject, filePath, oldString, newString } =
1327
+ knownCall.args;
1328
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1329
+ const success = await this.projectManager.replaceFileContent(
1330
+ resolvedPath,
1331
+ filePath,
1332
+ oldString,
1333
+ newString,
1334
+ );
1335
+ return {
1336
+ content: [{ type: "text", text: JSON.stringify({ success }) }],
1337
+ };
1338
+ }
1339
+
1340
+ case "multi_replace_file_content": {
1341
+ const { projectPath, subProject, filePath, replacements } =
1342
+ knownCall.args;
1343
+ const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1344
+ const success = await this.projectManager.multiReplaceFileContent(
1345
+ resolvedPath,
1346
+ filePath,
1347
+ replacements,
1348
+ );
1349
+ return {
1350
+ content: [{ type: "text", text: JSON.stringify({ success }) }],
1351
+ };
1352
+ }
1353
+
1354
+ default:
1355
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1356
+ // @ts-expect-error
1357
+ throw new Error(`Unknown tool: ${knownCall.name}`);
1358
+ }
1359
+ }
1360
+
1361
+ private filterFields<T>(data: T, fields?: string[]): T {
1362
+ if (!fields || !data) return data;
1363
+
1364
+ if (Array.isArray(data)) {
1365
+ return data.map((item) =>
1366
+ this.filterFields(item, fields),
1367
+ ) as unknown as T;
1368
+ }
1369
+
1370
+ if (typeof data !== "object") return data;
1371
+
1372
+ const filtered: Record<string, unknown> = {};
1373
+ const obj = data as Record<string, unknown>;
1374
+ for (const field of fields) {
1375
+ if (field in obj) {
1376
+ filtered[field] = obj[field];
1377
+ }
1378
+ }
1379
+ return filtered as unknown as T;
1380
+ }
1381
+
1382
+ private resolveProjectPath(
1383
+ projectPath: string,
1384
+ _subProject?: string,
1385
+ ): string {
1386
+ if (projectPath === "." || projectPath === "/" || !projectPath) {
1387
+ const projects = this.projectManager.getOpenProjectPaths();
1388
+ if (projects.length > 0) {
1389
+ // Fallback to the first project in the map if a generic path is given
1390
+ return projects[0];
1391
+ }
1392
+ }
1393
+ return projectPath;
1394
+ }
1395
+
1396
+ private sendResponse<K extends BackendMessageType>(
1397
+ ws: WebSocket,
1398
+ type: string,
1399
+ payload: BackendRequestMap[K]["response"],
1400
+ requestId?: string,
1401
+ ) {
1402
+ ws.send(JSON.stringify({ type, payload, requestId }));
1403
+ }
1404
+
1405
+ private sendChunkedResponse<K extends BackendMessageType>(
1406
+ ws: WebSocket,
1407
+ type: string,
1408
+ payload: BackendRequestMap[K]["response"],
1409
+ requestId?: string,
1410
+ ) {
1411
+ const data = JSON.stringify(payload);
1412
+ const CHUNK_SIZE = 1024 * 1024; // 1MB chunks
1413
+
1414
+ if (data.length <= CHUNK_SIZE) {
1415
+ this.sendResponse(ws, type, payload, requestId);
1416
+ return;
1417
+ }
1418
+
1419
+ const totalChunks = Math.ceil(data.length / CHUNK_SIZE);
1420
+ for (let i = 0; i < totalChunks; i++) {
1421
+ const chunk = data.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
1422
+ ws.send(
1423
+ JSON.stringify({
1424
+ type: "chunked_response",
1425
+ payload: {
1426
+ chunk,
1427
+ index: i,
1428
+ total: totalChunks,
1429
+ originalType: type,
1430
+ },
1431
+ requestId,
1432
+ }),
1433
+ );
1434
+ }
1435
+ }
1436
+
1437
+ private sendError(ws: WebSocket, message: string, requestId?: string) {
1438
+ ws.send(JSON.stringify({ type: "error", payload: { message }, requestId }));
1439
+ }
1440
+
1441
+ public startWebSocketServer() {
1442
+ try {
1443
+ this.wss = new WebSocketServer({
1444
+ port: this.port,
1445
+ maxPayload: 100 * 1024 * 1024, // 100MB
1446
+ perMessageDeflate: true,
1447
+ });
1448
+
1449
+ this.wss.on("error", (error) => {
1450
+ const errorMessage =
1451
+ error instanceof Error ? error.message : "Unknown error";
1452
+ console.error(`WebSocket server error: ${errorMessage}`);
1453
+ const err = error as { code?: string };
1454
+ if (err.code === "EADDRINUSE") {
1455
+ console.error(
1456
+ `Port ${this.port} is already in use. This instance will proceed without a WebSocket server.`,
1457
+ );
1458
+ this.wss = null;
1459
+ }
1460
+ });
1461
+
1462
+ console.error(`React Map backend started on ws://localhost:${this.port}`);
1463
+
1464
+ this.wss.on("connection", (ws) => {
1465
+ this.uiConnections++;
1466
+ console.error(
1467
+ `UI connected via WebSocket (Active: ${this.uiConnections})`,
1468
+ );
1469
+ this.checkExitCondition();
1470
+
1471
+ ws.on("close", () => {
1472
+ this.uiConnections--;
1473
+ console.error(`UI disconnected (Active: ${this.uiConnections})`);
1474
+ this.checkExitCondition();
1475
+ });
1476
+
1477
+ ws.on("message", async (message) => {
1478
+ let currentRequestId: string | undefined;
1479
+ try {
1480
+ const data = JSON.parse(message.toString()) as WsMessage;
1481
+ currentRequestId = data.requestId;
1482
+
1483
+ console.error(
1484
+ `Received WebSocket message: ${data.type} (Request: ${data.requestId || "none"})`,
1485
+ );
1486
+
1487
+ switch (data.type) {
1488
+ case "open_project": {
1489
+ const { projectPath, subProject } = data.payload;
1490
+ const project = await this.projectManager.openProject(
1491
+ projectPath,
1492
+ subProject,
1493
+ );
1494
+ this.sendResponse(
1495
+ ws,
1496
+ "project_opened",
1497
+ { sqlitePath: project.sqlitePath },
1498
+ data.requestId,
1499
+ );
1500
+ break;
1501
+ }
1502
+ case "update_graph_position": {
1503
+ const { projectPath, subProject, positions, contextId } =
1504
+ data.payload;
1505
+ const success = await this.projectManager.updateGraphPosition(
1506
+ projectPath,
1507
+ subProject,
1508
+ positions,
1509
+ contextId,
1510
+ );
1511
+ this.sendResponse(
1512
+ ws,
1513
+ "position_updated",
1514
+ { success },
1515
+ data.requestId,
1516
+ );
1517
+ break;
1518
+ }
1519
+ case "save_state": {
1520
+ const { projectPath, state } = data.payload;
1521
+ const success = await this.projectManager.saveAppState(
1522
+ projectPath,
1523
+ state,
1524
+ );
1525
+ this.sendResponse(
1526
+ ws,
1527
+ "state_saved",
1528
+ { success },
1529
+ data.requestId,
1530
+ );
1531
+ break;
1532
+ }
1533
+ case "read_state": {
1534
+ const { projectPath } = data.payload;
1535
+ const state =
1536
+ await this.projectManager.readAppState(projectPath);
1537
+ this.sendResponse(ws, "state_data", state, data.requestId);
1538
+ break;
1539
+ }
1540
+ case "check_project_status": {
1541
+ const { projectPath } = data.payload;
1542
+ const status =
1543
+ await this.projectManager.checkProjectStatus(projectPath);
1544
+ this.sendResponse(ws, "project_status", status, data.requestId);
1545
+ break;
1546
+ }
1547
+ case "save_project_config": {
1548
+ const { projectPath, config } = data.payload;
1549
+ const success = await this.projectManager.saveProjectConfig(
1550
+ projectPath,
1551
+ config,
1552
+ );
1553
+ this.sendResponse(
1554
+ ws,
1555
+ "config_saved",
1556
+ { success },
1557
+ data.requestId,
1558
+ );
1559
+ break;
1560
+ }
1561
+ case "get_project_icon": {
1562
+ const { projectPath } = data.payload;
1563
+ const icon =
1564
+ await this.projectManager.getProjectIcon(projectPath);
1565
+ this.sendResponse(ws, "project_icon", { icon }, data.requestId);
1566
+ break;
1567
+ }
1568
+ case "git_status": {
1569
+ const { projectPath } = data.payload;
1570
+ const status = await this.projectManager.gitStatus(projectPath);
1571
+ this.sendResponse(
1572
+ ws,
1573
+ "git_status_data",
1574
+ status,
1575
+ data.requestId,
1576
+ );
1577
+ break;
1578
+ }
1579
+ case "git_log": {
1580
+ const { projectPath, options } = data.payload;
1581
+ const log = await this.projectManager.gitLog(
1582
+ projectPath,
1583
+ options,
1584
+ );
1585
+ this.sendResponse(ws, "git_log_data", log, data.requestId);
1586
+ break;
1587
+ }
1588
+ case "git_diff": {
1589
+ const { projectPath, options } = data.payload;
1590
+ const diff = await this.projectManager.gitDiff(
1591
+ projectPath,
1592
+ options,
1593
+ );
1594
+ this.sendResponse(ws, "git_diff_data", diff, data.requestId);
1595
+ break;
1596
+ }
1597
+ case "git_analyze_commit": {
1598
+ const { projectPath, commitHash, subPath } = data.payload;
1599
+ const graph = await this.projectManager.gitAnalyzeCommit(
1600
+ projectPath,
1601
+ commitHash,
1602
+ subPath,
1603
+ );
1604
+ this.sendChunkedResponse(
1605
+ ws,
1606
+ "git_analyze_commit",
1607
+ graph,
1608
+ data.requestId,
1609
+ );
1610
+ break;
1611
+ }
1612
+ case "call_tool": {
1613
+ const { name, arguments: args } = data.payload;
1614
+ const result = await this.handleCallTool({
1615
+ name: name as keyof ToolArgsMap,
1616
+ args: args as unknown as ToolArgsMap[keyof ToolArgsMap],
1617
+ } as ToolCall);
1618
+ ws.send(
1619
+ JSON.stringify({
1620
+ type: "tool_result",
1621
+ payload: result,
1622
+ requestId: data.requestId,
1623
+ }),
1624
+ );
1625
+ break;
1626
+ }
1627
+ case "chunked_response": {
1628
+ // Server receiving a chunked response from client is not supported
1629
+ break;
1630
+ }
1631
+ default: {
1632
+ const unknownData = data as unknown as {
1633
+ type: string;
1634
+ requestId?: string;
1635
+ };
1636
+ this.sendError(
1637
+ ws,
1638
+ `Unknown message type: ${unknownData.type}`,
1639
+ unknownData.requestId,
1640
+ );
1641
+ break;
1642
+ }
1643
+ }
1644
+ } catch (e: unknown) {
1645
+ const errorMessage =
1646
+ e instanceof Error ? e.message : "Unknown error";
1647
+ console.error("Error handling WebSocket message", e);
1648
+ this.sendError(ws, errorMessage, currentRequestId);
1649
+ }
1650
+ });
1651
+ });
1652
+ } catch (error: unknown) {
1653
+ const errorMessage =
1654
+ error instanceof Error ? error.message : "Unknown error";
1655
+ console.error(`Failed to start WebSocket server: ${errorMessage}`);
1656
+ }
1657
+ }
1658
+
1659
+ public async startMcpServer(transport: StdioServerTransport) {
1660
+ this.mcpConnected = true;
1661
+
1662
+ transport.onclose = () => {
1663
+ console.error("MCP stdio connection closed.");
1664
+ this.mcpConnected = false;
1665
+ this.checkExitCondition();
1666
+ };
1667
+
1668
+ await this.mcpServer.connect(transport);
1669
+ console.error(
1670
+ `React Map MCP server running on stdio and ws://localhost:${this.port}`,
1671
+ );
1672
+
1673
+ // Initial check after 10s to see if anyone connected
1674
+ setTimeout(() => this.checkExitCondition(), 10000);
1675
+ }
1676
+
1677
+ private checkExitCondition() {
1678
+ if (process.env.NODE_ENV === "development") {
1679
+ return;
1680
+ }
1681
+
1682
+ if (this.uiConnections === 0 && !this.mcpConnected) {
1683
+ if (!this.exitTimeout) {
1684
+ console.error(
1685
+ "No active connections (UI or MCP). Starting 10s exit countdown...",
1686
+ );
1687
+ this.exitTimeout = setTimeout(async () => {
1688
+ if (this.uiConnections === 0 && !this.mcpConnected) {
1689
+ console.error("No active connections for 10s. Self-terminating...");
1690
+ await this.projectManager.closeAll();
1691
+ process.exit(0);
1692
+ } else {
1693
+ this.exitTimeout = null;
1694
+ }
1695
+ }, 10000);
1696
+ }
1697
+ } else if (this.exitTimeout) {
1698
+ console.error("Connection restored. Cancelling exit countdown.");
1699
+ clearTimeout(this.exitTimeout);
1700
+ this.exitTimeout = null;
1701
+ }
1702
+ }
1703
+
1704
+ public async stop() {
1705
+ if (this.wss) {
1706
+ await new Promise<void>((resolve) => this.wss!.close(() => resolve()));
1707
+ }
1708
+ await this.mcpServer.close();
1709
+ }
1710
+ }