forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.ts
More file actions
1955 lines (1744 loc) · 73.8 KB
/
tools.ts
File metadata and controls
1955 lines (1744 loc) · 73.8 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
/**
* MCP Tool Definitions
*
* Defines the tools exposed by the CodeGraph MCP server.
*/
import CodeGraph, { findNearestCodeGraphRoot } from '../index';
import type { Node, Edge, SearchResult, Subgraph, TaskContext, NodeKind } from '../types';
import { createHash } from 'crypto';
import {
constants as fsConstants,
closeSync,
existsSync,
lstatSync,
openSync,
readFileSync,
writeSync,
} from 'fs';
import { clamp, validatePathWithinRoot, validateProjectPath } from '../utils';
import { tmpdir } from 'os';
import { join } from 'path';
/** Maximum output length to prevent context bloat (characters) */
const MAX_OUTPUT_LENGTH = 15000;
/**
* Maximum length for free-form string inputs (query, task, symbol).
* Bounds memory and CPU when a buggy or hostile MCP client sends a
* huge payload — without this an attacker could ship a 100MB string
* and force a full FTS5 scan / OOM the server. 10 000 characters is
* far beyond any realistic legitimate query.
*/
const MAX_INPUT_LENGTH = 10_000;
/**
* Maximum length for path-like string inputs (projectPath, path
* filter, glob pattern). Paths beyond a few thousand chars are
* never legitimate and signal abuse or a bug upstream.
*/
const MAX_PATH_LENGTH = 4_096;
/**
* Rust path roots that have no file-system equivalent — `crate` is the
* current crate, `super` is the parent module, `self` is the current
* module. Used by `matchesSymbol` to strip these before file-path
* matching so `crate::configurator::stage_apply::run` resolves the
* same as `configurator::stage_apply::run`.
*/
const RUST_PATH_PREFIXES = new Set(['crate', 'super', 'self']);
/**
* Node kinds that contain other symbols. For these, `codegraph_node` with
* `includeCode=true` returns a structural outline (member names + signatures
* + line numbers) instead of the full body, which for a large class is a
* multi-thousand-character wall of source that bloats the agent's context.
*/
const CONTAINER_NODE_KINDS = new Set<NodeKind>([
'class', 'struct', 'interface', 'trait', 'protocol', 'enum', 'namespace', 'module',
]);
/** Last `::` / `.` / `/`-separated segment of a qualified symbol. */
function lastQualifierPart(symbol: string): string {
const parts = symbol.split(/::|[./]/).filter((p) => p.length > 0);
return parts[parts.length - 1] ?? symbol;
}
/**
* Calculate the recommended number of codegraph_explore calls based on project size.
* Larger codebases need more exploration calls to cover their surface area,
* but smaller ones should use fewer to avoid unnecessary overhead.
*/
export function getExploreBudget(fileCount: number): number {
if (fileCount < 500) return 1;
if (fileCount < 5000) return 2;
if (fileCount < 15000) return 3;
if (fileCount < 25000) return 4;
return 5;
}
/**
* Adaptive output budget for `codegraph_explore`, scaled to project size.
*
* Smaller codebases get a tighter total cap, fewer default files, smaller
* per-file cap, and tighter clustering — so a focused query on a 100-file
* project doesn't dump a whole file's worth of source into the agent's
* context. Larger codebases keep the generous defaults because the
* agent's native discovery cost (grep + find + many Reads) genuinely
* dwarfs a fat explore call at that scale.
*
* Meta-text (relationships map, "additional relevant files" list,
* completeness signal, budget note) is gated off for tiny projects
* where one rich call is the whole story and the extra prose is just
* overhead.
*
* Tier breakpoints mirror `getExploreBudget` so a project sits in the
* same tier across both knobs.
*/
export interface ExploreOutputBudget {
/** Hard cap on total output characters. */
maxOutputChars: number;
/** Default `maxFiles` when the caller didn't specify one. */
defaultMaxFiles: number;
/** Cap on contiguous source returned per file (across all its clusters). */
maxCharsPerFile: number;
/** Cluster gap threshold in lines — tighter clustering on small projects. */
gapThreshold: number;
/** Max symbols listed in the per-file header (`#### path — sym(kind), ...`). */
maxSymbolsInFileHeader: number;
/** Max edges shown per relationship kind in the Relationships section. */
maxEdgesPerRelationshipKind: number;
/** Include the "Relationships" section. */
includeRelationships: boolean;
/** Include the "Additional relevant files (not shown)" trailing list. */
includeAdditionalFiles: boolean;
/** Include the "Complete source code is included above…" reminder. */
includeCompletenessSignal: boolean;
/** Include the explore-budget reminder at the end. */
includeBudgetNote: boolean;
}
export function getExploreOutputBudget(fileCount: number): ExploreOutputBudget {
if (fileCount < 500) {
return {
maxOutputChars: 18000,
defaultMaxFiles: 5,
maxCharsPerFile: 3800,
gapThreshold: 8,
maxSymbolsInFileHeader: 6,
maxEdgesPerRelationshipKind: 6,
includeRelationships: true,
includeAdditionalFiles: false,
includeCompletenessSignal: false,
includeBudgetNote: false,
};
}
if (fileCount < 5000) {
return {
maxOutputChars: 13000,
defaultMaxFiles: 6,
maxCharsPerFile: 2500,
gapThreshold: 10,
maxSymbolsInFileHeader: 8,
maxEdgesPerRelationshipKind: 8,
includeRelationships: true,
includeAdditionalFiles: true,
includeCompletenessSignal: true,
includeBudgetNote: true,
};
}
if (fileCount < 15000) {
return {
maxOutputChars: 35000,
defaultMaxFiles: 12,
maxCharsPerFile: 7000,
gapThreshold: 15,
maxSymbolsInFileHeader: 15,
maxEdgesPerRelationshipKind: 15,
includeRelationships: true,
includeAdditionalFiles: true,
includeCompletenessSignal: true,
includeBudgetNote: true,
};
}
return {
maxOutputChars: 38000,
defaultMaxFiles: 14,
maxCharsPerFile: 7000,
gapThreshold: 15,
maxSymbolsInFileHeader: 15,
maxEdgesPerRelationshipKind: 15,
includeRelationships: true,
includeAdditionalFiles: true,
includeCompletenessSignal: true,
includeBudgetNote: true,
};
}
/**
* Whether `codegraph_explore` should prefix source lines with their line
* numbers (cat -n style: `<num>\t<code>`).
*
* Line numbers let the agent cite `file:line` straight from the explore
* payload instead of re-Reading the file just to find a line number — the
* dominant residual cost on precise-tracing questions (#185 follow-up).
*
* Defaults ON. Set `CODEGRAPH_EXPLORE_LINENUMS=0` to disable (used by the
* A/B harness to measure the payload-cost vs. read-savings tradeoff).
*/
function exploreLineNumbersEnabled(): boolean {
return process.env.CODEGRAPH_EXPLORE_LINENUMS !== '0';
}
/**
* Prefix each line of a source slice with its 1-based line number, matching
* the Read tool's `cat -n` convention (number + tab) so the agent treats it
* the same way it treats Read output.
*
* @param slice contiguous source text (already extracted from the file)
* @param firstLineNumber the 1-based line number of the slice's first line
*/
function numberSourceLines(slice: string, firstLineNumber: number): string {
const out: string[] = [];
const split = slice.split('\n');
for (let i = 0; i < split.length; i++) {
out.push(`${firstLineNumber + i}\t${split[i]}`);
}
return out.join('\n');
}
/**
* Mark a Claude session as having consulted MCP tools.
* This enables Grep/Glob/Bash commands that would otherwise be blocked.
*
* Why the explicit openSync + O_NOFOLLOW dance instead of plain writeFileSync:
* tmpdir() is world-writable on Linux (mode 1777), so on a shared multi-user
* machine any other local user can pre-create `codegraph-consulted-<hash>` as
* a symlink pointing at a file the victim owns. The old `writeFileSync` would
* happily follow that link and overwrite the target's contents with the ISO
* timestamp string (CWE-59). The session-id hash provides the predictability
* gate, but it's defense-in-depth: if a session id ever surfaces in logs,
* argv, or telemetry the attack becomes trivial, and the right fix is to not
* follow links from /tmp paths in the first place.
*/
function markSessionConsulted(sessionId: string): void {
try {
const hash = createHash('md5').update(sessionId).digest('hex').slice(0, 16);
const markerPath = join(tmpdir(), `codegraph-consulted-${hash}`);
// Refuse to follow a pre-planted symlink at the marker path (CWE-59).
// O_NOFOLLOW (below) is the atomic, TOCTOU-free guard on POSIX, but it is
// `undefined` on Windows (libuv ignores it), so the bitwise-OR silently
// drops it and openSync would follow the link. This lstat check closes that
// gap cross-platform; ENOENT (path is free) falls through to create it.
try {
if (lstatSync(markerPath).isSymbolicLink()) return;
} catch {
// No existing entry (or stat failed) — nothing to refuse; proceed.
}
// O_NOFOLLOW makes openSync throw ELOOP if markerPath is already a symlink.
// O_CREAT + O_TRUNC keep the original "create-or-overwrite" semantics, and
// mode 0o600 prevents readback by other local users (the marker payload is
// benign, but narrowing the exposure costs nothing).
const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC | fsConstants.O_NOFOLLOW;
const fd = openSync(markerPath, flags, 0o600);
try {
writeSync(fd, new Date().toISOString());
} finally {
closeSync(fd);
}
} catch {
// Silently fail - don't break MCP on marker write failure. ELOOP from a
// planted symlink lands here too, which is the intended behavior: refuse
// to write rather than overwrite an attacker-chosen target.
}
}
/**
* MCP Tool definition
*/
export interface ToolDefinition {
name: string;
description: string;
inputSchema: {
type: 'object';
properties: Record<string, PropertySchema>;
required?: string[];
};
}
interface PropertySchema {
type: string;
description: string;
enum?: string[];
default?: unknown;
}
/**
* Tool execution result
*/
export interface ToolResult {
content: Array<{
type: 'text';
text: string;
}>;
isError?: boolean;
}
/**
* Common projectPath property for cross-project queries
*/
const projectPathProperty: PropertySchema = {
type: 'string',
description: 'Path to a different project with .codegraph/ initialized. If omitted, uses current project. Use this to query other codebases.',
};
/**
* All CodeGraph MCP tools
*
* Designed for minimal context usage - use codegraph_context as the primary tool,
* and only use other tools for targeted follow-up queries.
*
* All tools support cross-project queries via the optional `projectPath` parameter.
*/
export const tools: ToolDefinition[] = [
{
name: 'codegraph_search',
description: 'Quick symbol search by name. Returns locations only (no code). Use codegraph_context instead for comprehensive task context.',
inputSchema: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'Symbol name or partial name (e.g., "auth", "signIn", "UserService")',
},
kind: {
type: 'string',
description: 'Filter by node kind',
enum: ['function', 'method', 'class', 'interface', 'type', 'variable', 'route', 'component'],
},
limit: {
type: 'number',
description: 'Maximum results (default: 10)',
default: 10,
},
projectPath: projectPathProperty,
},
required: ['query'],
},
},
{
name: 'codegraph_context',
description: 'PRIMARY TOOL — call this FIRST for any "how does X work", architecture, feature, or bug-context question. Composes search + node + callers + callees and returns entry points, related symbols, and key code in ONE call — usually enough to answer with no further search/Read/Grep. Prefer this over chaining codegraph_search + codegraph_node, and over codegraph_explore. NOTE: provides CODE context, not product requirements; for new features still clarify UX/edge cases with the user.',
inputSchema: {
type: 'object',
properties: {
task: {
type: 'string',
description: 'Description of the task, bug, or feature to build context for',
},
maxNodes: {
type: 'number',
description: 'Maximum symbols to include (default: 20)',
default: 20,
},
includeCode: {
type: 'boolean',
description: 'Include code snippets for key symbols (default: true)',
default: true,
},
projectPath: projectPathProperty,
},
required: ['task'],
},
},
{
name: 'codegraph_callers',
description: 'Find all functions/methods that call a specific symbol. Useful for understanding usage patterns and impact of changes.',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Name of the function, method, or class to find callers for',
},
limit: {
type: 'number',
description: 'Maximum number of callers to return (default: 20)',
default: 20,
},
projectPath: projectPathProperty,
},
required: ['symbol'],
},
},
{
name: 'codegraph_callees',
description: 'Find all functions/methods that a specific symbol calls. Useful for understanding dependencies and code flow.',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Name of the function, method, or class to find callees for',
},
limit: {
type: 'number',
description: 'Maximum number of callees to return (default: 20)',
default: 20,
},
projectPath: projectPathProperty,
},
required: ['symbol'],
},
},
{
name: 'codegraph_impact',
description: 'Analyze the impact radius of changing a symbol. Shows what code could be affected by modifications.',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Name of the symbol to analyze impact for',
},
depth: {
type: 'number',
description: 'How many levels of dependencies to traverse (default: 2)',
default: 2,
},
projectPath: projectPathProperty,
},
required: ['symbol'],
},
},
{
name: 'codegraph_node',
description: 'Get detailed info about ONE symbol (location, signature, docstring). Pass includeCode=true for source: a function/method returns its body; a class/interface/struct/enum returns a compact member OUTLINE (fields + method signatures + line numbers), not every method body — Read or codegraph_node a specific member for its body. Keep includeCode=false to minimize context. For SEVERAL related symbols, make ONE codegraph_explore (or codegraph_context) call instead of many node calls — repeated node calls each re-read the whole context and cost far more.',
inputSchema: {
type: 'object',
properties: {
symbol: {
type: 'string',
description: 'Name of the symbol to get details for',
},
includeCode: {
type: 'boolean',
description: 'Include full source code (default: false to minimize context)',
default: false,
},
projectPath: projectPathProperty,
},
required: ['symbol'],
},
},
{
name: 'codegraph_explore',
description: 'Returns source for SEVERAL related symbols grouped by file, plus a relationship map, in ONE capped call. This is the efficient way to inspect many related symbols at once — strongly prefer it over a series of codegraph_node or Read calls (each separate call re-reads the whole context, so 8 node calls cost far more than 1 explore). Use it after codegraph_context when you need to see the actual source of several symbols. Query with specific symbol/file/code terms, NOT natural-language sentences — run codegraph_search first to find names. Bad: "how are agent prompts loaded and passed to the CLI". Good: "renderStaticScene drawElementOnCanvas ShapeCache renderElement.ts".',
inputSchema: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'Symbol names, file names, or short code terms to explore (e.g., "AuthService loginUser session-manager", "GraphTraverser BFS impact traversal.ts"). Use codegraph_search first to find relevant names.',
},
maxFiles: {
type: 'number',
description: 'Maximum number of files to include source code from (default: 12)',
default: 12,
},
projectPath: projectPathProperty,
},
required: ['query'],
},
},
{
name: 'codegraph_status',
description: 'Get the status of the CodeGraph index, including statistics about indexed files, nodes, and edges.',
inputSchema: {
type: 'object',
properties: {
projectPath: projectPathProperty,
},
},
},
{
name: 'codegraph_files',
description: 'REQUIRED for file/folder exploration. Get the project file structure from the CodeGraph index. Returns a tree view of all indexed files with metadata (language, symbol count). Much faster than Glob/filesystem scanning. Use this FIRST when exploring project structure, finding files, or understanding codebase organization.',
inputSchema: {
type: 'object',
properties: {
path: {
type: 'string',
description: 'Filter to files under this directory path (e.g., "src/components"). Returns all files if not specified.',
},
pattern: {
type: 'string',
description: 'Filter files matching this glob pattern (e.g., "*.tsx", "**/*.test.ts")',
},
format: {
type: 'string',
description: 'Output format: "tree" (hierarchical, default), "flat" (simple list), "grouped" (by language)',
enum: ['tree', 'flat', 'grouped'],
default: 'tree',
},
includeMetadata: {
type: 'boolean',
description: 'Include file metadata like language and symbol count (default: true)',
default: true,
},
maxDepth: {
type: 'number',
description: 'Maximum directory depth to show (default: unlimited)',
},
projectPath: projectPathProperty,
},
},
},
];
/**
* Tool handler that executes tools against a CodeGraph instance
*
* Supports cross-project queries via the projectPath parameter.
* Other projects are opened on-demand and cached for performance.
*/
export class ToolHandler {
// Cache of opened CodeGraph instances for cross-project queries
private projectCache: Map<string, CodeGraph> = new Map();
// The directory the server last searched for a default project. Surfaced in
// the "not initialized" error so users can see why detection missed.
private defaultProjectHint: string | null = null;
constructor(private cg: CodeGraph | null) {}
/**
* Update the default CodeGraph instance (e.g. after lazy initialization)
*/
setDefaultCodeGraph(cg: CodeGraph): void {
this.cg = cg;
}
/**
* Record the directory the server tried to resolve the default project from.
* Used only to make the "no default project" error actionable.
*/
setDefaultProjectHint(searchedPath: string): void {
this.defaultProjectHint = searchedPath;
}
/**
* Whether a default CodeGraph instance is available
*/
hasDefaultCodeGraph(): boolean {
return this.cg !== null;
}
/**
* Get tool definitions with dynamic descriptions based on project size.
* The codegraph_explore tool description includes a budget recommendation
* scaled to the number of indexed files.
*/
getTools(): ToolDefinition[] {
if (!this.cg) return tools;
try {
const stats = this.cg.getStats();
const budget = getExploreBudget(stats.fileCount);
return tools.map(tool => {
if (tool.name === 'codegraph_explore') {
return {
...tool,
description: `${tool.description} Budget: make at most ${budget} calls for this project (${stats.fileCount.toLocaleString()} files indexed).`,
};
}
return tool;
});
} catch {
return tools;
}
}
/**
* Get CodeGraph instance for a project
*
* If projectPath is provided, opens that project's CodeGraph (cached).
* Otherwise returns the default CodeGraph instance.
*
* Walks up parent directories to find the nearest .codegraph/ folder,
* similar to how git finds .git/ directories.
*/
private getCodeGraph(projectPath?: string): CodeGraph {
if (!projectPath) {
if (!this.cg) {
const searched = this.defaultProjectHint ?? process.cwd();
throw new Error(
'No CodeGraph project is loaded for this session.\n' +
`Searched for a .codegraph/ directory starting from: ${searched}\n` +
'The index is likely fine — this is a working-directory detection issue: ' +
"the MCP client launched the server outside your project and didn't report the " +
'workspace root. Fix it either way:\n' +
' • Pass projectPath to the tool call, e.g. projectPath: "/absolute/path/to/your/project"\n' +
' • Or add --path to the server\'s MCP config args: ["serve", "--mcp", "--path", "/absolute/path/to/your/project"]'
);
}
return this.cg;
}
// Check cache first (using original path as key)
if (this.projectCache.has(projectPath)) {
return this.projectCache.get(projectPath)!;
}
// Reject sensitive system directories before opening. Only validate a
// path that actually exists — a nested or not-yet-created sub-path of a
// real project must still be allowed to resolve UP to its .codegraph/
// root below (issue #238), so we don't run the existence-checking
// validator on paths that are meant to walk up.
if (existsSync(projectPath)) {
const pathError = validateProjectPath(projectPath);
if (pathError) {
throw new Error(pathError);
}
}
// Walk up parent directories to find nearest .codegraph/
const resolvedRoot = findNearestCodeGraphRoot(projectPath);
if (!resolvedRoot) {
throw new Error(`CodeGraph not initialized in ${projectPath}. Run 'codegraph init' in that project first.`);
}
// If the path resolves to the default project, reuse the already-open
// default instance rather than opening a SECOND connection to the same DB.
// A duplicate connection serializes reads against the watcher's auto-sync
// writes; on the wasm backend (no WAL) that surfaces as intermittent
// "database is locked" on concurrent tool calls. See issue #238. Deliberately
// not cached under projectPath — the server owns and closes the default
// instance, so routing it through projectCache.closeAll() would double-close it.
if (this.cg && this.cg.getProjectRoot() === resolvedRoot) {
return this.cg;
}
// Check if we already have this resolved root cached (different path, same project)
if (this.projectCache.has(resolvedRoot)) {
const cg = this.projectCache.get(resolvedRoot)!;
// Cache under original path too for faster future lookups
this.projectCache.set(projectPath, cg);
return cg;
}
// Open and cache under both paths
const cg = CodeGraph.openSync(resolvedRoot);
this.projectCache.set(resolvedRoot, cg);
if (projectPath !== resolvedRoot) {
this.projectCache.set(projectPath, cg);
}
return cg;
}
/**
* Close all cached project connections
*/
closeAll(): void {
for (const cg of this.projectCache.values()) {
cg.close();
}
this.projectCache.clear();
}
/**
* Validate that a value is a non-empty string within length bounds.
*
* The `maxLength` cap protects against MCP clients that ship huge
* payloads (10MB+ query strings either by accident or maliciously).
* Without this, a single oversized input can pin the FTS5 index or
* exhaust memory before any real work runs.
*/
private validateString(
value: unknown,
name: string,
maxLength: number = MAX_INPUT_LENGTH
): string | ToolResult {
if (typeof value !== 'string' || value.length === 0) {
return this.errorResult(`${name} must be a non-empty string`);
}
if (value.length > maxLength) {
return this.errorResult(
`${name} exceeds maximum length of ${maxLength} characters (got ${value.length})`
);
}
return value;
}
/**
* Validate an optional path-like string input. Returns the value if
* valid (or undefined), or a ToolResult with the error.
*/
private validateOptionalPath(
value: unknown,
name: string
): string | undefined | ToolResult {
if (value === undefined || value === null) return undefined;
if (typeof value !== 'string') {
return this.errorResult(`${name} must be a string`);
}
if (value.length > MAX_PATH_LENGTH) {
return this.errorResult(
`${name} exceeds maximum length of ${MAX_PATH_LENGTH} characters (got ${value.length})`
);
}
return value;
}
/**
* Execute a tool by name
*/
async execute(toolName: string, args: Record<string, unknown>): Promise<ToolResult> {
try {
// Cross-cutting input validation. All tools accept an optional
// `projectPath` and most accept either `query`, `task`, or
// `symbol` — bound their lengths centrally so individual handlers
// can stay focused on tool-specific logic.
const pathCheck = this.validateOptionalPath(args.projectPath, 'projectPath');
if (typeof pathCheck === 'object' && pathCheck !== undefined) {
return pathCheck;
}
// The `path` and `pattern` properties used by codegraph_files are
// also path-shaped — apply the same cap.
if (args.path !== undefined) {
const check = this.validateOptionalPath(args.path, 'path');
if (typeof check === 'object' && check !== undefined) return check;
}
if (args.pattern !== undefined) {
const check = this.validateOptionalPath(args.pattern, 'pattern');
if (typeof check === 'object' && check !== undefined) return check;
}
switch (toolName) {
case 'codegraph_search':
return await this.handleSearch(args);
case 'codegraph_context':
return await this.handleContext(args);
case 'codegraph_callers':
return await this.handleCallers(args);
case 'codegraph_callees':
return await this.handleCallees(args);
case 'codegraph_impact':
return await this.handleImpact(args);
case 'codegraph_explore':
return await this.handleExplore(args);
case 'codegraph_node':
return await this.handleNode(args);
case 'codegraph_status':
return await this.handleStatus(args);
case 'codegraph_files':
return await this.handleFiles(args);
default:
return this.errorResult(`Unknown tool: ${toolName}`);
}
} catch (err) {
return this.errorResult(`Tool execution failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
/**
* Handle codegraph_search
*/
private async handleSearch(args: Record<string, unknown>): Promise<ToolResult> {
const query = this.validateString(args.query, 'query');
if (typeof query !== 'string') return query;
const cg = this.getCodeGraph(args.projectPath as string | undefined);
const kind = args.kind as string | undefined;
const rawLimit = Number(args.limit) || 10;
const limit = clamp(rawLimit, 1, 100);
const results = cg.searchNodes(query, {
limit,
kinds: kind ? [kind as NodeKind] : undefined,
});
if (results.length === 0) {
return this.textResult(`No results found for "${query}"`);
}
const formatted = this.formatSearchResults(results);
return this.textResult(this.truncateOutput(formatted));
}
/**
* Handle codegraph_context
*/
private async handleContext(args: Record<string, unknown>): Promise<ToolResult> {
const task = this.validateString(args.task, 'task');
if (typeof task !== 'string') return task;
// Mark session as consulted (enables Grep/Glob/Bash)
const sessionId = process.env.CLAUDE_SESSION_ID;
if (sessionId) {
markSessionConsulted(sessionId);
}
const cg = this.getCodeGraph(args.projectPath as string | undefined);
const maxNodes = (args.maxNodes as number) || 20;
const includeCode = args.includeCode !== false;
const context = await cg.buildContext(task, {
maxNodes,
includeCode,
format: 'markdown',
});
// Detect if this looks like a feature request (vs bug fix or exploration)
const isFeatureQuery = this.looksLikeFeatureRequest(task);
const reminder = isFeatureQuery
? '\n\n⚠️ **Ask user:** UX preferences, edge cases, acceptance criteria'
: '';
// buildContext returns string when format is 'markdown'
if (typeof context === 'string') {
return this.textResult(this.truncateOutput(context + reminder));
}
// If it returns TaskContext, format it
return this.textResult(this.truncateOutput(this.formatTaskContext(context) + reminder));
}
/**
* Heuristic to detect if a query looks like a feature request
*/
private looksLikeFeatureRequest(task: string): boolean {
const featureKeywords = [
'add', 'create', 'implement', 'build', 'enable', 'allow',
'new feature', 'support for', 'ability to', 'want to',
'should be able', 'need to add', 'swap', 'edit', 'modify'
];
const bugKeywords = [
'fix', 'bug', 'error', 'broken', 'crash', 'issue', 'problem',
'not working', 'fails', 'undefined', 'null'
];
const explorationKeywords = [
'how does', 'where is', 'what is', 'find', 'show me',
'explain', 'understand', 'explore'
];
const lowerTask = task.toLowerCase();
// If it's clearly a bug or exploration, not a feature
if (bugKeywords.some(k => lowerTask.includes(k))) return false;
if (explorationKeywords.some(k => lowerTask.includes(k))) return false;
// If it matches feature keywords, it's likely a feature request
return featureKeywords.some(k => lowerTask.includes(k));
}
/**
* Handle codegraph_callers
*/
private async handleCallers(args: Record<string, unknown>): Promise<ToolResult> {
const symbol = this.validateString(args.symbol, 'symbol');
if (typeof symbol !== 'string') return symbol;
const cg = this.getCodeGraph(args.projectPath as string | undefined);
const limit = clamp((args.limit as number) || 20, 1, 100);
const allMatches = this.findAllSymbols(cg, symbol);
if (allMatches.nodes.length === 0) {
return this.textResult(`Symbol "${symbol}" not found in the codebase`);
}
// Aggregate callers across all matching symbols
const seen = new Set<string>();
const allCallers: Node[] = [];
for (const node of allMatches.nodes) {
for (const c of cg.getCallers(node.id)) {
if (!seen.has(c.node.id)) {
seen.add(c.node.id);
allCallers.push(c.node);
}
}
}
if (allCallers.length === 0) {
return this.textResult(`No callers found for "${symbol}"${allMatches.note}`);
}
const formatted = this.formatNodeList(allCallers.slice(0, limit), `Callers of ${symbol}`) + allMatches.note;
return this.textResult(this.truncateOutput(formatted));
}
/**
* Handle codegraph_callees
*/
private async handleCallees(args: Record<string, unknown>): Promise<ToolResult> {
const symbol = this.validateString(args.symbol, 'symbol');
if (typeof symbol !== 'string') return symbol;
const cg = this.getCodeGraph(args.projectPath as string | undefined);
const limit = clamp((args.limit as number) || 20, 1, 100);
const allMatches = this.findAllSymbols(cg, symbol);
if (allMatches.nodes.length === 0) {
return this.textResult(`Symbol "${symbol}" not found in the codebase`);
}
// Aggregate callees across all matching symbols
const seen = new Set<string>();
const allCallees: Node[] = [];
for (const node of allMatches.nodes) {
for (const c of cg.getCallees(node.id)) {
if (!seen.has(c.node.id)) {
seen.add(c.node.id);
allCallees.push(c.node);
}
}
}
if (allCallees.length === 0) {
return this.textResult(`No callees found for "${symbol}"${allMatches.note}`);
}
const formatted = this.formatNodeList(allCallees.slice(0, limit), `Callees of ${symbol}`) + allMatches.note;
return this.textResult(this.truncateOutput(formatted));
}
/**
* Handle codegraph_impact
*/
private async handleImpact(args: Record<string, unknown>): Promise<ToolResult> {
const symbol = this.validateString(args.symbol, 'symbol');
if (typeof symbol !== 'string') return symbol;
const cg = this.getCodeGraph(args.projectPath as string | undefined);
const depth = clamp((args.depth as number) || 2, 1, 10);
const allMatches = this.findAllSymbols(cg, symbol);
if (allMatches.nodes.length === 0) {
return this.textResult(`Symbol "${symbol}" not found in the codebase`);
}
// Aggregate impact across all matching symbols
const mergedNodes = new Map<string, Node>();
const mergedEdges: Edge[] = [];
const seenEdges = new Set<string>();
for (const node of allMatches.nodes) {
const impact = cg.getImpactRadius(node.id, depth);
for (const [id, n] of impact.nodes) {
mergedNodes.set(id, n);
}
for (const e of impact.edges) {
const key = `${e.source}->${e.target}:${e.kind}`;
if (!seenEdges.has(key)) {
seenEdges.add(key);
mergedEdges.push(e);
}
}
}
const mergedImpact = {
nodes: mergedNodes,
edges: mergedEdges,
roots: allMatches.nodes.map(n => n.id),
};
const formatted = this.formatImpact(symbol, mergedImpact) + allMatches.note;
return this.textResult(this.truncateOutput(formatted));
}
/**
* Handle codegraph_explore — deep exploration in a single call
*
* Strategy: find relevant symbols via graph traversal, group by file,
* then read contiguous file sections covering all symbols per file.
* This replaces multiple codegraph_node + Read calls.
*
* Output size is adaptive to project file count via
* `getExploreOutputBudget` — see #185 for why a fixed 35k cap was a
* tax on small projects while earning its keep on large ones.
*/
private async handleExplore(args: Record<string, unknown>): Promise<ToolResult> {
const query = this.validateString(args.query, 'query');
if (typeof query !== 'string') return query;
const cg = this.getCodeGraph(args.projectPath as string | undefined);
const projectRoot = cg.getProjectRoot();
// Resolve adaptive output budget from project size. Falls back to the
// largest-tier defaults if stats aren't available, which preserves
// pre-#185 behavior for callers that hit the rare stats failure.
let budget: ExploreOutputBudget;
try {
budget = getExploreOutputBudget(cg.getStats().fileCount);
} catch {
budget = getExploreOutputBudget(Infinity);
}
const maxFiles = clamp((args.maxFiles as number) || budget.defaultMaxFiles, 1, 20);
// Step 1: Find relevant context with generous parameters.
// Use a large maxNodes budget — explore has its own 35k char output limit
// that prevents context bloat, so more nodes just means better coverage
// across entry points (especially for large files like Svelte components).
const subgraph = await cg.findRelevantContext(query, {
searchLimit: 8,
traversalDepth: 3,
maxNodes: 200,
minScore: 0.2,
});
if (subgraph.nodes.size === 0) {
return this.textResult(`No relevant code found for "${query}"`);
}
// Step 2: Group nodes by file, score by relevance
const fileGroups = new Map<string, { nodes: Node[]; score: number }>();
const entryNodeIds = new Set(subgraph.roots);
// Build a set of nodes directly connected to entry points (depth 1)
const connectedToEntry = new Set<string>();
for (const edge of subgraph.edges) {