-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.ts
More file actions
1964 lines (1733 loc) · 62.7 KB
/
index.ts
File metadata and controls
1964 lines (1733 loc) · 62.7 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
/**
* MCP Server for Codebase Context
* Provides codebase indexing and semantic search capabilities
*/
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { createServer } from './server/factory.js';
import { startHttpServer } from './server/http.js';
import { loadServerConfig } from './server/config.js';
import type { ProjectConfig } from './server/config.js';
import {
CallToolRequestSchema,
ListToolsRequestSchema,
ListResourcesRequestSchema,
ReadResourceRequestSchema,
RootsListChangedNotificationSchema,
Resource
} from '@modelcontextprotocol/sdk/types.js';
import { CodebaseIndexer } from './core/indexer.js';
import type {
IntelligenceData,
PatternsData,
PatternEntry,
PatternCandidate
} from './types/index.js';
import { analyzerRegistry } from './core/analyzer-registry.js';
import { AngularAnalyzer } from './analyzers/angular/index.js';
import { NextJsAnalyzer } from './analyzers/nextjs/index.js';
import { ReactAnalyzer } from './analyzers/react/index.js';
import { GenericAnalyzer } from './analyzers/generic/index.js';
import { IndexCorruptedError } from './errors/index.js';
import { appendMemoryFile } from './memory/store.js';
import { handleCliCommand } from './cli.js';
import { startFileWatcher } from './core/file-watcher.js';
import { parseGitLogLineToMemory } from './memory/git-memory.js';
import {
isComplementaryPatternCategory,
shouldSkipLegacyTestingFrameworkCategory
} from './patterns/semantics.js';
import {
CONTEXT_RESOURCE_URI,
buildProjectContextResourceUri,
getProjectPathFromContextResourceUri,
isContextResourceUri
} from './resources/uri.js';
import { generateCodebaseIntelligence } from './resources/codebase-intelligence.js';
import { EXCLUDED_GLOB_PATTERNS } from './constants/codebase-context.js';
import {
discoverProjectsWithinRoot,
findNearestProjectBoundary,
isPathWithin
} from './utils/project-discovery.js';
import { readIndexMeta, validateIndexArtifacts } from './core/index-meta.js';
import { TOOLS, dispatchTool, type ToolContext, type ToolResponse } from './tools/index.js';
import type { ProjectDescriptor, ToolPaths } from './tools/types.js';
import {
getOrCreateProject,
getAllProjects,
getProject,
makePaths,
makeLegacyPaths,
normalizeRootKey,
removeProject,
type ProjectRuntimeOverrides,
type ProjectState
} from './project-state.js';
analyzerRegistry.register(new AngularAnalyzer());
analyzerRegistry.register(new NextJsAnalyzer());
analyzerRegistry.register(new ReactAnalyzer());
analyzerRegistry.register(new GenericAnalyzer());
// Flags that are NOT project paths — skip them when resolving the bootstrap root.
const KNOWN_FLAGS = new Set(['--http', '--port', '--help']);
// Resolve optional bootstrap root with validation handled later in main().
function resolveRootPath(): string | undefined {
const envPath = process.env.CODEBASE_ROOT;
// Walk argv starting at position 2, skip known flags and their values.
let arg: string | undefined;
for (let i = 2; i < process.argv.length; i++) {
const token = process.argv[i];
if (!token) continue;
if (KNOWN_FLAGS.has(token)) {
if (token === '--port') i++; // skip the value that follows --port
continue;
}
if (!token.startsWith('-')) {
arg = token;
break;
}
}
// Priority: CLI arg > env var. Do not fall back to cwd in MCP mode.
const configuredRoot = arg || envPath;
if (!configuredRoot) {
return undefined;
}
return path.resolve(configuredRoot);
}
const primaryRootPath = resolveRootPath();
const toolNames = new Set(TOOLS.map((tool) => tool.name));
const knownRoots = new Map<string, { rootPath: string; label?: string }>();
/** Roots loaded from config file — preserved across syncKnownRoots() refreshes. */
const configRoots = new Map<string, { rootPath: string }>();
const discoveredProjectPaths = new Map<string, string>();
let clientRootsEnabled = false;
const projectSourcesByKey = new Map<string, ProjectDescriptor['source']>();
const projectAccessOrder = new Map<string, number>();
let activeProjectKey: string | undefined;
let nextProjectAccessOrder = 1;
const MAX_WATCHED_PROJECTS = 5;
const PROJECT_DISCOVERY_MAX_DEPTH = 4;
const debounceEnv = Number.parseInt(process.env.CODEBASE_CONTEXT_DEBOUNCE_MS ?? '', 10);
const watcherDebounceMs = Number.isFinite(debounceEnv) && debounceEnv >= 0 ? debounceEnv : 2000;
type ProjectResolution =
| { ok: true; project: ProjectState }
| { ok: false; response: ToolResponse };
function registerKnownRoot(rootPath: string): string {
const resolvedRootPath = path.resolve(rootPath);
knownRoots.set(normalizeRootKey(resolvedRootPath), { rootPath: resolvedRootPath });
rememberProjectPath(resolvedRootPath, 'root');
return resolvedRootPath;
}
function getKnownRootPaths(): string[] {
return Array.from(knownRoots.values())
.map((entry) => entry.rootPath)
.sort((a, b) => a.localeCompare(b));
}
function getKnownRootLabel(rootPath: string): string | undefined {
return knownRoots.get(normalizeRootKey(rootPath))?.label;
}
function getContainingKnownRoot(rootPath: string): string | undefined {
const orderedRoots = getKnownRootPaths().sort((a, b) => b.length - a.length);
return orderedRoots.find((knownRootPath) => isPathWithin(knownRootPath, rootPath));
}
function classifyProjectSource(rootPath: string): ProjectDescriptor['source'] {
const rootKey = normalizeRootKey(rootPath);
if (knownRoots.has(rootKey)) {
return 'root';
}
return getContainingKnownRoot(rootPath) ? 'subdirectory' : 'ad_hoc';
}
function touchProject(rootPath: string): void {
projectAccessOrder.set(normalizeRootKey(rootPath), nextProjectAccessOrder++);
}
function rememberProjectPath(
rootPath: string,
source: ProjectDescriptor['source'] = classifyProjectSource(rootPath),
options: { touch?: boolean } = {}
): void {
const resolvedRootPath = path.resolve(rootPath);
const rootKey = normalizeRootKey(resolvedRootPath);
const existingSource = projectSourcesByKey.get(rootKey);
if (
!existingSource ||
source === 'root' ||
(source === 'subdirectory' && existingSource === 'ad_hoc')
) {
projectSourcesByKey.set(rootKey, source);
}
if (options.touch !== false) {
touchProject(resolvedRootPath);
}
}
function registerDiscoveredProjectPath(
rootPath: string,
source: ProjectDescriptor['source'] = 'subdirectory'
): void {
const resolvedRootPath = path.resolve(rootPath);
discoveredProjectPaths.set(normalizeRootKey(resolvedRootPath), resolvedRootPath);
rememberProjectPath(resolvedRootPath, source, { touch: false });
}
function clearDiscoveredProjectPaths(): void {
discoveredProjectPaths.clear();
}
function getTrackedRootPathByKey(rootKey: string): string | undefined {
if (knownRoots.has(rootKey)) {
return knownRoots.get(rootKey)?.rootPath;
}
const project = Array.from(getAllProjects()).find(
(entry) => normalizeRootKey(entry.rootPath) === rootKey
);
return project?.rootPath;
}
function forgetProjectPath(rootPath: string): void {
const rootKey = normalizeRootKey(rootPath);
projectSourcesByKey.delete(rootKey);
projectAccessOrder.delete(rootKey);
if (activeProjectKey === rootKey) {
activeProjectKey = undefined;
}
}
function formatProjectLabel(rootPath: string): string {
const knownRootLabel = getKnownRootLabel(rootPath);
if (knownRootLabel) {
return knownRootLabel;
}
const containingRoot = getContainingKnownRoot(rootPath);
if (containingRoot) {
const relativePath = path.relative(containingRoot, rootPath);
if (!relativePath) {
return getKnownRootLabel(containingRoot) ?? (path.basename(rootPath) || rootPath);
}
return relativePath.replace(/\\/g, '/');
}
return path.basename(rootPath) || rootPath;
}
function getRelativeProjectPath(rootPath: string): string | undefined {
const containingRoot = getContainingKnownRoot(rootPath);
if (!containingRoot) return undefined;
const relativePath = path.relative(containingRoot, rootPath).replace(/\\/g, '/');
return relativePath || undefined;
}
function getProjectIndexStatus(rootPath: string): ProjectDescriptor['indexStatus'] {
return getProject(rootPath)?.indexState.status ?? 'idle';
}
function buildProjectDescriptor(rootPath: string): ProjectDescriptor {
const resolvedRootPath = path.resolve(rootPath);
const rootKey = normalizeRootKey(resolvedRootPath);
rememberProjectPath(resolvedRootPath, classifyProjectSource(resolvedRootPath), { touch: false });
return {
project: resolvedRootPath,
label: formatProjectLabel(resolvedRootPath),
rootPath: resolvedRootPath,
relativePath: getRelativeProjectPath(resolvedRootPath),
active: activeProjectKey === rootKey,
source: projectSourcesByKey.get(rootKey) ?? classifyProjectSource(resolvedRootPath),
indexStatus: getProjectIndexStatus(resolvedRootPath)
};
}
function listProjectDescriptors(): ProjectDescriptor[] {
const rootPaths = new Map<string, string>();
for (const rootPath of getKnownRootPaths()) {
rootPaths.set(normalizeRootKey(rootPath), rootPath);
}
for (const [projectKey, rootPath] of discoveredProjectPaths.entries()) {
rootPaths.set(projectKey, rootPath);
}
for (const project of getAllProjects()) {
rootPaths.set(normalizeRootKey(project.rootPath), project.rootPath);
}
const descriptors = Array.from(rootPaths.values())
.map((rootPath) => buildProjectDescriptor(rootPath))
.sort((a, b) => {
if (a.active !== b.active) return a.active ? -1 : 1;
if (a.source !== b.source) {
const weight: Record<ProjectDescriptor['source'], number> = {
root: 0,
subdirectory: 1,
ad_hoc: 2
};
return weight[a.source] - weight[b.source];
}
return a.label.localeCompare(b.label);
});
const duplicates = new Set<string>();
const counts = new Map<string, number>();
for (const descriptor of descriptors) {
counts.set(descriptor.label, (counts.get(descriptor.label) ?? 0) + 1);
}
for (const [label, count] of counts.entries()) {
if (count > 1) {
duplicates.add(label);
}
}
return descriptors.map((descriptor) => {
if (!duplicates.has(descriptor.label)) {
return descriptor;
}
const containingRoot = getContainingKnownRoot(descriptor.rootPath);
const rootHint =
(containingRoot && getKnownRootLabel(containingRoot)) ||
(containingRoot && path.basename(containingRoot)) ||
path.basename(descriptor.rootPath);
return {
...descriptor,
label: `${descriptor.label} (${rootHint})`
};
});
}
function getActiveProjectDescriptor(): ProjectDescriptor | undefined {
if (!activeProjectKey) return undefined;
const trackedRootPath = getTrackedRootPathByKey(activeProjectKey);
if (!trackedRootPath) {
activeProjectKey = undefined;
return undefined;
}
return buildProjectDescriptor(trackedRootPath);
}
function setActiveProject(rootPath: string): void {
const resolvedRootPath = path.resolve(rootPath);
activeProjectKey = normalizeRootKey(resolvedRootPath);
rememberProjectPath(resolvedRootPath);
}
function syncKnownRoots(rootEntries: Array<{ rootPath: string; label?: string }>): void {
const nextRoots = new Map<string, { rootPath: string; label?: string }>();
const normalizedRoots =
rootEntries.length > 0 ? rootEntries : primaryRootPath ? [{ rootPath: primaryRootPath }] : [];
for (const entry of normalizedRoots) {
const resolvedRootPath = path.resolve(entry.rootPath);
nextRoots.set(normalizeRootKey(resolvedRootPath), {
rootPath: resolvedRootPath,
label: entry.label?.trim() || undefined
});
}
// Always include config-registered roots — config is additive (REPO-03)
for (const [rootKey, rootEntry] of configRoots.entries()) {
if (!nextRoots.has(rootKey)) {
nextRoots.set(rootKey, rootEntry);
}
}
for (const [rootKey, existingRoot] of knownRoots.entries()) {
if (!nextRoots.has(rootKey)) {
removeProject(existingRoot.rootPath);
forgetProjectPath(existingRoot.rootPath);
}
}
for (const project of getAllProjects()) {
const stillAllowed = Array.from(nextRoots.values()).some((knownRoot) =>
isPathWithin(knownRoot.rootPath, project.rootPath)
);
if (!stillAllowed) {
removeProject(project.rootPath);
forgetProjectPath(project.rootPath);
}
}
knownRoots.clear();
clearDiscoveredProjectPaths();
for (const [rootKey, rootEntry] of nextRoots.entries()) {
knownRoots.set(rootKey, rootEntry);
rememberProjectPath(rootEntry.rootPath, 'root', { touch: false });
}
if (activeProjectKey) {
if (!getTrackedRootPathByKey(activeProjectKey)) {
activeProjectKey = undefined;
}
}
}
function parseProjectSelector(value: unknown): string | undefined {
if (typeof value !== 'string') return undefined;
const trimmedValue = value.trim();
if (!trimmedValue) return undefined;
return trimmedValue;
}
function parseProjectDirectory(value: unknown): string | undefined {
const selector = parseProjectSelector(value);
if (!selector) return undefined;
return selector.startsWith('file://')
? path.resolve(fileURLToPath(selector))
: path.resolve(selector);
}
function getProjectSourceForResolvedPath(rootPath: string): ProjectDescriptor['source'] {
return getContainingKnownRoot(rootPath) ? 'subdirectory' : 'ad_hoc';
}
async function resolveProjectFromAbsolutePath(resolvedPath: string): Promise<ProjectResolution> {
const absolutePath = path.resolve(resolvedPath);
const containingRoot = getContainingKnownRoot(absolutePath);
if (clientRootsEnabled && getKnownRootPaths().length > 0 && !containingRoot) {
return {
ok: false,
response: buildProjectSelectionError(
'unknown_project',
'Requested project is not under an active MCP root.'
)
};
}
let stats;
try {
stats = await fs.stat(absolutePath);
} catch {
return {
ok: false,
response: buildProjectSelectionError(
'unknown_project',
`project does not exist: ${absolutePath}`
)
};
}
const lookupPath = stats.isDirectory() ? absolutePath : path.dirname(absolutePath);
const exactDescriptor = listProjectDescriptors().find(
(descriptor) => normalizeRootKey(descriptor.rootPath) === normalizeRootKey(lookupPath)
);
if (exactDescriptor) {
const project = getOrCreateProject(exactDescriptor.rootPath);
if (exactDescriptor.source === 'subdirectory') {
registerDiscoveredProjectPath(exactDescriptor.rootPath, 'subdirectory');
} else {
rememberProjectPath(exactDescriptor.rootPath, exactDescriptor.source, { touch: false });
}
return { ok: true, project };
}
const nearestBoundary = await findNearestProjectBoundary(absolutePath, containingRoot);
const resolvedProjectPath =
nearestBoundary?.rootPath ?? containingRoot ?? (stats.isDirectory() ? absolutePath : undefined);
if (!resolvedProjectPath) {
return {
ok: false,
response: buildProjectSelectionError(
'unknown_project',
`project was not found from path: ${absolutePath}`
)
};
}
const invalidProjectResponse = await validateResolvedProjectPath(resolvedProjectPath);
if (invalidProjectResponse) {
return { ok: false, response: invalidProjectResponse };
}
const projectSource = getProjectSourceForResolvedPath(resolvedProjectPath);
if (projectSource === 'subdirectory') {
registerDiscoveredProjectPath(resolvedProjectPath, 'subdirectory');
} else {
rememberProjectPath(resolvedProjectPath, projectSource, { touch: false });
}
const project = getOrCreateProject(resolvedProjectPath);
return { ok: true, project };
}
function buildProjectSelectionPayload(
status: 'success' | 'selection_required' | 'error',
message: string,
project?: ProjectState,
extras: Record<string, unknown> = {}
): Record<string, unknown> {
return {
status,
message,
activeProject: project
? buildProjectDescriptor(project.rootPath)
: (getActiveProjectDescriptor() ?? null),
availableProjects: listProjectDescriptors(),
...extras
};
}
function buildProjectSelectionError(
errorCode: 'selection_required' | 'unknown_project',
message: string,
extras: Record<string, unknown> = {}
): ToolResponse {
const status = errorCode === 'selection_required' ? 'selection_required' : 'error';
return {
content: [
{
type: 'text',
text: JSON.stringify(
{ ...buildProjectSelectionPayload(status, message, undefined, extras), errorCode },
null,
2
)
}
],
isError: true
};
}
function createToolContext(project: ProjectState): ToolContext {
return {
indexState: project.indexState,
paths: project.paths,
rootPath: project.rootPath,
project: buildProjectDescriptor(project.rootPath),
performIndexing: (incrementalOnly?: boolean) => performIndexing(project, incrementalOnly),
listProjects: () => listProjectDescriptors(),
getActiveProject: () => getActiveProjectDescriptor()
};
}
function createWorkspaceToolContext(): ToolContext {
const fallbackRootPath = primaryRootPath ?? path.resolve(process.cwd());
return {
indexState: { status: 'idle' },
paths: makePaths(fallbackRootPath),
rootPath: fallbackRootPath,
performIndexing: () => undefined,
listProjects: () => listProjectDescriptors(),
getActiveProject: () => getActiveProjectDescriptor()
};
}
if (primaryRootPath) {
registerKnownRoot(primaryRootPath);
}
export const INDEX_CONSUMING_TOOL_NAMES = [
'search_codebase',
'get_symbol_references',
'detect_circular_dependencies',
'get_team_patterns',
'get_codebase_metadata'
] as const;
export const INDEX_CONSUMING_RESOURCE_NAMES = ['Codebase Intelligence'] as const;
type IndexStatus = 'ready' | 'rebuild-required' | 'indexing' | 'unknown';
type IndexConfidence = 'high' | 'low';
type IndexAction = 'served' | 'rebuild-started' | 'rebuilt-and-served';
export type IndexSignal = {
status: IndexStatus;
confidence: IndexConfidence;
action: IndexAction;
reason?: string;
};
async function requireValidIndex(rootPath: string, paths: ToolPaths): Promise<IndexSignal> {
const meta = await readIndexMeta(rootPath);
await validateIndexArtifacts(rootPath, meta);
// Optional artifact presence informs confidence.
const hasIntelligence = await fileExists(paths.intelligence);
return {
status: 'ready',
confidence: hasIntelligence ? 'high' : 'low',
action: 'served',
...(hasIntelligence ? {} : { reason: 'Optional intelligence artifact missing' })
};
}
async function ensureValidIndexOrAutoHeal(project: ProjectState): Promise<IndexSignal> {
if (project.indexState.status === 'indexing') {
return {
status: 'indexing',
confidence: 'low',
action: 'served',
reason: 'Indexing in progress'
};
}
try {
return await requireValidIndex(project.rootPath, project.paths);
} catch (error) {
if (error instanceof IndexCorruptedError) {
const reason = error.message;
console.error(`[Index] ${reason}`);
console.error('[Auto-Heal] Triggering background re-index...');
// Fire-and-forget: don't block the tool call
void performIndexing(project);
return {
status: 'indexing',
confidence: 'low',
action: 'rebuild-started',
reason: `Auto-heal triggered: ${reason}`
};
}
throw error;
}
}
async function validateResolvedProjectPath(rootPath: string): Promise<ToolResponse | undefined> {
try {
const stats = await fs.stat(rootPath);
if (!stats.isDirectory()) {
return buildProjectSelectionError(
'unknown_project',
`project is not a directory: ${rootPath}`
);
}
if (clientRootsEnabled && getKnownRootPaths().length > 0 && !getContainingKnownRoot(rootPath)) {
return buildProjectSelectionError(
'unknown_project',
'Requested project is not under an active MCP root.'
);
}
return undefined;
} catch {
return buildProjectSelectionError('unknown_project', `project does not exist: ${rootPath}`);
}
}
async function resolveProjectSelector(selector: string): Promise<ProjectResolution> {
const trimmedSelector = selector.trim();
if (!trimmedSelector) {
return {
ok: false,
response: buildProjectSelectionError(
'unknown_project',
'project must be a non-empty absolute path, file:// URI, or relative subproject path.'
)
};
}
if (trimmedSelector.startsWith('file://') || path.isAbsolute(trimmedSelector)) {
const resolvedPath = parseProjectDirectory(trimmedSelector);
if (!resolvedPath) {
return {
ok: false,
response: buildProjectSelectionError(
'unknown_project',
'project must be a non-empty absolute path, file:// URI, or relative subproject path.'
)
};
}
return resolveProjectFromAbsolutePath(resolvedPath);
}
const normalizedSelector = trimmedSelector.replace(/\\/g, '/').replace(/^\.\/+/, '');
const descriptorMatches = listProjectDescriptors().filter(
(descriptor) =>
descriptor.label === normalizedSelector ||
descriptor.relativePath === normalizedSelector ||
path.basename(descriptor.rootPath) === normalizedSelector
);
if (descriptorMatches.length === 1) {
const matchedRootPath = descriptorMatches[0].rootPath;
if (descriptorMatches[0].source === 'subdirectory') {
registerDiscoveredProjectPath(matchedRootPath, 'subdirectory');
} else {
rememberProjectPath(matchedRootPath, classifyProjectSource(matchedRootPath), {
touch: false
});
}
const project = getOrCreateProject(matchedRootPath);
return { ok: true, project };
}
if (descriptorMatches.length > 1) {
return {
ok: false,
response: buildProjectSelectionError(
'selection_required',
`Project selector "${normalizedSelector}" matches multiple known projects. Retry with an absolute path.`,
{
reason: 'project_selector_ambiguous',
nextAction: 'retry_with_project'
}
)
};
}
const matchingProjects = getKnownRootPaths()
.map((rootPath) => ({ rootPath, candidatePath: path.resolve(rootPath, normalizedSelector) }))
.filter(({ rootPath, candidatePath }) => isPathWithin(rootPath, candidatePath))
.map(({ candidatePath }) => candidatePath);
const resolvedMatches = new Map<string, ProjectState>();
for (const candidatePath of matchingProjects) {
const resolution = await resolveProjectFromAbsolutePath(candidatePath);
if (resolution.ok) {
resolvedMatches.set(normalizeRootKey(resolution.project.rootPath), resolution.project);
continue;
}
const payload = JSON.parse(resolution.response.content?.[0]?.text ?? '{}') as {
errorCode?: string;
};
if (payload.errorCode !== 'unknown_project') {
return resolution;
}
}
if (resolvedMatches.size === 1) {
const project = Array.from(resolvedMatches.values())[0];
return { ok: true, project };
}
if (resolvedMatches.size > 1) {
return {
ok: false,
response: buildProjectSelectionError(
'selection_required',
`Relative project path "${normalizedSelector}" matches multiple configured roots. Retry with an absolute path.`,
{
reason: 'relative_project_ambiguous',
nextAction: 'retry_with_project'
}
)
};
}
return {
ok: false,
response: buildProjectSelectionError(
'unknown_project',
`Relative project path "${normalizedSelector}" was not found under any configured root.`
)
};
}
/**
* Check if file/directory exists
*/
async function fileExists(filePath: string): Promise<boolean> {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
/**
* Migrate legacy file structure to .codebase-context/ folder.
* Idempotent, fail-safe. Rollback compatibility is not required.
*/
async function migrateToNewStructure(
paths: ToolPaths,
legacyPaths: ReturnType<typeof makeLegacyPaths>
): Promise<boolean> {
let migrated = false;
try {
await fs.mkdir(paths.baseDir, { recursive: true });
// intelligence.json
if (!(await fileExists(paths.intelligence))) {
if (await fileExists(legacyPaths.intelligence)) {
await fs.copyFile(legacyPaths.intelligence, paths.intelligence);
migrated = true;
if (process.env.CODEBASE_CONTEXT_DEBUG) {
console.error('[DEBUG] Migrated intelligence.json');
}
}
}
// index.json (keyword index)
if (!(await fileExists(paths.keywordIndex))) {
if (await fileExists(legacyPaths.keywordIndex)) {
await fs.copyFile(legacyPaths.keywordIndex, paths.keywordIndex);
migrated = true;
if (process.env.CODEBASE_CONTEXT_DEBUG) {
console.error('[DEBUG] Migrated index.json');
}
}
}
// Vector DB directory
if (!(await fileExists(paths.vectorDb))) {
if (await fileExists(legacyPaths.vectorDb)) {
await fs.rename(legacyPaths.vectorDb, paths.vectorDb);
migrated = true;
if (process.env.CODEBASE_CONTEXT_DEBUG) {
console.error('[DEBUG] Migrated vector database');
}
}
}
return migrated;
} catch (error) {
if (process.env.CODEBASE_CONTEXT_DEBUG) {
console.error('[DEBUG] Migration error:', error);
}
return false;
}
}
export type { IndexState } from './tools/types.js';
// Read version from package.json so it never drifts
const PKG_VERSION: string = JSON.parse(
await fs.readFile(new URL('../package.json', import.meta.url), 'utf-8')
).version;
/**
* Register all MCP request handlers on a Server instance.
* Exported so HTTP mode can wire up per-session servers with the
* same handler logic that closes over module-level state.
*/
export function registerHandlers(target: Server): void {
target.setRequestHandler(ListToolsRequestSchema, async () => {
return { tools: TOOLS };
});
target.setRequestHandler(ListResourcesRequestSchema, async () => {
return { resources: buildResources() };
});
target.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const uri = request.params.uri;
const explicitProjectPath = getProjectPathFromContextResourceUri(uri);
if (explicitProjectPath) {
const selection = await resolveProjectSelector(explicitProjectPath);
if (!selection.ok) {
throw new Error(`Unknown project resource: ${uri}`);
}
const project = selection.project;
await initProject(project.rootPath, watcherDebounceMs, { enableWatcher: true });
setActiveProject(project.rootPath);
return {
contents: [
{
uri: buildProjectContextResourceUri(project.rootPath),
mimeType: 'text/plain',
text: await generateCodebaseIntelligence(project)
}
]
};
}
if (isContextResourceUri(uri)) {
const project = await resolveProjectForResource();
return {
contents: [
{
uri: CONTEXT_RESOURCE_URI,
mimeType: 'text/plain',
text: project
? await generateCodebaseIntelligence(project)
: buildProjectSelectionMessage()
}
]
};
}
throw new Error(`Unknown resource: ${uri}`);
});
target.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
const normalizedArgs =
args && typeof args === 'object' && !Array.isArray(args)
? (args as Record<string, unknown>)
: {};
try {
if (!toolNames.has(name)) {
return await dispatchTool(name, normalizedArgs, createWorkspaceToolContext());
}
const projectResolution = await resolveProjectForTool(normalizedArgs);
if (!projectResolution.ok) {
return projectResolution.response;
}
const project = projectResolution.project;
// Gate INDEX_CONSUMING tools on a valid, healthy index
let indexSignal: IndexSignal | undefined;
if ((INDEX_CONSUMING_TOOL_NAMES as readonly string[]).includes(name)) {
if (project.indexState.status === 'indexing') {
return {
content: [
{
type: 'text',
text: JSON.stringify({
status: 'indexing',
message: 'Index build in progress - please retry shortly'
})
}
]
};
}
if (project.indexState.status === 'error') {
return {
content: [
{
type: 'text',
text: JSON.stringify({
status: 'error',
message: `Indexer error: ${project.indexState.error}`
})
}
]
};
}
indexSignal = await ensureValidIndexOrAutoHeal(project);
if (indexSignal.action === 'rebuild-started') {
return {
content: [
{
type: 'text',
text: JSON.stringify({
status: 'indexing',
message: 'Index rebuild in progress - please retry shortly',
index: indexSignal
})
}
]
};
}
}
const result = await dispatchTool(name, normalizedArgs, createToolContext(project));
// Inject routing/index metadata into JSON responses so agents can reuse the resolved project safely.
if (indexSignal !== undefined && result.content?.[0]) {
try {
const parsed = JSON.parse(result.content[0].text);
result.content[0] = {
type: 'text',
text: JSON.stringify({
...parsed,
index: indexSignal,
project: buildProjectDescriptor(project.rootPath)
})
};
} catch {
/* response wasn't JSON, skip injection */
}
} else if (result.content?.[0]) {
try {
const parsed = JSON.parse(result.content[0].text);
result.content[0] = {
type: 'text',
text: JSON.stringify({ ...parsed, project: buildProjectDescriptor(project.rootPath) })
};
} catch {
/* response wasn't JSON, skip injection */
}
}
return result;
} catch (error) {
return {
content: [
{
type: 'text',
text: `Unexpected error: ${error instanceof Error ? error.message : String(error)}`
}
],
isError: true
};
}
});
}
const server: Server = createServer(
{ name: 'codebase-context', version: PKG_VERSION },
registerHandlers
);
function buildResources(): Resource[] {
const resources: Resource[] = [
{
uri: CONTEXT_RESOURCE_URI,
name: 'Codebase Intelligence',
description:
'Context for the active project in this MCP session. In multi-project sessions, this falls back to a workspace overview until a project is selected.',