@nexiq/cli 1.0.1 → 1.0.2

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/dist/index.js DELETED
@@ -1,2438 +0,0 @@
1
- // src/index.ts
2
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
-
4
- // src/projectManager.ts
5
- import fs from "fs";
6
- import path from "path";
7
- import { minimatch } from "minimatch";
8
- import * as watcher from "@parcel/watcher";
9
- import { analyzeProject } from "@nexiq/analyser";
10
- import { SqliteDB } from "@nexiq/analyser/db/sqlite";
11
- import {
12
- getDisplayName,
13
- parseRawDiff
14
- } from "@nexiq/shared";
15
- import { pathToFileURL } from "url";
16
- import { exec } from "child_process";
17
- import { promisify } from "util";
18
- import { simpleGit } from "simple-git";
19
- import yaml from "js-yaml";
20
- import fg from "fast-glob";
21
- import tmp from "tmp";
22
- var execAsync = promisify(exec);
23
- var ProjectManager = class {
24
- projects = /* @__PURE__ */ new Map();
25
- pendingProjects = /* @__PURE__ */ new Map();
26
- async openProject(projectPath, subProject) {
27
- const key = subProject ? `${projectPath}:${subProject}` : projectPath;
28
- if (this.projects.has(key)) {
29
- return this.projects.get(key);
30
- }
31
- if (this.pendingProjects.has(key)) {
32
- console.error(
33
- `Project already opening: ${key}, returning pending promise`
34
- );
35
- return this.pendingProjects.get(key);
36
- }
37
- const openPromise = (async () => {
38
- try {
39
- const result = await this._openProjectInternal(projectPath, subProject);
40
- this.projects.set(key, result);
41
- return result;
42
- } finally {
43
- this.pendingProjects.delete(key);
44
- }
45
- })();
46
- this.pendingProjects.set(key, openPromise);
47
- return openPromise;
48
- }
49
- async _openProjectInternal(projectPath, subProject) {
50
- const analysisPath = subProject ? path.resolve(projectPath, subProject) : projectPath;
51
- const cacheDir = path.join(analysisPath, ".react-map", "cache");
52
- try {
53
- if (!fs.existsSync(cacheDir)) {
54
- fs.mkdirSync(cacheDir, { recursive: true });
55
- }
56
- } catch (e) {
57
- console.warn(`Failed to create cache directory at ${cacheDir}:`, e);
58
- }
59
- const pathHash = Buffer.from(analysisPath).toString("hex").slice(0, 8);
60
- const cacheFile = path.join(
61
- cacheDir,
62
- `${path.basename(analysisPath)}-${pathHash}.json`
63
- );
64
- const sqlitePath = path.join(
65
- cacheDir,
66
- `${path.basename(analysisPath)}-${pathHash}.sqlite`
67
- );
68
- const configPath = path.join(analysisPath, "react.map.config.json");
69
- let ignorePatterns;
70
- let extensionNames = [];
71
- if (fs.existsSync(configPath)) {
72
- try {
73
- const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
74
- ignorePatterns = config.ignorePatterns;
75
- extensionNames = config.extensions || [];
76
- } catch (e) {
77
- console.warn("Failed to load config for project", e);
78
- }
79
- }
80
- const extensions = [];
81
- for (const name of extensionNames) {
82
- try {
83
- let loaded;
84
- try {
85
- loaded = await import(name);
86
- } catch (e) {
87
- const projectNodeModulesPath = path.join(
88
- analysisPath,
89
- "node_modules",
90
- name
91
- );
92
- const pkgJsonPath = path.join(projectNodeModulesPath, "package.json");
93
- if (fs.existsSync(pkgJsonPath)) {
94
- const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
95
- const entry = pkg.module || pkg.main || "index.js";
96
- const fullPath = path.join(projectNodeModulesPath, entry);
97
- loaded = await import(pathToFileURL(fullPath).href);
98
- } else {
99
- throw e;
100
- }
101
- }
102
- const extension = Object.values(
103
- loaded || {}
104
- ).find(
105
- (val) => val && typeof val === "object" && "id" in val
106
- );
107
- if (extension) {
108
- extensions.push(extension);
109
- console.error(`Loaded extension: ${extension.id} from ${name}`);
110
- }
111
- } catch (e) {
112
- console.error(
113
- `Failed to load extension ${name}:`,
114
- e instanceof Error ? e.message : "Unknown error"
115
- );
116
- }
117
- }
118
- console.error(`Analyzing project: ${analysisPath}`);
119
- const graph = await analyzeProject(
120
- analysisPath,
121
- cacheFile,
122
- ignorePatterns,
123
- sqlitePath
124
- );
125
- fs.writeFileSync(cacheFile, JSON.stringify(graph, null, 2));
126
- const projectInfo = {
127
- projectPath,
128
- subProject,
129
- graph,
130
- extensions,
131
- sqlitePath,
132
- db: new SqliteDB(sqlitePath)
133
- };
134
- try {
135
- const subscription = await watcher.subscribe(
136
- analysisPath,
137
- (err, events) => {
138
- if (err) {
139
- console.error(`Watcher error for ${analysisPath}:`, err);
140
- return;
141
- }
142
- const hasRelevantChange = events.some((event) => {
143
- const filePath = event.path;
144
- return filePath.endsWith(".ts") || filePath.endsWith(".tsx") || filePath.endsWith(".js") || filePath.endsWith(".jsx");
145
- });
146
- if (hasRelevantChange) {
147
- console.error(
148
- `Changes detected in ${analysisPath}, re-analyzing...`
149
- );
150
- analyzeProject(
151
- analysisPath,
152
- cacheFile,
153
- ignorePatterns,
154
- projectInfo.sqlitePath
155
- ).then((newGraph) => {
156
- projectInfo.graph = newGraph;
157
- fs.writeFileSync(
158
- cacheFile,
159
- JSON.stringify(projectInfo.graph, null, 2)
160
- );
161
- if (projectInfo.db) projectInfo.db.close();
162
- projectInfo.db = new SqliteDB(projectInfo.sqlitePath);
163
- console.error(
164
- `Project ${analysisPath} re-analyzed successfully.`
165
- );
166
- }).catch((reAnalyzeError) => {
167
- console.error(
168
- `Re-analysis failed for ${analysisPath}:`,
169
- reAnalyzeError
170
- );
171
- });
172
- }
173
- },
174
- {
175
- ignore: [
176
- "node_modules",
177
- ".git",
178
- ".react-map",
179
- "dist",
180
- "build",
181
- ".next",
182
- ".vite",
183
- ...(ignorePatterns || []).map(
184
- (p) => p.replace(/^\*\*\/|\/\*\*$/g, "")
185
- )
186
- ]
187
- }
188
- );
189
- projectInfo.subscription = subscription;
190
- } catch (watcherError) {
191
- console.error(
192
- `Failed to start watcher for ${analysisPath}:`,
193
- watcherError
194
- );
195
- }
196
- return projectInfo;
197
- }
198
- async getDatabaseData(projectPath, subProject) {
199
- const project = await this.openProject(projectPath, subProject);
200
- return project.db.getAllData();
201
- }
202
- getOpenProjectPaths() {
203
- return Array.from(this.projects.values()).map((p) => p.projectPath);
204
- }
205
- getProject(projectPath, subProject) {
206
- const key = subProject ? `${projectPath}:${subProject}` : projectPath;
207
- return this.projects.get(key);
208
- }
209
- getAllExtensions() {
210
- const all = /* @__PURE__ */ new Map();
211
- for (const project of this.projects.values()) {
212
- for (const ext of project.extensions) {
213
- all.set(ext.id, ext);
214
- }
215
- }
216
- return Array.from(all.values());
217
- }
218
- async findSymbol(projectPath, query, subProject, strict = true, includeProps = false, includeUsages = false, exclude) {
219
- const project = await this.openProject(projectPath, subProject);
220
- const definitions_results = [];
221
- const externalUsages = [];
222
- const isExcluded = (filePath) => {
223
- if (!exclude || exclude.length === 0) return false;
224
- return exclude.some(
225
- (pattern) => minimatch(filePath, pattern, { dot: true, nocase: true }) || minimatch(path.basename(filePath), pattern, {
226
- dot: true,
227
- nocase: true
228
- })
229
- );
230
- };
231
- let definitions;
232
- if (strict) {
233
- definitions = project.db.db.prepare(
234
- `
235
- SELECT s.*, f.path as file, e.line, e.column, e.kind, e.type, e.data_json
236
- FROM symbols s
237
- JOIN entities e ON s.entity_id = e.id
238
- JOIN scopes sc ON e.scope_id = sc.id
239
- JOIN files f ON sc.file_id = f.id
240
- WHERE s.name = ? and e.kind != 'import'
241
- `
242
- ).all(query);
243
- } else {
244
- definitions = project.db.db.prepare(
245
- `
246
- SELECT s.*, f.path as file, e.line, e.column, e.kind, e.type, e.data_json
247
- FROM symbols s
248
- JOIN entities e ON s.entity_id = e.id
249
- JOIN scopes sc ON e.scope_id = sc.id
250
- JOIN files f ON sc.file_id = f.id
251
- WHERE (s.name = ? OR s.name LIKE ?) and e.kind != 'import'
252
- `
253
- ).all(query, `%${query}%`);
254
- }
255
- for (const def of definitions) {
256
- if (isExcluded(def.file)) continue;
257
- const definition = {
258
- kind: def.kind,
259
- name: def.name,
260
- file: def.file,
261
- loc: { line: def.line || 0, column: def.column || 0 }
262
- };
263
- if (includeProps && def.data_json) {
264
- try {
265
- const data = JSON.parse(def.data_json);
266
- definition.props = data.props || [];
267
- } catch {
268
- definition.props = [];
269
- }
270
- }
271
- if (includeUsages) {
272
- definition.usages = [];
273
- const usages = project.db.db.prepare(
274
- `
275
- SELECT r.*, f.path as file, s.name as in_name
276
- FROM renders r
277
- JOIN files f ON r.file_id = f.id
278
- LEFT JOIN entities e ON r.parent_entity_id = e.id
279
- LEFT JOIN symbols s ON s.entity_id = e.id
280
- WHERE r.symbol_id = ? OR r.tag = ?
281
- `
282
- ).all(def.id, def.name);
283
- for (const usage of usages) {
284
- if (isExcluded(usage.file)) continue;
285
- definition.usages.push({
286
- kind: usage.kind === "jsx" ? "render" : "call",
287
- name: usage.tag,
288
- file: usage.file,
289
- loc: { line: usage.line || 0, column: usage.column || 0 },
290
- in: usage.in_name || "unknown"
291
- });
292
- }
293
- }
294
- definitions_results.push(definition);
295
- }
296
- if (includeUsages && definitions_results.length === 0) {
297
- const results = project.db.db.prepare(
298
- `
299
- SELECT r.*, f.path as file, s.name as in_name
300
- FROM renders r
301
- JOIN files f ON r.file_id = f.id
302
- LEFT JOIN entities e ON r.parent_entity_id = e.id
303
- LEFT JOIN symbols s ON s.entity_id = e.id
304
- WHERE r.tag = ?
305
- `
306
- ).all(query);
307
- for (const usage of results) {
308
- if (isExcluded(usage.file)) continue;
309
- externalUsages.push({
310
- kind: usage.kind === "jsx" ? "render" : "call",
311
- name: usage.tag,
312
- file: usage.file,
313
- loc: { line: usage.line || 0, column: usage.column || 0 },
314
- in: usage.in_name || "unknown"
315
- });
316
- }
317
- }
318
- return { definitions: definitions_results, externalUsages };
319
- }
320
- async getSymbolUsagesWithContext(projectPath, query, subProject, strict = true, contextLines = 2, exclude) {
321
- const symbolInfo = await this.findSymbol(
322
- projectPath,
323
- query,
324
- subProject,
325
- strict,
326
- false,
327
- true,
328
- exclude
329
- );
330
- const allUsages = [];
331
- symbolInfo.definitions.forEach((def) => {
332
- if (def.usages) allUsages.push(...def.usages);
333
- });
334
- if (symbolInfo.externalUsages) {
335
- allUsages.push(...symbolInfo.externalUsages);
336
- }
337
- const fileCache = /* @__PURE__ */ new Map();
338
- const results = [];
339
- const analysisPath = subProject ? path.resolve(projectPath, subProject) : projectPath;
340
- for (const usage of allUsages) {
341
- const fullPath = path.resolve(
342
- analysisPath,
343
- usage.file.startsWith("/") ? usage.file.slice(1) : usage.file
344
- );
345
- if (!fs.existsSync(fullPath)) continue;
346
- let lines = fileCache.get(fullPath);
347
- if (!lines) {
348
- lines = fs.readFileSync(fullPath, "utf-8").split("\n");
349
- fileCache.set(fullPath, lines);
350
- }
351
- const lineIdx = usage.loc.line - 1;
352
- const start = Math.max(0, lineIdx - contextLines);
353
- const end = Math.min(lines.length - 1, lineIdx + contextLines);
354
- const context = lines.slice(start, end + 1);
355
- results.push({
356
- file: usage.file,
357
- line: usage.loc.line,
358
- column: usage.loc.column,
359
- in: usage.in,
360
- kind: usage.kind,
361
- context
362
- });
363
- }
364
- return results;
365
- }
366
- async getPropDefinitions(projectPath, query, subProject) {
367
- const symbolInfo = await this.findSymbol(
368
- projectPath,
369
- query,
370
- subProject,
371
- true,
372
- // strict
373
- true,
374
- // includeProps
375
- false
376
- // includeUsages
377
- );
378
- return symbolInfo.definitions.map((def) => ({
379
- name: def.name,
380
- file: def.file,
381
- props: def.props || []
382
- }));
383
- }
384
- async findFiles(projectPath, pattern, subProject) {
385
- const project = await this.openProject(projectPath, subProject);
386
- const isGlob = /[*?[\]]/.test(pattern);
387
- const files = Object.keys(project.graph.files);
388
- if (isGlob) {
389
- const results2 = files.filter(
390
- (p) => minimatch(p, pattern, { dot: true, nocase: true }) || minimatch(path.basename(p), pattern, { dot: true, nocase: true })
391
- );
392
- return results2.sort();
393
- }
394
- const regex = new RegExp(pattern, "i");
395
- const results = files.filter(
396
- (p) => regex.test(p) || regex.test(path.basename(p))
397
- );
398
- return results.sort();
399
- }
400
- async getFileImports(projectPath, filePath, subProject) {
401
- const project = await this.openProject(projectPath, subProject);
402
- const normalizedPath = filePath.startsWith("/") ? filePath : `/${filePath}`;
403
- const file = project.graph.files[normalizedPath];
404
- if (!file) throw new Error(`File not found: ${normalizedPath}`);
405
- return file.import;
406
- }
407
- async getProjectTree(projectPath, subProject, maxDepth = 3) {
408
- const project = await this.openProject(projectPath, subProject);
409
- const root = { name: "/", children: [] };
410
- const files = Object.keys(project.graph.files).sort();
411
- for (const filePath of files) {
412
- const parts = filePath.split("/").filter(Boolean);
413
- let current = root;
414
- for (let i = 0; i < Math.min(parts.length, maxDepth); i++) {
415
- const part = parts[i];
416
- let node = current.children.find((c) => c.name === part);
417
- if (!node) {
418
- node = { name: part, children: [] };
419
- current.children.push(node);
420
- }
421
- current = node;
422
- }
423
- }
424
- const sortNodes = (node) => {
425
- node.children.sort((a, b) => a.name.localeCompare(b.name));
426
- for (const child of node.children) sortNodes(child);
427
- };
428
- sortNodes(root);
429
- return root;
430
- }
431
- async getComponentHierarchy(projectPath, componentName, subProject, depth = 2) {
432
- const project = await this.openProject(projectPath, subProject);
433
- const startComponents = project.db.db.prepare(
434
- `
435
- SELECT s.*, f.path as file, e.line, e.column, e.kind, e.type
436
- FROM symbols s
437
- JOIN entities e ON s.entity_id = e.id
438
- JOIN scopes sc ON e.scope_id = sc.id
439
- JOIN files f ON sc.file_id = f.id
440
- WHERE s.name = ? AND e.kind = 'component'
441
- `
442
- ).all(componentName);
443
- if (startComponents.length === 0) {
444
- return { error: `Component "${componentName}" not found.` };
445
- }
446
- const buildHierarchy = (symbolId, currentDepth, visited) => {
447
- const sym = project.db.db.prepare(`SELECT * FROM symbols WHERE id = ?`).get(symbolId);
448
- if (!sym || currentDepth > depth || visited.has(symbolId)) {
449
- return {
450
- id: symbolId,
451
- name: sym?.name || "unknown",
452
- children: [],
453
- status: "limit-or-circular"
454
- };
455
- }
456
- visited.add(symbolId);
457
- const children = project.db.db.prepare(
458
- `SELECT r.*, f.path as file FROM renders r JOIN files f ON r.file_id = f.id WHERE parent_entity_id = (SELECT entity_id FROM symbols WHERE id = ?)`
459
- ).all(symbolId);
460
- return {
461
- id: sym.id,
462
- name: sym.name,
463
- children: children.map((c) => {
464
- if (c.symbol_id) {
465
- return buildHierarchy(
466
- c.symbol_id,
467
- currentDepth + 1,
468
- new Set(visited)
469
- );
470
- }
471
- return {
472
- name: c.tag,
473
- status: "unresolved",
474
- kind: c.kind,
475
- index: c.render_index
476
- };
477
- })
478
- };
479
- };
480
- const renderedBy = project.db.db.prepare(
481
- `
482
- SELECT DISTINCT s.id, s.name, f.path as file
483
- FROM symbols s
484
- JOIN entities e ON s.entity_id = e.id
485
- JOIN scopes sc ON e.scope_id = sc.id
486
- JOIN files f ON sc.file_id = f.id
487
- JOIN renders r ON r.parent_entity_id = e.id
488
- WHERE r.tag = ? OR r.symbol_id IN (SELECT id FROM symbols WHERE name = ?)
489
- `
490
- ).all(componentName, componentName);
491
- return {
492
- component: componentName,
493
- hierarchies: startComponents.map(
494
- (c) => buildHierarchy(c.id, 0, /* @__PURE__ */ new Set())
495
- ),
496
- renderedBy: renderedBy.map((s) => ({
497
- id: s.id,
498
- name: s.name,
499
- file: s.file
500
- }))
501
- };
502
- }
503
- async getSymbolLocation(projectPath, query, subProject) {
504
- const project = await this.openProject(projectPath, subProject);
505
- const symbols = project.db.db.prepare(
506
- `
507
- SELECT s.id, s.name, f.path as file, e.line, e.column, e.kind, e.type
508
- FROM symbols s
509
- JOIN entities e ON s.entity_id = e.id
510
- JOIN scopes sc ON e.scope_id = sc.id
511
- JOIN files f ON sc.file_id = f.id
512
- WHERE s.name = ?
513
- `
514
- ).all(query);
515
- return symbols.map((s) => ({
516
- id: s.id,
517
- name: s.name,
518
- file: s.file,
519
- loc: { line: s.line || 0, column: s.column || 0 },
520
- kind: s.kind,
521
- type: s.type
522
- // Keep database type, UI expects this as symbol type
523
- }));
524
- }
525
- async getSymbolContent(projectPath, query, subProject) {
526
- const locations = await this.getSymbolLocation(
527
- projectPath,
528
- query,
529
- subProject
530
- );
531
- if (locations.length === 0)
532
- return { error: `Symbol "${query}" not found.` };
533
- const analysisPath = subProject ? path.resolve(projectPath, subProject) : projectPath;
534
- const results = [];
535
- for (const locInfo of locations) {
536
- const fullPath = path.resolve(
537
- analysisPath,
538
- locInfo.file.startsWith("/") ? locInfo.file.slice(1) : locInfo.file
539
- );
540
- if (!fs.existsSync(fullPath)) {
541
- results.push({ ...locInfo, error: "File not found on disk." });
542
- continue;
543
- }
544
- const content = fs.readFileSync(fullPath, "utf-8");
545
- const lines = content.split("\n");
546
- results.push({ ...locInfo, content: lines[locInfo.loc.line - 1] || "" });
547
- }
548
- return results;
549
- }
550
- async updateGraphPosition(projectPath, subProject, _positions, _contextId) {
551
- const project = await this.openProject(projectPath, subProject);
552
- if (!project.graph) return false;
553
- return true;
554
- }
555
- async addLabel(projectPath, id, label, subProject) {
556
- const project = await this.openProject(projectPath, subProject);
557
- const graph = project.graph;
558
- if (!graph.labels) graph.labels = {};
559
- if (!graph.labels[id]) graph.labels[id] = [];
560
- if (!graph.labels[id].includes(label)) {
561
- graph.labels[id].push(label);
562
- this._saveCache(project);
563
- }
564
- return graph.labels[id];
565
- }
566
- async removeLabel(projectPath, id, label, subProject) {
567
- const project = await this.openProject(projectPath, subProject);
568
- if (!project.graph || !project.graph.labels) return [];
569
- if (project.graph.labels[id]) {
570
- project.graph.labels[id] = project.graph.labels[id].filter(
571
- (l) => l !== label
572
- );
573
- if (project.graph.labels[id].length === 0)
574
- delete project.graph.labels[id];
575
- this._saveCache(project);
576
- }
577
- return project.graph.labels[id] || [];
578
- }
579
- async getLabels(projectPath, subProject) {
580
- const project = await this.openProject(projectPath, subProject);
581
- return project.graph?.labels || {};
582
- }
583
- async findEntitiesByLabel(projectPath, label, subProject) {
584
- const project = await this.openProject(projectPath, subProject);
585
- if (!project.graph || !project.graph.labels) return [];
586
- const ids = [];
587
- for (const [id, labels] of Object.entries(project.graph.labels)) {
588
- if (labels.includes(label)) ids.push(id);
589
- }
590
- return ids;
591
- }
592
- async listDirectory(projectPath, dirPath, subProject) {
593
- const project = await this.openProject(projectPath, subProject);
594
- const normalizedDir = dirPath.startsWith("/") ? dirPath : `/${dirPath}`;
595
- const filesInDir = /* @__PURE__ */ new Set();
596
- const subDirs = /* @__PURE__ */ new Set();
597
- for (const filePath of Object.keys(project.graph.files)) {
598
- if (filePath.startsWith(normalizedDir)) {
599
- const relative = filePath.slice(normalizedDir.length).replace(/^\//, "");
600
- const parts = relative.split("/");
601
- if (parts.length === 1 && parts[0] !== "") filesInDir.add(parts[0]);
602
- else if (parts.length > 1) subDirs.add(parts[0]);
603
- }
604
- }
605
- return {
606
- directories: Array.from(subDirs).sort(),
607
- files: Array.from(filesInDir).sort()
608
- };
609
- }
610
- async getFileOutline(projectPath, filePath, subProject) {
611
- const project = await this.openProject(projectPath, subProject);
612
- const normalizedPath = filePath.startsWith("/") ? filePath : `/${filePath}`;
613
- const file = project.graph.files[normalizedPath];
614
- if (!file) throw new Error(`File not found: ${normalizedPath}`);
615
- const outline = Object.values(file.var || {}).map((v) => ({
616
- id: v.id,
617
- name: getDisplayName(v.name),
618
- kind: v.kind,
619
- type: v.type,
620
- line: v.loc.line
621
- }));
622
- return outline.sort((a, b) => a.line - b.line);
623
- }
624
- async readFile(projectPath, filePath, subProject) {
625
- const analysisPath = subProject ? path.resolve(projectPath, subProject) : projectPath;
626
- const fullPath = path.resolve(
627
- analysisPath,
628
- filePath.startsWith("/") ? filePath.slice(1) : filePath
629
- );
630
- if (!fs.existsSync(fullPath))
631
- throw new Error(`File not found: ${filePath}`);
632
- return fs.readFileSync(fullPath, "utf-8");
633
- }
634
- async grepSearch(projectPath, pattern, subProject, exclude) {
635
- const project = await this.openProject(projectPath, subProject);
636
- const results = [];
637
- const regex = new RegExp(pattern, "i");
638
- const analysisPath = subProject ? path.resolve(projectPath, subProject) : projectPath;
639
- const isExcluded = (filePath) => {
640
- if (!exclude || exclude.length === 0) return false;
641
- return exclude.some(
642
- (pattern2) => minimatch(filePath, pattern2, { dot: true, nocase: true }) || minimatch(path.basename(filePath), pattern2, {
643
- dot: true,
644
- nocase: true
645
- })
646
- );
647
- };
648
- for (const filePath of Object.keys(project.graph.files)) {
649
- if (isExcluded(filePath)) continue;
650
- const fullPath = path.resolve(
651
- analysisPath,
652
- filePath.startsWith("/") ? filePath.slice(1) : filePath
653
- );
654
- if (fs.existsSync(fullPath)) {
655
- const content = fs.readFileSync(fullPath, "utf-8");
656
- const lines = content.split("\n");
657
- lines.forEach((line, index) => {
658
- if (regex.test(line))
659
- results.push({
660
- file: filePath,
661
- line: index + 1,
662
- content: line.trim()
663
- });
664
- });
665
- }
666
- if (results.length > 100) break;
667
- }
668
- return results;
669
- }
670
- async runShellCommand(projectPath, command, subProject) {
671
- const analysisPath = subProject ? path.resolve(projectPath, subProject) : projectPath;
672
- const dangerous = [
673
- "rm -rf",
674
- "mkfs",
675
- "dd if=",
676
- "> /dev/",
677
- "shutdown",
678
- "reboot"
679
- ];
680
- if (dangerous.some((c) => command.includes(c)))
681
- throw new Error(`Command "${command}" is restricted.`);
682
- try {
683
- const { stdout, stderr } = await execAsync(command, {
684
- cwd: analysisPath,
685
- timeout: 3e4,
686
- maxBuffer: 1024 * 1024
687
- });
688
- return { stdout, stderr, exitCode: 0 };
689
- } catch (e) {
690
- const err = e;
691
- return {
692
- error: err.message,
693
- stdout: err.stdout,
694
- stderr: err.stderr,
695
- exitCode: err.code ?? 1
696
- };
697
- }
698
- }
699
- async saveAppState(projectPath, state) {
700
- try {
701
- const dotDir = path.join(projectPath, ".react-map");
702
- if (!fs.existsSync(dotDir)) fs.mkdirSync(dotDir, { recursive: true });
703
- fs.writeFileSync(
704
- path.join(dotDir, "state.json"),
705
- JSON.stringify(state, null, 2)
706
- );
707
- return true;
708
- } catch (_error) {
709
- return false;
710
- }
711
- }
712
- async readAppState(projectPath) {
713
- const statePath = path.join(projectPath, ".react-map", "state.json");
714
- if (fs.existsSync(statePath)) {
715
- try {
716
- return JSON.parse(fs.readFileSync(statePath, "utf-8"));
717
- } catch (_e) {
718
- }
719
- }
720
- return null;
721
- }
722
- _saveCache(project) {
723
- const analysisPath = project.subProject ? path.resolve(project.projectPath, project.subProject) : project.projectPath;
724
- const cacheDir = path.join(analysisPath, ".react-map", "cache");
725
- const pathHash = Buffer.from(analysisPath).toString("hex").slice(0, 8);
726
- fs.writeFileSync(
727
- path.join(cacheDir, `${path.basename(analysisPath)}-${pathHash}.json`),
728
- JSON.stringify(project.graph, null, 2)
729
- );
730
- }
731
- async checkProjectStatus(directoryPath) {
732
- const status = {
733
- hasConfig: false,
734
- isMonorepo: false,
735
- projectType: "unknown",
736
- config: null,
737
- subProjects: []
738
- };
739
- try {
740
- const configPath = path.join(directoryPath, "react.map.config.json");
741
- if (fs.existsSync(configPath)) {
742
- status.hasConfig = true;
743
- try {
744
- status.config = JSON.parse(
745
- fs.readFileSync(configPath, "utf-8")
746
- );
747
- } catch (e) {
748
- console.error("Error reading config", e);
749
- }
750
- }
751
- const pnpmWorkspace = path.join(directoryPath, "pnpm-workspace.yaml");
752
- const packageJsonPath = path.join(directoryPath, "package.json");
753
- let workspacePatterns = [];
754
- if (fs.existsSync(pnpmWorkspace)) {
755
- status.isMonorepo = true;
756
- try {
757
- const doc = yaml.load(
758
- fs.readFileSync(pnpmWorkspace, "utf-8")
759
- );
760
- if (doc && doc.packages && Array.isArray(doc.packages)) {
761
- workspacePatterns = doc.packages;
762
- }
763
- } catch (e) {
764
- console.error("Error reading pnpm-workspace.yaml", e);
765
- }
766
- } else if (fs.existsSync(packageJsonPath)) {
767
- try {
768
- const pkg = JSON.parse(
769
- fs.readFileSync(packageJsonPath, "utf-8")
770
- );
771
- if (pkg.workspaces) {
772
- status.isMonorepo = true;
773
- if (Array.isArray(pkg.workspaces)) {
774
- workspacePatterns = pkg.workspaces;
775
- } else if (pkg.workspaces.packages && Array.isArray(pkg.workspaces.packages)) {
776
- workspacePatterns = pkg.workspaces.packages;
777
- }
778
- }
779
- } catch {
780
- }
781
- }
782
- if (status.isMonorepo && workspacePatterns.length > 0) {
783
- try {
784
- const entries = await fg(
785
- workspacePatterns.map(
786
- (p) => p.endsWith("/") ? `${p}package.json` : `${p}/package.json`
787
- ),
788
- {
789
- cwd: directoryPath,
790
- ignore: ["**/node_modules/**"],
791
- absolute: true
792
- }
793
- );
794
- const subProjects = [];
795
- for (const entry of entries) {
796
- try {
797
- const pkg = JSON.parse(
798
- fs.readFileSync(entry, "utf-8")
799
- );
800
- subProjects.push({
801
- name: pkg.name || path.basename(path.dirname(entry)),
802
- path: path.dirname(entry)
803
- });
804
- } catch {
805
- }
806
- }
807
- status.subProjects = subProjects;
808
- } catch (e) {
809
- console.error("Error resolving workspaces", e);
810
- }
811
- }
812
- if (fs.existsSync(path.join(directoryPath, "vite.config.ts")) || fs.existsSync(path.join(directoryPath, "vite.config.js"))) {
813
- status.projectType = "vite";
814
- } else if (fs.existsSync(path.join(directoryPath, "next.config.js"))) {
815
- status.projectType = "next";
816
- }
817
- } catch (error) {
818
- console.error("Error checking project status:", error);
819
- }
820
- return status;
821
- }
822
- async saveProjectConfig(directoryPath, config) {
823
- try {
824
- const configPath = path.join(directoryPath, "react.map.config.json");
825
- let oldConfig = null;
826
- if (fs.existsSync(configPath)) {
827
- try {
828
- oldConfig = JSON.parse(fs.readFileSync(configPath, "utf-8"));
829
- } catch (e) {
830
- console.error("Failed to read old config", e);
831
- }
832
- }
833
- const configContent = JSON.stringify(config, null, 2);
834
- fs.writeFileSync(configPath, configContent);
835
- const patternsChanged = JSON.stringify(oldConfig?.ignorePatterns) !== JSON.stringify(config.ignorePatterns);
836
- if (patternsChanged) {
837
- const cacheDir = path.join(directoryPath, ".react-map", "cache");
838
- if (fs.existsSync(cacheDir)) {
839
- const files = fs.readdirSync(cacheDir);
840
- for (const file of files) {
841
- if (file.endsWith(".json")) {
842
- fs.unlinkSync(path.join(cacheDir, file));
843
- }
844
- }
845
- console.log("Ignore patterns changed, cleared cache.");
846
- }
847
- }
848
- return true;
849
- } catch (error) {
850
- console.error("Error saving config:", error);
851
- return false;
852
- }
853
- }
854
- async gitStatus(projectRoot) {
855
- const git = simpleGit(projectRoot);
856
- const status = await git.status();
857
- return {
858
- current: status.current,
859
- tracking: status.tracking,
860
- detached: status.detached,
861
- files: status.files.map((f) => ({
862
- path: f.path,
863
- index: f.index,
864
- working_dir: f.working_dir
865
- })),
866
- staged: status.staged
867
- };
868
- }
869
- async gitLog(projectRoot, options = 50) {
870
- const git = simpleGit(projectRoot);
871
- let limit = 50;
872
- let pathFilter;
873
- if (typeof options === "number") {
874
- limit = options;
875
- } else {
876
- limit = options.limit || 50;
877
- pathFilter = options.path;
878
- }
879
- const logOptions = { maxCount: limit };
880
- if (pathFilter) {
881
- logOptions.file = pathFilter;
882
- }
883
- const log = await git.log(logOptions);
884
- return log.all.map((commit) => ({
885
- hash: commit.hash,
886
- date: commit.date,
887
- message: commit.message,
888
- author_name: commit.author_name,
889
- author_email: commit.author_email
890
- }));
891
- }
892
- async gitDiff(projectRoot, options) {
893
- const git = simpleGit(projectRoot);
894
- let rawDiff;
895
- const sanitizedFile = options.file?.startsWith("/") ? options.file.slice(1) : options.file;
896
- if (options.baseCommit && options.commit) {
897
- const args = [options.baseCommit, options.commit];
898
- if (sanitizedFile) {
899
- args.push("--", sanitizedFile);
900
- }
901
- rawDiff = await git.diff(args);
902
- } else if (options.commit && !options.staged) {
903
- const args = [options.commit];
904
- if (sanitizedFile) {
905
- args.push("--", sanitizedFile);
906
- }
907
- rawDiff = await git.show(args);
908
- } else {
909
- const args = [];
910
- if (options.staged) {
911
- args.push("--staged");
912
- }
913
- if (sanitizedFile) {
914
- args.push("--", sanitizedFile);
915
- }
916
- rawDiff = await git.diff(args);
917
- }
918
- return parseRawDiff(rawDiff, sanitizedFile);
919
- }
920
- async gitAnalyzeCommit(projectRoot, commitHash, subPath) {
921
- const git = simpleGit(projectRoot);
922
- const resolvedHash = await git.revparse([commitHash]);
923
- const relativeSubPath = subPath ? path.isAbsolute(subPath) ? path.relative(projectRoot, subPath) : subPath : void 0;
924
- const cacheKey = relativeSubPath ? `${resolvedHash}-${relativeSubPath.replace(/[/\\]/g, "_")}` : resolvedHash;
925
- const commitCacheDir = path.join(
926
- projectRoot,
927
- ".react-map",
928
- "cache",
929
- "commits"
930
- );
931
- const sqlitePath = path.join(commitCacheDir, `${cacheKey}.sqlite`);
932
- if (fs.existsSync(sqlitePath)) {
933
- const sqlite = new SqliteDB(sqlitePath);
934
- const data = sqlite.getAllData();
935
- sqlite.close();
936
- return data;
937
- }
938
- if (!fs.existsSync(commitCacheDir)) {
939
- fs.mkdirSync(commitCacheDir, { recursive: true });
940
- }
941
- const tempDir = tmp.dirSync({ unsafeCleanup: true });
942
- try {
943
- await new Promise((resolve, reject) => {
944
- exec(
945
- `git archive ${resolvedHash} | tar -x -C "${tempDir.name}"`,
946
- { cwd: projectRoot },
947
- (error) => {
948
- if (error) reject(error);
949
- else resolve();
950
- }
951
- );
952
- });
953
- const analysisPath = relativeSubPath ? path.join(tempDir.name, relativeSubPath) : tempDir.name;
954
- const configPath = path.join(projectRoot, "react.map.config.json");
955
- let ignorePatterns = void 0;
956
- if (fs.existsSync(configPath)) {
957
- try {
958
- const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
959
- ignorePatterns = config.ignorePatterns;
960
- } catch (e) {
961
- console.warn("Failed to load config for git analysis", e);
962
- }
963
- }
964
- await analyzeProject(analysisPath, void 0, ignorePatterns, sqlitePath);
965
- const sqlite = new SqliteDB(sqlitePath);
966
- const data = sqlite.getAllData();
967
- sqlite.close();
968
- return data;
969
- } finally {
970
- tempDir.removeCallback();
971
- }
972
- }
973
- async getProjectIcon(projectRoot) {
974
- try {
975
- const localIcons = [
976
- "favicon.ico",
977
- "logo.svg",
978
- "logo.png",
979
- "vite.svg",
980
- "public/favicon.ico",
981
- "public/logo.svg",
982
- "public/logo.png",
983
- "public/vite.svg"
984
- ];
985
- for (const icon of localIcons) {
986
- const iconPath = path.join(projectRoot, icon);
987
- if (fs.existsSync(iconPath)) {
988
- const buffer = fs.readFileSync(iconPath);
989
- const ext = path.extname(icon).toLowerCase();
990
- const mimeType = ext === ".svg" ? "image/svg+xml" : ext === ".ico" ? "image/x-icon" : `image/${ext.slice(1)}`;
991
- return `data:${mimeType};base64,${buffer.toString("base64")}`;
992
- }
993
- }
994
- if (fs.existsSync(path.join(projectRoot, ".git"))) {
995
- const git = simpleGit(projectRoot);
996
- try {
997
- const remotes = await git.getRemotes(true);
998
- const origin = remotes.find((r) => r.name === "origin") || remotes[0];
999
- if (origin && origin.refs.fetch) {
1000
- const url = origin.refs.fetch;
1001
- const match = url.match(/github\.com[/:]([^/]+)\//);
1002
- if (match && match[1]) {
1003
- const owner = match[1];
1004
- return `https://github.com/${owner}.png`;
1005
- }
1006
- }
1007
- } catch (e) {
1008
- console.warn("Failed to get git remotes", e);
1009
- }
1010
- }
1011
- return null;
1012
- } catch (e) {
1013
- console.error("Failed to get project icon", e);
1014
- return null;
1015
- }
1016
- }
1017
- async writeFile(projectRoot, filePath, content) {
1018
- const absolutePath = path.resolve(projectRoot, filePath);
1019
- if (!absolutePath.startsWith(path.resolve(projectRoot))) {
1020
- throw new Error("Path is outside of project root");
1021
- }
1022
- try {
1023
- fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
1024
- fs.writeFileSync(absolutePath, content, "utf-8");
1025
- return true;
1026
- } catch (error) {
1027
- console.error(`Error writing file ${filePath}:`, error);
1028
- return false;
1029
- }
1030
- }
1031
- async replaceFileContent(projectRoot, filePath, oldString, newString) {
1032
- const absolutePath = path.resolve(projectRoot, filePath);
1033
- if (!absolutePath.startsWith(path.resolve(projectRoot))) {
1034
- throw new Error("Path is outside of project root");
1035
- }
1036
- try {
1037
- if (!fs.existsSync(absolutePath)) {
1038
- throw new Error(`File not found: ${filePath}`);
1039
- }
1040
- const content = fs.readFileSync(absolutePath, "utf-8");
1041
- if (!content.includes(oldString)) {
1042
- throw new Error(`Old string not found in ${filePath}`);
1043
- }
1044
- const newContent = content.replace(oldString, newString);
1045
- fs.writeFileSync(absolutePath, newContent, "utf-8");
1046
- return true;
1047
- } catch (error) {
1048
- console.error(`Error replacing content in ${filePath}:`, error);
1049
- throw error;
1050
- }
1051
- }
1052
- async multiReplaceFileContent(projectRoot, filePath, replacements) {
1053
- const absolutePath = path.resolve(projectRoot, filePath);
1054
- if (!absolutePath.startsWith(path.resolve(projectRoot))) {
1055
- throw new Error("Path is outside of project root");
1056
- }
1057
- try {
1058
- if (!fs.existsSync(absolutePath)) {
1059
- throw new Error(`File not found: ${filePath}`);
1060
- }
1061
- let content = fs.readFileSync(absolutePath, "utf-8");
1062
- for (const { oldString, newString } of replacements) {
1063
- if (!content.includes(oldString)) {
1064
- throw new Error(`Old string not found in ${filePath}`);
1065
- }
1066
- content = content.replace(oldString, newString);
1067
- }
1068
- fs.writeFileSync(absolutePath, content, "utf-8");
1069
- return true;
1070
- } catch (error) {
1071
- console.error(`Error in multi-replace for ${filePath}:`, error);
1072
- throw error;
1073
- }
1074
- }
1075
- async closeAll() {
1076
- for (const project of this.projects.values()) {
1077
- if (project.subscription) await project.subscription.unsubscribe();
1078
- if (project.db) project.db.close();
1079
- }
1080
- this.projects.clear();
1081
- }
1082
- };
1083
-
1084
- // src/server.ts
1085
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
1086
- import {
1087
- CallToolRequestSchema,
1088
- ListToolsRequestSchema
1089
- } from "@modelcontextprotocol/sdk/types.js";
1090
- import {
1091
- getDisplayName as getDisplayName2
1092
- } from "@nexiq/shared";
1093
- import { WebSocketServer } from "ws";
1094
- import { minimatch as minimatch2 } from "minimatch";
1095
- import path2 from "path";
1096
- var DEFAULT_EXCLUDES = [
1097
- "**/node_modules/**",
1098
- "**/dist/**",
1099
- "**/build/**",
1100
- "**/test/**",
1101
- "**/__tests__/**",
1102
- "**/*.test.*",
1103
- "**/__snapshots__/**",
1104
- "**/.react-map/**"
1105
- ];
1106
- var BackendServer = class {
1107
- constructor(projectManager, port = 3030) {
1108
- this.projectManager = projectManager;
1109
- this.port = port;
1110
- this.mcpServer = new Server(
1111
- {
1112
- name: "react-map-mcp",
1113
- version: "0.2.0"
1114
- },
1115
- {
1116
- capabilities: {
1117
- tools: {}
1118
- }
1119
- }
1120
- );
1121
- this.setupMcpHandlers();
1122
- }
1123
- mcpServer;
1124
- wss = null;
1125
- uiConnections = 0;
1126
- mcpConnected = false;
1127
- exitTimeout = null;
1128
- setupMcpHandlers() {
1129
- this.mcpServer.setRequestHandler(ListToolsRequestSchema, async () => {
1130
- const baseTools = [
1131
- {
1132
- name: "open_project",
1133
- description: "Open a project and start analysis. Returns project status.",
1134
- inputSchema: {
1135
- type: "object",
1136
- properties: {
1137
- projectPath: {
1138
- type: "string",
1139
- description: "Absolute path to the project root"
1140
- },
1141
- subProject: {
1142
- type: "string",
1143
- description: "Optional sub-project path for monorepos"
1144
- }
1145
- },
1146
- required: ["projectPath"]
1147
- }
1148
- },
1149
- {
1150
- name: "get_symbol_info",
1151
- description: "Get detailed information about a symbol (component or hook), including its definition and all usages/call sites across the project.",
1152
- inputSchema: {
1153
- type: "object",
1154
- properties: {
1155
- projectPath: {
1156
- type: "string",
1157
- description: "Absolute path to the project root"
1158
- },
1159
- subProject: {
1160
- type: "string",
1161
- description: "Optional sub-project path"
1162
- },
1163
- query: {
1164
- type: "string",
1165
- description: "The name of the component or hook to find"
1166
- },
1167
- strict: {
1168
- type: "boolean",
1169
- description: "If true, only return symbols that exactly match the query. Defaults to true."
1170
- },
1171
- props: {
1172
- type: "boolean",
1173
- description: "If true, include props in the definition. Defaults to false."
1174
- },
1175
- usages: {
1176
- type: "boolean",
1177
- description: "If true, include usages across the project. Defaults to false."
1178
- },
1179
- loc: {
1180
- type: "boolean",
1181
- description: "If true, include location information (line, column). Defaults to false."
1182
- },
1183
- exclude: {
1184
- type: "array",
1185
- items: { type: "string" },
1186
- description: "List of glob patterns to exclude from results (e.g. ['**/test/**', '**/*.test.tsx'])."
1187
- },
1188
- fields: {
1189
- type: "array",
1190
- items: { type: "string" },
1191
- description: "Optional list of fields to return (e.g., ['definitions']). Omit to return all fields."
1192
- }
1193
- },
1194
- required: ["projectPath", "query"]
1195
- }
1196
- },
1197
- {
1198
- name: "get_symbol_usages_with_context",
1199
- description: "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.",
1200
- inputSchema: {
1201
- type: "object",
1202
- properties: {
1203
- projectPath: {
1204
- type: "string",
1205
- description: "Absolute path to the project root"
1206
- },
1207
- subProject: {
1208
- type: "string",
1209
- description: "Optional sub-project path"
1210
- },
1211
- query: {
1212
- type: "string",
1213
- description: "The name of the component or hook to find"
1214
- },
1215
- strict: {
1216
- type: "boolean",
1217
- description: "If true, only return symbols that exactly match the query. Defaults to true."
1218
- },
1219
- contextLines: {
1220
- type: "number",
1221
- description: "Number of context lines to show around the match. Defaults to 2."
1222
- },
1223
- exclude: {
1224
- type: "array",
1225
- items: { type: "string" },
1226
- description: "List of glob patterns to exclude from results (e.g. ['**/test/**', '**/*.test.tsx'])."
1227
- },
1228
- fields: {
1229
- type: "array",
1230
- items: { type: "string" },
1231
- description: "Optional list of fields to return. Omit to return all fields."
1232
- }
1233
- },
1234
- required: ["projectPath", "query"]
1235
- }
1236
- },
1237
- {
1238
- name: "get_prop_definitions",
1239
- description: "Get the prop definitions for a component. Returns a clean summary of props (name, type, required, documentation).",
1240
- inputSchema: {
1241
- type: "object",
1242
- properties: {
1243
- projectPath: {
1244
- type: "string",
1245
- description: "Absolute path to the project root"
1246
- },
1247
- subProject: {
1248
- type: "string",
1249
- description: "Optional sub-project path"
1250
- },
1251
- componentName: {
1252
- type: "string",
1253
- description: "The name of the component"
1254
- },
1255
- fields: {
1256
- type: "array",
1257
- items: { type: "string" },
1258
- description: "Optional list of fields to return. Omit to return all fields."
1259
- }
1260
- },
1261
- required: ["projectPath", "componentName"]
1262
- }
1263
- },
1264
- {
1265
- name: "find_files",
1266
- description: "Search for files by name or pattern (glob or regex) across the project.",
1267
- inputSchema: {
1268
- type: "object",
1269
- properties: {
1270
- projectPath: {
1271
- type: "string",
1272
- description: "Absolute path to the project root"
1273
- },
1274
- subProject: {
1275
- type: "string",
1276
- description: "Optional sub-project path"
1277
- },
1278
- pattern: {
1279
- type: "string",
1280
- description: "Pattern to match against file paths or basenames (e.g., 'App*', 'src/**/*.tsx', 'auth')"
1281
- },
1282
- fields: {
1283
- type: "array",
1284
- items: { type: "string" },
1285
- description: "Optional list of fields to return. Omit to return all fields."
1286
- }
1287
- },
1288
- required: ["projectPath", "pattern"]
1289
- }
1290
- },
1291
- {
1292
- name: "get_file_imports",
1293
- description: "Get the list of imports for a specific file from the analysis data. More token-efficient than reading the full file.",
1294
- inputSchema: {
1295
- type: "object",
1296
- properties: {
1297
- projectPath: {
1298
- type: "string",
1299
- description: "Absolute path to the project root"
1300
- },
1301
- subProject: {
1302
- type: "string",
1303
- description: "Optional sub-project path"
1304
- },
1305
- filePath: {
1306
- type: "string",
1307
- description: "Relative path from project root"
1308
- },
1309
- fields: {
1310
- type: "array",
1311
- items: { type: "string" },
1312
- description: "Optional list of fields to return. Omit to return all fields."
1313
- }
1314
- },
1315
- required: ["projectPath", "filePath"]
1316
- }
1317
- },
1318
- {
1319
- name: "get_project_tree",
1320
- description: "Get a tree structure of the project directories and files up to a specified depth.",
1321
- inputSchema: {
1322
- type: "object",
1323
- properties: {
1324
- projectPath: {
1325
- type: "string",
1326
- description: "Absolute path to the project root"
1327
- },
1328
- subProject: {
1329
- type: "string",
1330
- description: "Optional sub-project path"
1331
- },
1332
- maxDepth: {
1333
- type: "number",
1334
- description: "Maximum depth to traverse (default: 3)"
1335
- },
1336
- fields: {
1337
- type: "array",
1338
- items: { type: "string" },
1339
- description: "Optional list of fields to return. Omit to return all fields."
1340
- }
1341
- },
1342
- required: ["projectPath"]
1343
- }
1344
- },
1345
- {
1346
- name: "list_files",
1347
- description: "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.",
1348
- inputSchema: {
1349
- type: "object",
1350
- properties: {
1351
- projectPath: {
1352
- type: "string",
1353
- description: "Absolute path to the project root"
1354
- },
1355
- subProject: {
1356
- type: "string",
1357
- description: "Optional sub-project path"
1358
- },
1359
- fields: {
1360
- type: "array",
1361
- items: { type: "string" },
1362
- description: "Optional list of fields to return for each file (e.g., ['path']). Omit to return all fields."
1363
- },
1364
- exclude: {
1365
- type: "array",
1366
- items: { type: "string" },
1367
- description: "List of glob patterns to exclude from results (e.g. ['**/test/**', '**/*.test.tsx'])."
1368
- }
1369
- },
1370
- required: ["projectPath"]
1371
- }
1372
- },
1373
- {
1374
- name: "get_component_hierarchy",
1375
- description: "Get the render hierarchy starting from a specific component (who it renders and who renders it).",
1376
- inputSchema: {
1377
- type: "object",
1378
- properties: {
1379
- projectPath: {
1380
- type: "string",
1381
- description: "Absolute path to the project root"
1382
- },
1383
- subProject: {
1384
- type: "string",
1385
- description: "Optional sub-project path"
1386
- },
1387
- componentName: {
1388
- type: "string",
1389
- description: "The name of the component to start from"
1390
- },
1391
- depth: {
1392
- type: "number",
1393
- description: "How many levels up and down to traverse (default: 2)"
1394
- },
1395
- fields: {
1396
- type: "array",
1397
- items: { type: "string" },
1398
- description: "Optional list of fields to return. Omit to return all fields."
1399
- }
1400
- },
1401
- required: ["projectPath", "componentName"]
1402
- }
1403
- },
1404
- {
1405
- name: "get_symbol_location",
1406
- description: "Get the exact file and location (line/column) of a symbol's definition, including its body scope if it's a function or hook.",
1407
- inputSchema: {
1408
- type: "object",
1409
- properties: {
1410
- projectPath: {
1411
- type: "string",
1412
- description: "Absolute path to the project root"
1413
- },
1414
- subProject: {
1415
- type: "string",
1416
- description: "Optional sub-project path"
1417
- },
1418
- query: {
1419
- type: "string",
1420
- description: "The name of the symbol to find"
1421
- },
1422
- fields: {
1423
- type: "array",
1424
- items: { type: "string" },
1425
- description: "Optional list of fields to return. Omit to return all fields."
1426
- }
1427
- },
1428
- required: ["projectPath", "query"]
1429
- }
1430
- },
1431
- {
1432
- name: "get_symbol_content",
1433
- description: "Get the source code content of a symbol's definition.",
1434
- inputSchema: {
1435
- type: "object",
1436
- properties: {
1437
- projectPath: {
1438
- type: "string",
1439
- description: "Absolute path to the project root"
1440
- },
1441
- subProject: {
1442
- type: "string",
1443
- description: "Optional sub-project path"
1444
- },
1445
- query: {
1446
- type: "string",
1447
- description: "The name of the symbol to find"
1448
- },
1449
- fields: {
1450
- type: "array",
1451
- items: { type: "string" },
1452
- description: "Optional list of fields to return. Omit to return all fields."
1453
- }
1454
- },
1455
- required: ["projectPath", "query"]
1456
- }
1457
- },
1458
- {
1459
- name: "add_label",
1460
- description: "Add a persistent label/tag to a file, folder, or variable ID for instant retrieval later.",
1461
- inputSchema: {
1462
- type: "object",
1463
- properties: {
1464
- projectPath: { type: "string" },
1465
- subProject: { type: "string" },
1466
- id: {
1467
- type: "string",
1468
- description: "The ID or path to label (e.g. file path or graph ID)"
1469
- },
1470
- label: { type: "string", description: "The label to attach" }
1471
- },
1472
- required: ["projectPath", "id", "label"]
1473
- }
1474
- },
1475
- {
1476
- name: "list_labels",
1477
- description: "List all persistent labels in the project.",
1478
- inputSchema: {
1479
- type: "object",
1480
- properties: {
1481
- projectPath: { type: "string" },
1482
- subProject: { type: "string" }
1483
- },
1484
- required: ["projectPath"]
1485
- }
1486
- },
1487
- {
1488
- name: "search_by_label",
1489
- description: "Find entities (files, folders, variables) by their associated label.",
1490
- inputSchema: {
1491
- type: "object",
1492
- properties: {
1493
- projectPath: { type: "string" },
1494
- subProject: { type: "string" },
1495
- label: { type: "string" }
1496
- },
1497
- required: ["projectPath", "label"]
1498
- }
1499
- },
1500
- {
1501
- name: "list_directory",
1502
- description: "List files and subdirectories in a specific folder. Use this to explore the project structure efficiently.",
1503
- inputSchema: {
1504
- type: "object",
1505
- properties: {
1506
- projectPath: { type: "string" },
1507
- subProject: { type: "string" },
1508
- dirPath: {
1509
- type: "string",
1510
- description: "Relative path from project root"
1511
- }
1512
- },
1513
- required: ["projectPath", "dirPath"]
1514
- }
1515
- },
1516
- {
1517
- name: "get_file_outline",
1518
- description: "Get a structured outline of a single file, including components, hooks, states, and their line numbers.",
1519
- inputSchema: {
1520
- type: "object",
1521
- properties: {
1522
- projectPath: { type: "string" },
1523
- subProject: { type: "string" },
1524
- filePath: {
1525
- type: "string",
1526
- description: "Relative path from project root"
1527
- },
1528
- fields: {
1529
- type: "array",
1530
- items: { type: "string" },
1531
- description: "Optional list of fields to return (e.g., ['name', 'line']). Omit to return all fields."
1532
- }
1533
- },
1534
- required: ["projectPath", "filePath"]
1535
- }
1536
- },
1537
- {
1538
- name: "read_file",
1539
- description: "Read the full content of a file.",
1540
- inputSchema: {
1541
- type: "object",
1542
- properties: {
1543
- projectPath: { type: "string" },
1544
- subProject: { type: "string" },
1545
- filePath: {
1546
- type: "string",
1547
- description: "Relative path from project root"
1548
- }
1549
- },
1550
- required: ["projectPath", "filePath"]
1551
- }
1552
- },
1553
- {
1554
- name: "grep_search",
1555
- description: "Search for a pattern across all files in the project.",
1556
- inputSchema: {
1557
- type: "object",
1558
- properties: {
1559
- projectPath: { type: "string" },
1560
- subProject: { type: "string" },
1561
- pattern: {
1562
- type: "string",
1563
- description: "Regex pattern to search for"
1564
- },
1565
- exclude: {
1566
- type: "array",
1567
- items: { type: "string" },
1568
- description: "List of glob patterns to exclude from results (e.g. ['**/test/**', '**/*.test.tsx'])."
1569
- }
1570
- },
1571
- required: ["projectPath", "pattern"]
1572
- }
1573
- },
1574
- {
1575
- name: "run_shell_command",
1576
- description: "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.",
1577
- inputSchema: {
1578
- type: "object",
1579
- properties: {
1580
- projectPath: { type: "string" },
1581
- subProject: { type: "string" },
1582
- command: {
1583
- type: "string",
1584
- description: "The command to execute"
1585
- }
1586
- },
1587
- required: ["projectPath", "command"]
1588
- }
1589
- },
1590
- {
1591
- name: "write_file",
1592
- description: "Write content to a file. Useful for creating or overwriting files.",
1593
- inputSchema: {
1594
- type: "object",
1595
- properties: {
1596
- projectPath: { type: "string" },
1597
- subProject: { type: "string" },
1598
- filePath: {
1599
- type: "string",
1600
- description: "Relative path from project root"
1601
- },
1602
- content: { type: "string" }
1603
- },
1604
- required: ["projectPath", "filePath", "content"]
1605
- }
1606
- },
1607
- {
1608
- name: "replace_file_content",
1609
- description: "Replace a string in a file with another string.",
1610
- inputSchema: {
1611
- type: "object",
1612
- properties: {
1613
- projectPath: { type: "string" },
1614
- subProject: { type: "string" },
1615
- filePath: {
1616
- type: "string",
1617
- description: "Relative path from project root"
1618
- },
1619
- oldString: { type: "string" },
1620
- newString: { type: "string" }
1621
- },
1622
- required: ["projectPath", "filePath", "oldString", "newString"]
1623
- }
1624
- },
1625
- {
1626
- name: "multi_replace_file_content",
1627
- description: "Perform multiple string replacements in a single file.",
1628
- inputSchema: {
1629
- type: "object",
1630
- properties: {
1631
- projectPath: { type: "string" },
1632
- subProject: { type: "string" },
1633
- filePath: {
1634
- type: "string",
1635
- description: "Relative path from project root"
1636
- },
1637
- replacements: {
1638
- type: "array",
1639
- items: {
1640
- type: "object",
1641
- properties: {
1642
- oldString: { type: "string" },
1643
- newString: { type: "string" }
1644
- },
1645
- required: ["oldString", "newString"]
1646
- }
1647
- }
1648
- },
1649
- required: ["projectPath", "filePath", "replacements"]
1650
- }
1651
- }
1652
- ];
1653
- const extensions = this.projectManager.getAllExtensions();
1654
- const extensionTools = extensions.flatMap(
1655
- (ext) => (ext.mcpTools || []).map((tool) => ({
1656
- name: `${ext.id}_${tool.name}`,
1657
- description: tool.description,
1658
- inputSchema: tool.inputSchema
1659
- }))
1660
- );
1661
- return {
1662
- tools: [...baseTools, ...extensionTools]
1663
- };
1664
- });
1665
- this.mcpServer.setRequestHandler(CallToolRequestSchema, async (request) => {
1666
- const { name, arguments: args } = request.params;
1667
- try {
1668
- const result = await this.handleCallTool({
1669
- name,
1670
- args
1671
- });
1672
- return result;
1673
- } catch (error) {
1674
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
1675
- return {
1676
- isError: true,
1677
- content: [{ type: "text", text: errorMessage }]
1678
- };
1679
- }
1680
- });
1681
- }
1682
- async handleCallTool(toolCall) {
1683
- const extensions = this.projectManager.getAllExtensions();
1684
- for (const ext of extensions) {
1685
- if (toolCall.name.startsWith(`${ext.id}_`)) {
1686
- const toolName = toolCall.name.replace(`${ext.id}_`, "");
1687
- const tool = (ext.mcpTools || []).find((t) => t.name === toolName);
1688
- if (tool) {
1689
- const result = await tool.handler({
1690
- ...toolCall.args,
1691
- projectManager: this.projectManager
1692
- });
1693
- return {
1694
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1695
- };
1696
- }
1697
- }
1698
- }
1699
- return await this.handleKnownToolCall(toolCall);
1700
- }
1701
- async handleKnownToolCall(knownCall) {
1702
- switch (knownCall.name) {
1703
- case "open_project": {
1704
- const { projectPath, subProject } = knownCall.args;
1705
- await this.projectManager.openProject(projectPath, subProject);
1706
- return {
1707
- content: [
1708
- {
1709
- type: "text",
1710
- text: `Project ${subProject || projectPath} opened and analyzed successfully.`
1711
- }
1712
- ]
1713
- };
1714
- }
1715
- case "get_symbol_info": {
1716
- const {
1717
- projectPath,
1718
- subProject,
1719
- query,
1720
- strict,
1721
- props,
1722
- usages,
1723
- loc,
1724
- exclude,
1725
- fields
1726
- } = knownCall.args;
1727
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1728
- const includeUsage = usages === true;
1729
- const results = await this.projectManager.findSymbol(
1730
- resolvedPath,
1731
- query,
1732
- subProject,
1733
- strict !== false,
1734
- // Default to strict true
1735
- props === true,
1736
- // Default to false
1737
- includeUsage,
1738
- exclude || DEFAULT_EXCLUDES
1739
- );
1740
- const includeLoc = loc === true;
1741
- const processItem = (item) => {
1742
- const processed = { ...item };
1743
- if (!includeLoc) {
1744
- delete processed.loc;
1745
- }
1746
- if (processed.usages) {
1747
- processed.usages = processed.usages.map((u) => processItem(u));
1748
- }
1749
- return processed;
1750
- };
1751
- const result = {
1752
- definitions: results.definitions.map((d) => processItem(d))
1753
- };
1754
- if (includeUsage) {
1755
- result.externalUsages = (results.externalUsages ?? []).map(
1756
- (u) => processItem(u)
1757
- );
1758
- }
1759
- return {
1760
- content: [
1761
- {
1762
- type: "text",
1763
- text: JSON.stringify(this.filterFields(result, fields), null, 2)
1764
- }
1765
- ]
1766
- };
1767
- }
1768
- case "get_symbol_usages_with_context": {
1769
- const {
1770
- projectPath,
1771
- subProject,
1772
- query,
1773
- strict,
1774
- contextLines,
1775
- exclude,
1776
- fields
1777
- } = knownCall.args;
1778
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1779
- const results = await this.projectManager.getSymbolUsagesWithContext(
1780
- resolvedPath,
1781
- query,
1782
- subProject,
1783
- strict !== false,
1784
- contextLines ?? 2,
1785
- exclude || DEFAULT_EXCLUDES
1786
- );
1787
- return {
1788
- content: [
1789
- {
1790
- type: "text",
1791
- text: JSON.stringify(this.filterFields(results, fields), null, 2)
1792
- }
1793
- ]
1794
- };
1795
- }
1796
- case "get_prop_definitions": {
1797
- const { projectPath, subProject, componentName, fields } = knownCall.args;
1798
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1799
- const results = await this.projectManager.getPropDefinitions(
1800
- resolvedPath,
1801
- componentName,
1802
- subProject
1803
- );
1804
- return {
1805
- content: [
1806
- {
1807
- type: "text",
1808
- text: JSON.stringify(this.filterFields(results, fields), null, 2)
1809
- }
1810
- ]
1811
- };
1812
- }
1813
- case "find_files": {
1814
- const { projectPath, subProject, pattern, fields } = knownCall.args;
1815
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1816
- const results = await this.projectManager.findFiles(
1817
- resolvedPath,
1818
- pattern,
1819
- subProject
1820
- );
1821
- return {
1822
- content: [
1823
- {
1824
- type: "text",
1825
- text: JSON.stringify(this.filterFields(results, fields), null, 2)
1826
- }
1827
- ]
1828
- };
1829
- }
1830
- case "get_file_imports": {
1831
- const { projectPath, subProject, filePath, fields } = knownCall.args;
1832
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1833
- const results = await this.projectManager.getFileImports(
1834
- resolvedPath,
1835
- filePath,
1836
- subProject
1837
- );
1838
- return {
1839
- content: [
1840
- {
1841
- type: "text",
1842
- text: JSON.stringify(this.filterFields(results, fields), null, 2)
1843
- }
1844
- ]
1845
- };
1846
- }
1847
- case "get_project_tree": {
1848
- const { projectPath, subProject, maxDepth, fields } = knownCall.args;
1849
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1850
- const results = await this.projectManager.getProjectTree(
1851
- resolvedPath,
1852
- subProject,
1853
- maxDepth
1854
- );
1855
- return {
1856
- content: [
1857
- {
1858
- type: "text",
1859
- text: JSON.stringify(this.filterFields(results, fields), null, 2)
1860
- }
1861
- ]
1862
- };
1863
- }
1864
- case "list_files": {
1865
- const { projectPath, subProject, exclude, fields } = knownCall.args;
1866
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1867
- const project = await this.projectManager.openProject(
1868
- resolvedPath,
1869
- subProject
1870
- );
1871
- const excludePatterns = exclude || DEFAULT_EXCLUDES;
1872
- const isExcluded = (filePath) => {
1873
- return excludePatterns.some(
1874
- (pattern) => minimatch2(filePath, pattern, { dot: true, nocase: true }) || minimatch2(path2.basename(filePath), pattern, {
1875
- dot: true,
1876
- nocase: true
1877
- })
1878
- );
1879
- };
1880
- const files = Object.entries(project.graph.files).filter(
1881
- ([path3]) => !isExcluded(path3)
1882
- );
1883
- const totalFiles = files.length;
1884
- const MAX_FILES = 50;
1885
- const displayedFiles = files.slice(0, MAX_FILES);
1886
- let fileSummary;
1887
- if (totalFiles > MAX_FILES) {
1888
- fileSummary = displayedFiles.map(([path3]) => ({ path: path3 }));
1889
- } else {
1890
- fileSummary = displayedFiles.map(([path3, file]) => {
1891
- return {
1892
- path: path3,
1893
- exports: Object.values(file.var || {}).map((v) => ({
1894
- name: getDisplayName2(v.name),
1895
- kind: v.kind
1896
- }))
1897
- };
1898
- });
1899
- }
1900
- return {
1901
- content: [
1902
- {
1903
- type: "text",
1904
- text: JSON.stringify(
1905
- {
1906
- totalFiles,
1907
- displayedCount: fileSummary.length,
1908
- files: this.filterFields(fileSummary, fields),
1909
- hint: totalFiles > MAX_FILES ? `Project has ${totalFiles} files. Showing first ${MAX_FILES}. Use 'list_directory' to explore folders or 'find_files' to search for specific files.` : void 0
1910
- },
1911
- null,
1912
- 2
1913
- )
1914
- }
1915
- ]
1916
- };
1917
- }
1918
- case "get_component_hierarchy": {
1919
- const { projectPath, subProject, componentName, depth, fields } = knownCall.args;
1920
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1921
- const result = await this.projectManager.getComponentHierarchy(
1922
- resolvedPath,
1923
- componentName,
1924
- subProject,
1925
- depth
1926
- );
1927
- return {
1928
- content: [
1929
- {
1930
- type: "text",
1931
- text: JSON.stringify(this.filterFields(result, fields), null, 2)
1932
- }
1933
- ]
1934
- };
1935
- }
1936
- case "get_symbol_location": {
1937
- const { projectPath, subProject, query, fields } = knownCall.args;
1938
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1939
- const result = await this.projectManager.getSymbolLocation(
1940
- resolvedPath,
1941
- query,
1942
- subProject
1943
- );
1944
- return {
1945
- content: [
1946
- {
1947
- type: "text",
1948
- text: JSON.stringify(this.filterFields(result, fields), null, 2)
1949
- }
1950
- ]
1951
- };
1952
- }
1953
- case "get_symbol_content": {
1954
- const { projectPath, subProject, query, fields } = knownCall.args;
1955
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1956
- const result = await this.projectManager.getSymbolContent(
1957
- resolvedPath,
1958
- query,
1959
- subProject
1960
- );
1961
- return {
1962
- content: [
1963
- {
1964
- type: "text",
1965
- text: JSON.stringify(this.filterFields(result, fields), null, 2)
1966
- }
1967
- ]
1968
- };
1969
- }
1970
- case "add_label": {
1971
- const { projectPath, subProject, id, label } = knownCall.args;
1972
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1973
- const result = await this.projectManager.addLabel(
1974
- resolvedPath,
1975
- id,
1976
- label,
1977
- subProject
1978
- );
1979
- return {
1980
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1981
- };
1982
- }
1983
- case "list_labels": {
1984
- const { projectPath, subProject } = knownCall.args;
1985
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1986
- const result = await this.projectManager.getLabels(
1987
- resolvedPath,
1988
- subProject
1989
- );
1990
- return {
1991
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1992
- };
1993
- }
1994
- case "search_by_label": {
1995
- const { projectPath, subProject, label } = knownCall.args;
1996
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
1997
- const result = await this.projectManager.findEntitiesByLabel(
1998
- resolvedPath,
1999
- label,
2000
- subProject
2001
- );
2002
- return {
2003
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2004
- };
2005
- }
2006
- case "list_directory": {
2007
- const { projectPath, subProject, dirPath } = knownCall.args;
2008
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
2009
- const result = await this.projectManager.listDirectory(
2010
- resolvedPath,
2011
- dirPath,
2012
- subProject
2013
- );
2014
- return {
2015
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2016
- };
2017
- }
2018
- case "get_file_outline": {
2019
- const { projectPath, subProject, filePath, fields } = knownCall.args;
2020
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
2021
- const result = await this.projectManager.getFileOutline(
2022
- resolvedPath,
2023
- filePath,
2024
- subProject
2025
- );
2026
- return {
2027
- content: [
2028
- {
2029
- type: "text",
2030
- text: JSON.stringify(this.filterFields(result, fields), null, 2)
2031
- }
2032
- ]
2033
- };
2034
- }
2035
- case "read_file": {
2036
- const { projectPath, subProject, filePath } = knownCall.args;
2037
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
2038
- const result = await this.projectManager.readFile(
2039
- resolvedPath,
2040
- filePath,
2041
- subProject
2042
- );
2043
- return { content: [{ type: "text", text: result }] };
2044
- }
2045
- case "grep_search": {
2046
- const { projectPath, subProject, pattern, exclude } = knownCall.args;
2047
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
2048
- const result = await this.projectManager.grepSearch(
2049
- resolvedPath,
2050
- pattern,
2051
- subProject,
2052
- exclude || DEFAULT_EXCLUDES
2053
- );
2054
- return {
2055
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2056
- };
2057
- }
2058
- case "run_shell_command": {
2059
- const { projectPath, subProject, command } = knownCall.args;
2060
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
2061
- const result = await this.projectManager.runShellCommand(
2062
- resolvedPath,
2063
- command,
2064
- subProject
2065
- );
2066
- return {
2067
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2068
- };
2069
- }
2070
- case "write_file": {
2071
- const { projectPath, subProject, filePath, content } = knownCall.args;
2072
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
2073
- const success = await this.projectManager.writeFile(
2074
- resolvedPath,
2075
- filePath,
2076
- content
2077
- );
2078
- return {
2079
- content: [{ type: "text", text: JSON.stringify({ success }) }]
2080
- };
2081
- }
2082
- case "replace_file_content": {
2083
- const { projectPath, subProject, filePath, oldString, newString } = knownCall.args;
2084
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
2085
- const success = await this.projectManager.replaceFileContent(
2086
- resolvedPath,
2087
- filePath,
2088
- oldString,
2089
- newString
2090
- );
2091
- return {
2092
- content: [{ type: "text", text: JSON.stringify({ success }) }]
2093
- };
2094
- }
2095
- case "multi_replace_file_content": {
2096
- const { projectPath, subProject, filePath, replacements } = knownCall.args;
2097
- const resolvedPath = this.resolveProjectPath(projectPath, subProject);
2098
- const success = await this.projectManager.multiReplaceFileContent(
2099
- resolvedPath,
2100
- filePath,
2101
- replacements
2102
- );
2103
- return {
2104
- content: [{ type: "text", text: JSON.stringify({ success }) }]
2105
- };
2106
- }
2107
- default:
2108
- throw new Error(`Unknown tool: ${knownCall.name}`);
2109
- }
2110
- }
2111
- filterFields(data, fields) {
2112
- if (!fields || !data) return data;
2113
- if (Array.isArray(data)) {
2114
- return data.map(
2115
- (item) => this.filterFields(item, fields)
2116
- );
2117
- }
2118
- if (typeof data !== "object") return data;
2119
- const filtered = {};
2120
- const obj = data;
2121
- for (const field of fields) {
2122
- if (field in obj) {
2123
- filtered[field] = obj[field];
2124
- }
2125
- }
2126
- return filtered;
2127
- }
2128
- resolveProjectPath(projectPath, _subProject) {
2129
- if (projectPath === "." || projectPath === "/" || !projectPath) {
2130
- const projects = this.projectManager.getOpenProjectPaths();
2131
- if (projects.length > 0) {
2132
- return projects[0];
2133
- }
2134
- }
2135
- return projectPath;
2136
- }
2137
- sendResponse(ws, type, payload, requestId) {
2138
- ws.send(JSON.stringify({ type, payload, requestId }));
2139
- }
2140
- sendChunkedResponse(ws, type, payload, requestId) {
2141
- const data = JSON.stringify(payload);
2142
- const CHUNK_SIZE = 1024 * 1024;
2143
- if (data.length <= CHUNK_SIZE) {
2144
- this.sendResponse(ws, type, payload, requestId);
2145
- return;
2146
- }
2147
- const totalChunks = Math.ceil(data.length / CHUNK_SIZE);
2148
- for (let i = 0; i < totalChunks; i++) {
2149
- const chunk = data.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
2150
- ws.send(
2151
- JSON.stringify({
2152
- type: "chunked_response",
2153
- payload: {
2154
- chunk,
2155
- index: i,
2156
- total: totalChunks,
2157
- originalType: type
2158
- },
2159
- requestId
2160
- })
2161
- );
2162
- }
2163
- }
2164
- sendError(ws, message, requestId) {
2165
- ws.send(JSON.stringify({ type: "error", payload: { message }, requestId }));
2166
- }
2167
- startWebSocketServer() {
2168
- try {
2169
- this.wss = new WebSocketServer({
2170
- port: this.port,
2171
- maxPayload: 100 * 1024 * 1024,
2172
- // 100MB
2173
- perMessageDeflate: true
2174
- });
2175
- this.wss.on("error", (error) => {
2176
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
2177
- console.error(`WebSocket server error: ${errorMessage}`);
2178
- const err = error;
2179
- if (err.code === "EADDRINUSE") {
2180
- console.error(
2181
- `Port ${this.port} is already in use. This instance will proceed without a WebSocket server.`
2182
- );
2183
- this.wss = null;
2184
- }
2185
- });
2186
- console.error(`React Map backend started on ws://localhost:${this.port}`);
2187
- this.wss.on("connection", (ws) => {
2188
- this.uiConnections++;
2189
- console.error(
2190
- `UI connected via WebSocket (Active: ${this.uiConnections})`
2191
- );
2192
- this.checkExitCondition();
2193
- ws.on("close", () => {
2194
- this.uiConnections--;
2195
- console.error(`UI disconnected (Active: ${this.uiConnections})`);
2196
- this.checkExitCondition();
2197
- });
2198
- ws.on("message", async (message) => {
2199
- let currentRequestId;
2200
- try {
2201
- const data = JSON.parse(message.toString());
2202
- currentRequestId = data.requestId;
2203
- console.error(
2204
- `Received WebSocket message: ${data.type} (Request: ${data.requestId || "none"})`
2205
- );
2206
- switch (data.type) {
2207
- case "open_project": {
2208
- const { projectPath, subProject } = data.payload;
2209
- const project = await this.projectManager.openProject(
2210
- projectPath,
2211
- subProject
2212
- );
2213
- this.sendResponse(
2214
- ws,
2215
- "project_opened",
2216
- { sqlitePath: project.sqlitePath },
2217
- data.requestId
2218
- );
2219
- break;
2220
- }
2221
- case "update_graph_position": {
2222
- const { projectPath, subProject, positions, contextId } = data.payload;
2223
- const success = await this.projectManager.updateGraphPosition(
2224
- projectPath,
2225
- subProject,
2226
- positions,
2227
- contextId
2228
- );
2229
- this.sendResponse(
2230
- ws,
2231
- "position_updated",
2232
- { success },
2233
- data.requestId
2234
- );
2235
- break;
2236
- }
2237
- case "save_state": {
2238
- const { projectPath, state } = data.payload;
2239
- const success = await this.projectManager.saveAppState(
2240
- projectPath,
2241
- state
2242
- );
2243
- this.sendResponse(
2244
- ws,
2245
- "state_saved",
2246
- { success },
2247
- data.requestId
2248
- );
2249
- break;
2250
- }
2251
- case "read_state": {
2252
- const { projectPath } = data.payload;
2253
- const state = await this.projectManager.readAppState(projectPath);
2254
- this.sendResponse(ws, "state_data", state, data.requestId);
2255
- break;
2256
- }
2257
- case "check_project_status": {
2258
- const { projectPath } = data.payload;
2259
- const status = await this.projectManager.checkProjectStatus(projectPath);
2260
- this.sendResponse(ws, "project_status", status, data.requestId);
2261
- break;
2262
- }
2263
- case "save_project_config": {
2264
- const { projectPath, config } = data.payload;
2265
- const success = await this.projectManager.saveProjectConfig(
2266
- projectPath,
2267
- config
2268
- );
2269
- this.sendResponse(
2270
- ws,
2271
- "config_saved",
2272
- { success },
2273
- data.requestId
2274
- );
2275
- break;
2276
- }
2277
- case "get_project_icon": {
2278
- const { projectPath } = data.payload;
2279
- const icon = await this.projectManager.getProjectIcon(projectPath);
2280
- this.sendResponse(ws, "project_icon", { icon }, data.requestId);
2281
- break;
2282
- }
2283
- case "git_status": {
2284
- const { projectPath } = data.payload;
2285
- const status = await this.projectManager.gitStatus(projectPath);
2286
- this.sendResponse(
2287
- ws,
2288
- "git_status_data",
2289
- status,
2290
- data.requestId
2291
- );
2292
- break;
2293
- }
2294
- case "git_log": {
2295
- const { projectPath, options } = data.payload;
2296
- const log = await this.projectManager.gitLog(
2297
- projectPath,
2298
- options
2299
- );
2300
- this.sendResponse(ws, "git_log_data", log, data.requestId);
2301
- break;
2302
- }
2303
- case "git_diff": {
2304
- const { projectPath, options } = data.payload;
2305
- const diff = await this.projectManager.gitDiff(
2306
- projectPath,
2307
- options
2308
- );
2309
- this.sendResponse(ws, "git_diff_data", diff, data.requestId);
2310
- break;
2311
- }
2312
- case "git_analyze_commit": {
2313
- const { projectPath, commitHash, subPath } = data.payload;
2314
- const graph = await this.projectManager.gitAnalyzeCommit(
2315
- projectPath,
2316
- commitHash,
2317
- subPath
2318
- );
2319
- this.sendChunkedResponse(
2320
- ws,
2321
- "git_analyze_commit",
2322
- graph,
2323
- data.requestId
2324
- );
2325
- break;
2326
- }
2327
- case "call_tool": {
2328
- const { name, arguments: args } = data.payload;
2329
- const result = await this.handleCallTool({
2330
- name,
2331
- args
2332
- });
2333
- ws.send(
2334
- JSON.stringify({
2335
- type: "tool_result",
2336
- payload: result,
2337
- requestId: data.requestId
2338
- })
2339
- );
2340
- break;
2341
- }
2342
- case "chunked_response": {
2343
- break;
2344
- }
2345
- default: {
2346
- const unknownData = data;
2347
- this.sendError(
2348
- ws,
2349
- `Unknown message type: ${unknownData.type}`,
2350
- unknownData.requestId
2351
- );
2352
- break;
2353
- }
2354
- }
2355
- } catch (e) {
2356
- const errorMessage = e instanceof Error ? e.message : "Unknown error";
2357
- console.error("Error handling WebSocket message", e);
2358
- this.sendError(ws, errorMessage, currentRequestId);
2359
- }
2360
- });
2361
- });
2362
- } catch (error) {
2363
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
2364
- console.error(`Failed to start WebSocket server: ${errorMessage}`);
2365
- }
2366
- }
2367
- async startMcpServer(transport) {
2368
- this.mcpConnected = true;
2369
- transport.onclose = () => {
2370
- console.error("MCP stdio connection closed.");
2371
- this.mcpConnected = false;
2372
- this.checkExitCondition();
2373
- };
2374
- await this.mcpServer.connect(transport);
2375
- console.error(
2376
- `React Map MCP server running on stdio and ws://localhost:${this.port}`
2377
- );
2378
- setTimeout(() => this.checkExitCondition(), 1e4);
2379
- }
2380
- checkExitCondition() {
2381
- if (process.env.NODE_ENV === "development") {
2382
- return;
2383
- }
2384
- if (this.uiConnections === 0 && !this.mcpConnected) {
2385
- if (!this.exitTimeout) {
2386
- console.error(
2387
- "No active connections (UI or MCP). Starting 10s exit countdown..."
2388
- );
2389
- this.exitTimeout = setTimeout(async () => {
2390
- if (this.uiConnections === 0 && !this.mcpConnected) {
2391
- console.error("No active connections for 10s. Self-terminating...");
2392
- await this.projectManager.closeAll();
2393
- process.exit(0);
2394
- } else {
2395
- this.exitTimeout = null;
2396
- }
2397
- }, 1e4);
2398
- }
2399
- } else if (this.exitTimeout) {
2400
- console.error("Connection restored. Cancelling exit countdown.");
2401
- clearTimeout(this.exitTimeout);
2402
- this.exitTimeout = null;
2403
- }
2404
- }
2405
- async stop() {
2406
- if (this.wss) {
2407
- await new Promise((resolve) => this.wss.close(() => resolve()));
2408
- }
2409
- await this.mcpServer.close();
2410
- }
2411
- };
2412
-
2413
- // src/index.ts
2414
- if (import.meta.url === `file://${process.argv[1]}`) {
2415
- const projectManager = new ProjectManager();
2416
- const server = new BackendServer(projectManager);
2417
- const main = async () => {
2418
- const transport = new StdioServerTransport();
2419
- server.startWebSocketServer();
2420
- await server.startMcpServer(transport);
2421
- };
2422
- main().catch((error) => {
2423
- console.error("Fatal error in main():", error);
2424
- process.exit(1);
2425
- });
2426
- process.on("SIGINT", async () => {
2427
- await projectManager.closeAll();
2428
- process.exit(0);
2429
- });
2430
- process.on("SIGTERM", async () => {
2431
- await projectManager.closeAll();
2432
- process.exit(0);
2433
- });
2434
- }
2435
- export {
2436
- BackendServer,
2437
- ProjectManager
2438
- };