-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.js
More file actions
1057 lines (924 loc) · 37.4 KB
/
index.js
File metadata and controls
1057 lines (924 loc) · 37.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import fs from 'fs';
import path from 'path';
import * as url from 'url';
import TreeSitter from 'web-tree-sitter';
// WASM language parsers will be loaded dynamically
let Parser = null;
let initialized = false;
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
// Define supported languages and their WASM paths
const SUPPORTED_LANGUAGES = {
'js': 'tree-sitter-javascript.wasm',
'jsx': 'tree-sitter-javascript.wasm',
'ts': 'tree-sitter-javascript.wasm',
'tsx': 'tree-sitter-javascript.wasm',
'py': 'tree-sitter-python.wasm'
};
// Language instances
const languageInstances = {};
// Global store for code symbols
const codeSymbols = {
functions: {}, // Functions by file path
variables: {}, // Variables by file path
classes: {}, // Classes by file path
imports: {}, // Imports by file path
exports: {}, // Exports by file path
files: new Set() // All analyzed files
};
// Initialize Tree-sitter with WASM
async function initializeTreeSitter() {
if (initialized) return;
try {
await TreeSitter.init();
Parser = TreeSitter;
// Create language parsers
const languages = new Set(Object.values(SUPPORTED_LANGUAGES));
const parsersDir = ensureParsersDirectory();
let missingWasmFiles = [];
for (const wasmFile of languages) {
try {
const wasmPath = path.join(parsersDir, wasmFile);
if (fs.existsSync(wasmPath)) {
const lang = await TreeSitter.Language.load(wasmPath);
languageInstances[wasmFile] = lang;
} else {
console.warn(`Warning: WASM parser not found at ${wasmPath}`);
missingWasmFiles.push(wasmFile);
}
} catch (err) {
console.error(`Failed to load language ${wasmFile}:`, err);
missingWasmFiles.push(wasmFile);
}
}
// Provide helpful error message if WASM files are missing
if (missingWasmFiles.length > 0) {
console.error(`\nMissing WASM parser files: ${missingWasmFiles.join(', ')}`);
console.error(`\nPlease run the setup script to download them automatically:`);
console.error(` npx code-context-provider-mcp-setup`);
console.error(`\nOr download the WASM files manually and place them in: ${parsersDir}`);
console.error(`- JavaScript: https://github.com/tree-sitter/tree-sitter-javascript/releases`);
console.error(`- Python: https://github.com/tree-sitter/tree-sitter-python/releases`);
// Attempt to run the setup script automatically if in a Node.js context (not in browser)
if (typeof process !== 'undefined' && process.versions && process.versions.node) {
console.log('\nAttempting to download WASM files automatically...');
try {
// Using dynamic import to avoid issues in browser environments
const setupModule = await import('./setup.js');
if (typeof setupModule.default === 'function') {
await setupModule.default();
} else {
// Try to run the setupParsers function directly
await setupModule.setupParsers();
}
// Try to initialize again with the newly downloaded files
return await initializeTreeSitter();
} catch (setupErr) {
console.error('Automatic download failed:', setupErr.message);
}
}
}
initialized = missingWasmFiles.length === 0;
return initialized;
} catch (err) {
console.error("Failed to initialize Tree-sitter:", err);
throw err;
}
}
// Function to determine language from file extension
function getLanguageFromExtension(filePath) {
const ext = path.extname(filePath).substring(1).toLowerCase();
return SUPPORTED_LANGUAGES[ext] || null;
}
// Function to extract code symbols from a file
async function extractCodeSymbols(filePath, fileContent) {
// Ensure TreeSitter is initialized
if (!initialized) {
await initializeTreeSitter();
}
try {
// Set the appropriate language based on file extension
const wasmFile = getLanguageFromExtension(filePath);
if (!wasmFile || !languageInstances[wasmFile]) {
return null; // Unsupported language
}
const parser = new Parser();
parser.setLanguage(languageInstances[wasmFile]);
const tree = parser.parse(fileContent);
const rootNode = tree.rootNode;
const functions = [];
const variables = [];
const classes = [];
const imports = [];
const exports = [];
// Helper to get line and column info
const getPosition = (node) => {
return {
startLine: node.startPosition.row + 1,
startCol: node.startPosition.column,
endLine: node.endPosition.row + 1,
endCol: node.endPosition.column
};
};
// Helper to check if a function is significant enough to track
const isSignificantFunction = (node, name) => {
// Skip tiny arrow functions like () => {} or x => x
if (node.type === 'arrow_function' && node.text.length < 15) {
return false;
}
// Skip callback functions in array methods if they're simple
const parent = node.parent;
if (parent &&
(parent.type === 'call_expression' || parent.type === 'member_expression') &&
node.text.length < 50) {
// Check if it's a callback in common array methods
const callText = parent.text.slice(0, 30).toLowerCase();
if (callText.includes('.map(') ||
callText.includes('.filter(') ||
callText.includes('.forEach(') ||
callText.includes('.find(') ||
callText.includes('.reduce(')) {
return false;
}
}
// Keep named functions and significant anonymous ones
return name !== 'anonymous' || node.text.length > 100;
};
// Helper to infer function name from context
const inferFunctionName = (node) => {
let name = 'anonymous';
// Check if function is assigned to a variable
const parent = node.parent;
if (parent) {
if (parent.type === 'variable_declarator') {
// Case: const myFunc = function() {...} or const myFunc = () => {...}
const nameNode = parent.childForFieldName('name');
if (nameNode) {
return nameNode.text;
}
} else if (parent.type === 'pair' && parent.parent && parent.parent.type === 'object') {
// Case: { myMethod: function() {...} } or { myMethod: () => {...} }
const keyNode = parent.childForFieldName('key');
if (keyNode) {
return keyNode.text.replace(/['"]/g, '');
}
} else if (parent.type === 'assignment_expression') {
// Case: obj.method = function() {...} or MyClass.prototype.method = function() {...}
const leftNode = parent.childForFieldName('left');
if (leftNode) {
if (leftNode.type === 'member_expression') {
// Get rightmost part, e.g., 'method' from 'obj.method'
const propertyNode = leftNode.childForFieldName('property');
if (propertyNode) {
return propertyNode.text;
}
} else {
return leftNode.text;
}
}
} else if (parent.type === 'property_identifier' && parent.parent &&
parent.parent.type === 'member_expression') {
// Case for method callbacks like .then(() => {...})
return parent.text;
}
}
return name;
};
// Process different languages
if (wasmFile === 'tree-sitter-javascript.wasm') {
// Process JavaScript/TypeScript
// Find function declarations
const functionNodes = rootNode.descendantsOfType([
'function_declaration',
'method_definition',
'arrow_function',
'function'
]);
for (const node of functionNodes) {
// Get function name
let name = 'anonymous';
let parentFunction = null;
if (node.type === 'function_declaration') {
const nameNode = node.firstNamedChild;
if (nameNode) name = nameNode.text;
} else if (node.type === 'method_definition') {
const nameNode = node.childForFieldName('name');
if (nameNode) name = nameNode.text;
// Get parent class or object
const classNode = node.parent?.parent;
if (classNode?.type === 'class_declaration') {
const classNameNode = classNode.childForFieldName('name');
if (classNameNode) parentFunction = classNameNode.text;
}
} else if (node.type === 'function' || node.type === 'arrow_function') {
// Try to infer the name from context
name = inferFunctionName(node);
}
// Only add significant functions
if (isSignificantFunction(node, name)) {
functions.push({
name,
parent: parentFunction,
position: getPosition(node),
code: node.text
});
}
}
// Find variable declarations
const variableNodes = rootNode.descendantsOfType([
'variable_declaration',
'lexical_declaration'
]);
for (const node of variableNodes) {
const declarators = node.descendantsOfType('variable_declarator');
for (const declarator of declarators) {
const nameNode = declarator.childForFieldName('name');
if (nameNode) {
variables.push({
name: nameNode.text,
kind: node.childForFieldName('kind')?.text || 'var',
position: getPosition(declarator),
code: declarator.text
});
}
}
}
// Find class declarations
const classNodes = rootNode.descendantsOfType('class_declaration');
for (const node of classNodes) {
const nameNode = node.childForFieldName('name');
if (nameNode) {
const className = nameNode.text;
// Get class members
const methods = [];
const methodNodes = node.descendantsOfType('method_definition');
for (const methodNode of methodNodes) {
const methodNameNode = methodNode.childForFieldName('name');
if (methodNameNode) {
methods.push({
name: methodNameNode.text,
position: getPosition(methodNode),
isStatic: methodNode.childForFieldName('static')?.text === 'static',
code: methodNode.text
});
}
}
classes.push({
name: className,
position: getPosition(node),
methods,
code: node.text
});
}
}
// Find imports
const importNodes = rootNode.descendantsOfType('import_statement');
for (const node of importNodes) {
const sourceNode = node.childForFieldName('source');
if (sourceNode) {
const source = sourceNode.text.replace(/['"]/g, '');
const importedItems = [];
const specifiers = node.descendantsOfType([
'import_specifier',
'namespace_import'
]);
for (const specNode of specifiers) {
if (specNode.type === 'import_specifier') {
const nameNode = specNode.childForFieldName('name');
const aliasNode = specNode.childForFieldName('alias');
if (nameNode) {
importedItems.push({
name: nameNode.text,
alias: aliasNode ? aliasNode.text : null
});
}
} else if (specNode.type === 'namespace_import') {
const nameNode = specNode.childForFieldName('name');
if (nameNode) {
importedItems.push({
name: '*',
alias: nameNode.text
});
}
}
}
// Check for default imports
const defaultImportNode = node.descendantsOfType('identifier')[0];
if (defaultImportNode && !specifiers.length) {
importedItems.push({
name: 'default',
alias: defaultImportNode.text
});
}
imports.push({
source,
items: importedItems,
position: getPosition(node),
code: node.text
});
}
}
// Find exports
const exportNodes = rootNode.descendantsOfType([
'export_statement',
'lexical_declaration',
'function_declaration'
]);
for (const node of exportNodes) {
if (node.type === 'export_statement') {
const sourceNode = node.childForFieldName('source');
const source = sourceNode ? sourceNode.text.replace(/['"]/g, '') : null;
const exportedItems = [];
const specifiers = node.descendantsOfType('export_specifier');
for (const specNode of specifiers) {
const nameNode = specNode.childForFieldName('name');
const aliasNode = specNode.childForFieldName('alias');
if (nameNode) {
exportedItems.push({
name: nameNode.text,
alias: aliasNode ? aliasNode.text : null
});
}
}
exports.push({
source,
items: exportedItems,
isDefault: node.childForFieldName('default')?.text === 'default',
position: getPosition(node),
code: node.text
});
} else {
// Check for export modifier on declaration
const parent = node.parent;
if (parent?.type === 'export_statement') {
let name = '';
if (node.type === 'function_declaration') {
const nameNode = node.childForFieldName('name');
if (nameNode) name = nameNode.text;
} else if (node.type === 'lexical_declaration') {
const declarator = node.descendantsOfType('variable_declarator')[0];
if (declarator) {
const nameNode = declarator.childForFieldName('name');
if (nameNode) name = nameNode.text;
}
}
if (name) {
exports.push({
source: null,
items: [{ name, alias: null }],
isDefault: parent.childForFieldName('default')?.text === 'default',
position: getPosition(parent),
code: parent.text
});
}
}
}
}
} else if (wasmFile === 'tree-sitter-python.wasm') {
// Process Python
// Find function declarations
const functionNodes = rootNode.descendantsOfType('function_definition');
for (const node of functionNodes) {
// Get function name
let name = 'anonymous';
let parentFunction = null;
const nameNode = node.childForFieldName('name');
if (nameNode) name = nameNode.text;
// Check if this is a class method
const parent = node.parent?.parent;
if (parent?.type === 'class_definition') {
const classNameNode = parent.childForFieldName('name');
if (classNameNode) parentFunction = classNameNode.text;
}
functions.push({
name,
parent: parentFunction,
position: getPosition(node),
code: node.text
});
}
// Find variable assignments (global and class level)
const assignmentNodes = rootNode.descendantsOfType('assignment');
for (const node of assignmentNodes) {
// Only consider top-level or class-level assignments
const parent = node.parent;
if (parent?.type === 'module' || parent?.type === 'block' && parent.parent?.type === 'class_definition') {
const left = node.childForFieldName('left');
if (left && left.type === 'identifier') {
variables.push({
name: left.text,
kind: 'var', // Python doesn't have explicit variable declarations
position: getPosition(node),
code: node.text
});
}
}
}
// Find class declarations
const classNodes = rootNode.descendantsOfType('class_definition');
for (const node of classNodes) {
const nameNode = node.childForFieldName('name');
if (nameNode) {
const className = nameNode.text;
// Get class methods
const methods = [];
const methodNodes = node.descendantsOfType('function_definition');
for (const methodNode of methodNodes) {
const methodNameNode = methodNode.childForFieldName('name');
if (methodNameNode) {
// Check if method is static (has @staticmethod decorator)
let isStatic = false;
const decorators = methodNode.childForFieldName('decorator_list');
if (decorators) {
const decoratorNodes = decorators.children;
for (const decorator of decoratorNodes) {
if (decorator.text === '@staticmethod') {
isStatic = true;
break;
}
}
}
methods.push({
name: methodNameNode.text,
position: getPosition(methodNode),
isStatic,
code: methodNode.text
});
}
}
classes.push({
name: className,
position: getPosition(node),
methods,
code: node.text
});
}
}
// Find imports
const importNodes = rootNode.descendantsOfType(['import_statement', 'import_from_statement']);
for (const node of importNodes) {
if (node.type === 'import_statement') {
// Case: import module [as alias]
const namesNode = node.childForFieldName('names');
if (namesNode) {
const importedModules = namesNode.descendantsOfType('dotted_name');
for (const moduleNode of importedModules) {
const moduleName = moduleNode.text;
const aliasNode = moduleNode.nextNamedSibling;
imports.push({
source: moduleName,
items: [{
name: 'module',
alias: aliasNode ? aliasNode.text : null
}],
position: getPosition(node),
code: node.text
});
}
}
} else if (node.type === 'import_from_statement') {
// Case: from module import name [as alias], ...
const moduleNode = node.childForFieldName('module');
const namesNode = node.childForFieldName('names');
if (moduleNode && namesNode) {
const moduleName = moduleNode.text;
const importedItems = [];
const importedNames = namesNode.namedChildren;
for (const nameNode of importedNames) {
if (nameNode.type === 'aliased_import') {
const name = nameNode.childForFieldName('name')?.text;
const alias = nameNode.childForFieldName('alias')?.text;
if (name) {
importedItems.push({
name,
alias
});
}
} else if (nameNode.type === 'identifier') {
importedItems.push({
name: nameNode.text,
alias: null
});
}
}
imports.push({
source: moduleName,
items: importedItems,
position: getPosition(node),
code: node.text
});
}
}
}
}
return {
functions,
variables,
classes,
imports,
exports
};
} catch (error) {
console.error(`Error parsing ${filePath}: ${error.message}`);
return null;
}
}
// Function to parse .gitignore file
function parseGitignore(gitignorePath) {
if (!fs.existsSync(gitignorePath)) {
return [];
}
try {
const content = fs.readFileSync(gitignorePath, 'utf8');
return content
.split('\n')
.map(line => line.trim())
.filter(line => line && !line.startsWith('#'))
.map(pattern => {
// Common patterns we want to handle explicitly
if (pattern === 'node_modules' || pattern === 'node_modules/') {
return '^node_modules($|/)';
}
// Remove trailing slashes (they mean directories in gitignore)
let processedPattern = pattern.replace(/\/+$/, '');
// Handle leading slashes (anchors the pattern to the root)
const hasLeadingSlash = processedPattern.startsWith('/');
if (hasLeadingSlash) {
processedPattern = processedPattern.slice(1);
}
// Convert gitignore glob pattern to regex pattern
processedPattern = processedPattern
.replace(/\./g, '\\.') // Escape dots
.replace(/\*\*/g, '__DOUBLE_STAR__') // Temporarily replace **
.replace(/\*/g, '[^/]*') // * matches any character except /
.replace(/__DOUBLE_STAR__/g, '.*') // ** matches anything including /
.replace(/\?/g, '[^/]') // ? matches a single character except /
.replace(/\//g, '\\/'); // Escape forward slashes
// If it had a leading slash, anchor it to the start
if (hasLeadingSlash) {
return `^${processedPattern}($|/.*)`;
}
// If no leading slash, match anywhere in path
return `(^|.*/|^/)${processedPattern}($|/.*)`;
});
} catch (error) {
console.error(`Error parsing .gitignore: ${error.message}`);
return [];
}
}
// Function to check if a path should be ignored based on gitignore patterns
function shouldIgnore(itemPath, ignorePatterns, rootPath) {
if (ignorePatterns.length === 0) {
return false;
}
// Get relative path for matching (always use forward slashes)
const relativePath = path.relative(rootPath, itemPath).replace(/\\/g, '/');
// Add trailing slash for directories to match directory-specific patterns
const stats = fs.statSync(itemPath);
const pathToCheck = stats.isDirectory() ? `${relativePath}/` : relativePath;
// Name-only check for simple file matches
const itemName = path.basename(itemPath);
// Check if the path matches any ignore pattern
return ignorePatterns.some(pattern => {
const regex = new RegExp(pattern);
return regex.test(pathToCheck) || regex.test(itemName);
});
}
// Function to check if file is supported for code analysis
function isSupportedFile(filePath, customPatterns = null) {
// If we have custom patterns, check if the file matches any of them
if (customPatterns && customPatterns.length > 0) {
const fileName = path.basename(filePath);
return customPatterns.some(pattern => {
// Try to match as glob pattern
if (pattern.includes('*')) {
const regexPattern = pattern
.replace(/\./g, '\\.')
.replace(/\*/g, '.*');
return new RegExp(`^${regexPattern}$`).test(fileName);
}
// Check for extension match (with or without the dot)
if (pattern.startsWith('.')) {
return filePath.endsWith(pattern);
}
// Match by extension without the dot
return path.extname(filePath).substring(1).toLowerCase() === pattern.toLowerCase();
});
}
// Otherwise use the default language support check
const ext = path.extname(filePath).substring(1).toLowerCase();
return ext in SUPPORTED_LANGUAGES;
}
// Create parsers directory if it doesn't exist
function ensureParsersDirectory() {
const parsersDir = path.join(__dirname, 'parsers');
if (!fs.existsSync(parsersDir)) {
fs.mkdirSync(parsersDir, { recursive: true });
}
return parsersDir;
}
// Function to recursively get directory structure and analyze JS files
async function getDirectoryTree(dirPath, rootPath = dirPath, ignorePatterns = [], filePatterns = null, indent = '', analyzeJs = false, includeSymbols = false, symbolType = 'all', currentDepth = 0, maxDepth = 5) {
try {
if (!fs.existsSync(dirPath)) {
return `${indent}Path does not exist: ${dirPath}`;
}
// Default patterns to ignore common directories and files
const defaultIgnorePatterns = [
'^node_modules($|/)',
'^.git($|/)',
'\\.log$',
'\\.tmp$',
'\\.temp$',
'\\.swp$',
'\\.DS_Store$',
'\\.vscode($|/)',
'\\.idea($|/)',
'\\.vs($|/)',
'^dist($|/)',
'^build($|/)',
'^coverage($|/)'
];
// Combine default patterns with any provided patterns
let allIgnorePatterns = [...defaultIgnorePatterns, ...ignorePatterns];
// Check for .gitignore file in this directory
const gitignorePath = path.join(dirPath, '.gitignore');
if (fs.existsSync(gitignorePath)) {
const newPatterns = parseGitignore(gitignorePath);
allIgnorePatterns = [...allIgnorePatterns, ...newPatterns];
}
let output = '';
const items = fs.readdirSync(dirPath);
for (let i = 0; i < items.length; i++) {
const itemName = items[i];
const itemPath = path.join(dirPath, itemName);
// Skip .gitignore files
if (itemName === '.gitignore') {
continue;
}
// Skip hidden files/directories
if (itemName.startsWith('.')) {
continue;
}
// Skip items that match ignore patterns
if (shouldIgnore(itemPath, allIgnorePatterns, rootPath)) {
continue;
}
const isLast = i === items.length - 1;
const stats = fs.statSync(itemPath);
// Generate the prefix for current item
const prefix = isLast ? '└── ' : '├── ';
// Generate the prefix for child items
const childIndent = indent + (isLast ? ' ' : '│ ');
if (stats.isDirectory()) {
output += `${indent}${prefix}${itemName}/\n`;
// Always recurse to build the directory tree, but only analyze code if we're within maxDepth
const shouldAnalyze = analyzeJs && (currentDepth < maxDepth);
output += await getDirectoryTree(
itemPath,
rootPath,
allIgnorePatterns,
filePatterns,
childIndent,
shouldAnalyze, // Only analyze if within depth limit
includeSymbols,
symbolType,
currentDepth + 1,
maxDepth
);
} else {
const sizeInKB = Math.ceil(stats.size / 1024);
output += `${indent}${prefix}${itemName} (${sizeInKB} KB)\n`;
// Analyze supported files if requested AND we're within the max depth limit
if (analyzeJs && currentDepth <= maxDepth && isSupportedFile(itemPath, filePatterns)) {
try {
const fileContent = fs.readFileSync(itemPath, 'utf8');
const symbols = await extractCodeSymbols(itemPath, fileContent);
if (symbols) {
// Store the extracted symbols
codeSymbols.functions[itemPath] = symbols.functions;
codeSymbols.variables[itemPath] = symbols.variables;
codeSymbols.classes[itemPath] = symbols.classes;
codeSymbols.imports[itemPath] = symbols.imports;
codeSymbols.exports[itemPath] = symbols.exports;
codeSymbols.files.add(itemPath);
// Add a summary of what was found
output += `${childIndent}└── [Analyzed: ${symbols.functions.length} functions, ${symbols.variables.length} variables, ${symbols.classes.length} classes]\n`;
// Add detailed symbol information if requested
if (includeSymbols) {
// Functions
if ((symbolType === 'functions' || symbolType === 'all') && symbols.functions.length > 0) {
// Always filter out anonymous functions by default
const fileFunctions = symbols.functions.filter(fn => fn.name !== 'anonymous');
if (fileFunctions.length > 0) {
output += `${childIndent} Functions:\n`;
output += fileFunctions.map(fn =>
`${childIndent} - ${fn.name}${fn.parent ? ` (in ${fn.parent})` : ''} [${fn.position.startLine}:${fn.position.startCol}]`
).join('\n') + '\n';
}
}
// Variables
if ((symbolType === 'variables' || symbolType === 'all') && symbols.variables.length > 0) {
output += `${childIndent} Variables:\n`;
output += symbols.variables.map(v =>
`${childIndent} - ${v.kind} ${v.name} [${v.position.startLine}:${v.position.startCol}]`
).join('\n') + '\n';
}
// Classes
if ((symbolType === 'classes' || symbolType === 'all') && symbols.classes.length > 0) {
output += `${childIndent} Classes:\n`;
output += symbols.classes.map(c => {
let classInfo = `${childIndent} - ${c.name} [${c.position.startLine}:${c.position.startCol}]`;
if (c.methods.length > 0) {
classInfo += `\n${childIndent} Methods:\n`;
classInfo += c.methods.map(m =>
`${childIndent} - ${m.isStatic ? 'static ' : ''}${m.name} [${m.position.startLine}:${m.position.startCol}]`
).join('\n');
}
return classInfo;
}).join('\n') + '\n';
}
// Imports
if ((symbolType === 'imports' || symbolType === 'all') && symbols.imports.length > 0) {
output += `${childIndent} Imports:\n`;
output += symbols.imports.map(imp => {
let importInfo = `${childIndent} - from '${imp.source}'`;
if (imp.items.length > 0) {
importInfo += ': ' + imp.items.map(item =>
`${item.name}${item.alias ? ` as ${item.alias}` : ''}`
).join(', ');
}
return importInfo;
}).join('\n') + '\n';
}
// Exports
if ((symbolType === 'exports' || symbolType === 'all') && symbols.exports.length > 0) {
output += `${childIndent} Exports:\n`;
output += symbols.exports.map(exp => {
let exportInfo = `${childIndent} - ${exp.isDefault ? 'default export' : 'export'}`;
if (exp.source) {
exportInfo += ` from '${exp.source}'`;
}
if (exp.items.length > 0) {
exportInfo += ': ' + exp.items.map(item =>
`${item.name}${item.alias ? ` as ${item.alias}` : ''}`
).join(', ');
}
return exportInfo;
}).join('\n') + '\n';
}
}
}
} catch (error) {
console.error(`Error analyzing ${itemPath}: ${error.message}`);
}
}
}
}
return output;
} catch (error) {
console.error(`Error processing directory ${dirPath}: ${error.message}`);
return `${indent}Error: ${error.message}\n`;
}
}
// Create an MCP Server
const server = new McpServer({
name: "Context Provider MCP Server",
version: "1.0.0"
});
// Add the get_code_context tool
server.tool(
"get_code_context",
"Returns Complete Context of a given project directory, including directory tree, and code symbols. Useful for getting a quick overview of a project. Use this tool when you need to get a comprehensive overview of a project's codebase. Useful at the start of a new task.",
{
absolutePath: z.string().describe("Absolute path to the directory to analyze. For windows, it is recommended to use forward slashes to avoid escaping (e.g. C:/Users/username/Documents/project/src)"),
analyzeJs: z.boolean().optional().default(false).describe("Whether to analyze JavaScript/TypeScript and Python files. Returns the count of functions, variables, classes, imports, and exports in the codebase."),
includeSymbols: z.boolean().optional().default(false).describe("Whether to include code symbols in the response. Returns the code symbols for each file."),
symbolType: z.enum(['functions', 'variables', 'classes', 'imports', 'exports', 'all']).optional().default('all').describe("Type of symbols to include if includeSymbols is true. Otherwise, returns only the directory tree."),
maxDepth: z.number().optional().default(5).describe("Maximum directory depth for code analysis (default: 5 levels). Directory tree will still be built for all levels. Reduce the depth if you only need a quick overview of the project.")
},
async ({ absolutePath, analyzeJs, includeSymbols, symbolType, filePatterns, maxDepth = 5 }) => {
try {
// Check if the path is C:/ drive root or common non-project directories on Windows OS
if (process.platform === 'win32') {
// Check for C: drive root or common system directories that are not project directories
const nonProjectPaths = [
/^[cC]:[\\/]?$/, // C:/ or C:
/^[cC]:[\\/]Users[\\/]?$/, // C:/Users/
/^[cC]:[\\/]Windows[\\/]?$/, // C:/Windows/
/^[cC]:[\\/]Program Files[\\/]?$/, // C:/Program Files/
/^[cC]:[\\/]Program Files \(x86\)[\\/]?$/ // C:/Program Files (x86)/
];
if (nonProjectPaths.some(regex => regex.test(absolutePath))) {
return {
content: [{ type: "text", text: "C drive is not a project directory. Try different path" }],
isError: true
};
}
}
// Ensure TreeSitter is initialized if we're going to analyze code
if (analyzeJs && !initialized) {
// Create parsers directory and ensure it exists
const parsersDir = ensureParsersDirectory();
console.error(`Using parsers directory: ${parsersDir}`);
// Initialize TreeSitter
await initializeTreeSitter();
if (!initialized) {
return {
content: [{ type: "text", text: "Error: Failed to initialize code analysis parser. WASM parsers may be missing." }],
isError: true
};
}
}
// Normalize path to handle both Windows and Unix-style paths
const normalizedPath = path.normalize(absolutePath);
console.error(`Analyzing directory: ${normalizedPath} (analyzeJs: ${analyzeJs}, maxAnalysisDepth: ${maxDepth !== 5 ? maxDepth : '5 (default)'})`);
// Reset code symbols if analyzing JS
if (analyzeJs) {
codeSymbols.functions = {};
codeSymbols.variables = {};
codeSymbols.classes = {};
codeSymbols.imports = {};
codeSymbols.exports = {};
codeSymbols.files = new Set();
}
// Get the directory tree, passing along all the symbol-related parameters
const tree = await getDirectoryTree(
normalizedPath,
normalizedPath,
[],
filePatterns,
'',
analyzeJs,
includeSymbols,
symbolType,
0,
maxDepth
);
// Generate summary of analyzed files if applicable
let analysisSummary = '';
if (analyzeJs && codeSymbols.files.size > 0) {
const totalFunctions = Object.values(codeSymbols.functions).reduce((sum, arr) => sum + arr.length, 0);
const totalVariables = Object.values(codeSymbols.variables).reduce((sum, arr) => sum + arr.length, 0);
const totalClasses = Object.values(codeSymbols.classes).reduce((sum, arr) => sum + arr.length, 0);
analysisSummary = `\n\nCode Analysis Summary:
- Files analyzed: ${codeSymbols.files.size}
- Total functions: ${totalFunctions}
- Total variables: ${totalVariables}
- Total classes: ${totalClasses}`;
// Add language support info and custom pattern info