-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmcp.js
More file actions
1125 lines (1105 loc) · 38.4 KB
/
Copy pathmcp.js
File metadata and controls
1125 lines (1105 loc) · 38.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
/**
* MCP (Model Context Protocol) server for codegraph.
* Exposes codegraph queries as tools that AI coding assistants can call.
*
* Requires: npm install @modelcontextprotocol/sdk
*/
import { createRequire } from 'node:module';
import { findCycles } from './cycles.js';
import { findDbPath } from './db.js';
import { MCP_DEFAULTS, MCP_MAX_LIMIT } from './paginate.js';
import { ALL_SYMBOL_KINDS, diffImpactMermaid, VALID_ROLES } from './queries.js';
const REPO_PROP = {
repo: {
type: 'string',
description: 'Repository name from the registry (omit for local project)',
},
};
const PAGINATION_PROPS = {
limit: { type: 'number', description: 'Max results to return (pagination)' },
offset: { type: 'number', description: 'Skip this many results (pagination, default: 0)' },
};
const BASE_TOOLS = [
{
name: 'query_function',
description: 'Find callers and callees of a function by name',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Function name to query (supports partial match)' },
depth: {
type: 'number',
description: 'Traversal depth for transitive callers',
default: 2,
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
...PAGINATION_PROPS,
},
required: ['name'],
},
},
{
name: 'file_deps',
description: 'Show what a file imports and what imports it',
inputSchema: {
type: 'object',
properties: {
file: { type: 'string', description: 'File path (partial match supported)' },
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
...PAGINATION_PROPS,
},
required: ['file'],
},
},
{
name: 'impact_analysis',
description: 'Show files affected by changes to a given file (transitive)',
inputSchema: {
type: 'object',
properties: {
file: { type: 'string', description: 'File path to analyze' },
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
...PAGINATION_PROPS,
},
required: ['file'],
},
},
{
name: 'find_cycles',
description: 'Detect circular dependencies in the codebase',
inputSchema: {
type: 'object',
properties: {},
},
},
{
name: 'module_map',
description: 'Get high-level overview of most-connected files',
inputSchema: {
type: 'object',
properties: {
limit: { type: 'number', description: 'Number of top files to show', default: 20 },
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
},
},
},
{
name: 'fn_deps',
description: 'Show function-level dependency chain: what a function calls and what calls it',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Function/method/class name (partial match)' },
depth: { type: 'number', description: 'Transitive caller depth', default: 3 },
file: {
type: 'string',
description: 'Scope search to functions in this file (partial match)',
},
kind: {
type: 'string',
enum: ALL_SYMBOL_KINDS,
description: 'Filter to a specific symbol kind',
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
...PAGINATION_PROPS,
},
required: ['name'],
},
},
{
name: 'fn_impact',
description:
'Show function-level blast radius: all functions transitively affected by changes to a function',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Function/method/class name (partial match)' },
depth: { type: 'number', description: 'Max traversal depth', default: 5 },
file: {
type: 'string',
description: 'Scope search to functions in this file (partial match)',
},
kind: {
type: 'string',
enum: ALL_SYMBOL_KINDS,
description: 'Filter to a specific symbol kind',
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
...PAGINATION_PROPS,
},
required: ['name'],
},
},
{
name: 'symbol_path',
description: 'Find the shortest path between two symbols in the call graph (A calls...calls B)',
inputSchema: {
type: 'object',
properties: {
from: { type: 'string', description: 'Source symbol name (partial match)' },
to: { type: 'string', description: 'Target symbol name (partial match)' },
max_depth: { type: 'number', description: 'Maximum BFS depth', default: 10 },
edge_kinds: {
type: 'array',
items: { type: 'string' },
description: 'Edge kinds to follow (default: ["calls"])',
},
reverse: { type: 'boolean', description: 'Follow edges backward', default: false },
from_file: { type: 'string', description: 'Disambiguate source by file (partial match)' },
to_file: { type: 'string', description: 'Disambiguate target by file (partial match)' },
kind: {
type: 'string',
enum: ALL_SYMBOL_KINDS,
description: 'Filter both symbols by kind',
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
},
required: ['from', 'to'],
},
},
{
name: 'context',
description:
'Full context for a function: source code, dependencies with summaries, callers, signature, and related tests — everything needed to understand or modify a function in one call',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Function/method/class name (partial match)' },
depth: {
type: 'number',
description: 'Include callee source up to N levels deep (0=no source, 1=direct)',
default: 0,
},
file: {
type: 'string',
description: 'Scope search to functions in this file (partial match)',
},
kind: {
type: 'string',
enum: ALL_SYMBOL_KINDS,
description: 'Filter to a specific symbol kind',
},
no_source: {
type: 'boolean',
description: 'Skip source extraction (metadata only)',
default: false,
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
include_tests: {
type: 'boolean',
description: 'Include test file source code',
default: false,
},
...PAGINATION_PROPS,
},
required: ['name'],
},
},
{
name: 'explain',
description:
'Structural summary of a file or function: public/internal API, data flow, dependencies. No LLM needed.',
inputSchema: {
type: 'object',
properties: {
target: { type: 'string', description: 'File path or function name' },
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
...PAGINATION_PROPS,
},
required: ['target'],
},
},
{
name: 'where',
description:
'Find where a symbol is defined and used, or list symbols/imports/exports for a file. Minimal, fast lookup.',
inputSchema: {
type: 'object',
properties: {
target: { type: 'string', description: 'Symbol name or file path' },
file_mode: {
type: 'boolean',
description: 'Treat target as file path (list symbols/imports/exports)',
default: false,
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
...PAGINATION_PROPS,
},
required: ['target'],
},
},
{
name: 'diff_impact',
description: 'Analyze git diff to find which functions changed and their transitive callers',
inputSchema: {
type: 'object',
properties: {
staged: { type: 'boolean', description: 'Analyze staged changes only', default: false },
ref: { type: 'string', description: 'Git ref to diff against (default: HEAD)' },
depth: { type: 'number', description: 'Transitive caller depth', default: 3 },
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
format: {
type: 'string',
enum: ['json', 'mermaid'],
description: 'Output format (default: json)',
},
...PAGINATION_PROPS,
},
},
},
{
name: 'semantic_search',
description:
'Search code symbols by meaning using embeddings and/or keyword matching (requires prior `codegraph embed`). Default hybrid mode combines BM25 keyword + semantic search for best results.',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'Natural language search query' },
limit: { type: 'number', description: 'Max results to return', default: 15 },
min_score: { type: 'number', description: 'Minimum similarity score (0-1)', default: 0.2 },
mode: {
type: 'string',
enum: ['hybrid', 'semantic', 'keyword'],
description:
'Search mode: hybrid (BM25 + semantic, default), semantic (embeddings only), keyword (BM25 only)',
},
...PAGINATION_PROPS,
},
required: ['query'],
},
},
{
name: 'export_graph',
description: 'Export the dependency graph in DOT (Graphviz), Mermaid, or JSON format',
inputSchema: {
type: 'object',
properties: {
format: {
type: 'string',
enum: ['dot', 'mermaid', 'json'],
description: 'Export format',
},
file_level: {
type: 'boolean',
description: 'File-level graph (true) or function-level (false)',
default: true,
},
...PAGINATION_PROPS,
},
required: ['format'],
},
},
{
name: 'list_functions',
description:
'List functions, methods, classes, structs, enums, traits, records, and modules in the codebase, optionally filtered by file or name pattern',
inputSchema: {
type: 'object',
properties: {
file: { type: 'string', description: 'Filter by file path (partial match)' },
pattern: { type: 'string', description: 'Filter by function name (partial match)' },
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
...PAGINATION_PROPS,
},
},
},
{
name: 'structure',
description:
'Show project structure with directory hierarchy, cohesion scores, and per-file metrics. Per-file details are capped at 25 files by default; use full=true to show all.',
inputSchema: {
type: 'object',
properties: {
directory: { type: 'string', description: 'Filter to a specific directory path' },
depth: { type: 'number', description: 'Max directory depth to show' },
sort: {
type: 'string',
enum: ['cohesion', 'fan-in', 'fan-out', 'density', 'files'],
description: 'Sort directories by metric',
},
full: {
type: 'boolean',
description: 'Return all files without limit',
default: false,
},
...PAGINATION_PROPS,
},
},
},
{
name: 'node_roles',
description:
'Show node role classification (entry, core, utility, adapter, dead, leaf) based on connectivity patterns',
inputSchema: {
type: 'object',
properties: {
role: {
type: 'string',
enum: VALID_ROLES,
description: 'Filter to a specific role',
},
file: { type: 'string', description: 'Scope to a specific file (partial match)' },
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
...PAGINATION_PROPS,
},
},
},
{
name: 'hotspots',
description:
'Find structural hotspots: files or directories with extreme fan-in, fan-out, or symbol density',
inputSchema: {
type: 'object',
properties: {
metric: {
type: 'string',
enum: ['fan-in', 'fan-out', 'density', 'coupling'],
description: 'Metric to rank by',
},
level: {
type: 'string',
enum: ['file', 'directory'],
description: 'Rank files or directories',
},
limit: { type: 'number', description: 'Number of results to return', default: 10 },
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
offset: { type: 'number', description: 'Skip this many results (pagination, default: 0)' },
},
},
},
{
name: 'co_changes',
description:
'Find files that historically change together based on git commit history. Requires prior `codegraph co-change --analyze`.',
inputSchema: {
type: 'object',
properties: {
file: {
type: 'string',
description: 'File path (partial match). Omit for top global pairs.',
},
limit: { type: 'number', description: 'Max results', default: 20 },
min_jaccard: {
type: 'number',
description: 'Minimum Jaccard similarity (0-1)',
default: 0.3,
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
offset: { type: 'number', description: 'Skip this many results (pagination, default: 0)' },
},
},
},
{
name: 'execution_flow',
description:
'Trace execution flow forward from an entry point (route, command, event) through callees to leaf functions. Answers "what happens when X is called?"',
inputSchema: {
type: 'object',
properties: {
name: {
type: 'string',
description:
'Entry point or function name (e.g. "POST /login", "build"). Supports prefix-stripped matching.',
},
depth: { type: 'number', description: 'Max forward traversal depth', default: 10 },
file: {
type: 'string',
description: 'Scope search to functions in this file (partial match)',
},
kind: {
type: 'string',
enum: ALL_SYMBOL_KINDS,
description: 'Filter to a specific symbol kind',
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
...PAGINATION_PROPS,
},
required: ['name'],
},
},
{
name: 'list_entry_points',
description:
'List all framework entry points (routes, commands, events) in the codebase, grouped by type',
inputSchema: {
type: 'object',
properties: {
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
...PAGINATION_PROPS,
},
},
},
{
name: 'complexity',
description:
'Show per-function complexity metrics (cognitive, cyclomatic, nesting, Halstead, Maintainability Index). Sorted by most complex first.',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Function name filter (partial match)' },
file: { type: 'string', description: 'Scope to file (partial match)' },
limit: { type: 'number', description: 'Max results', default: 20 },
sort: {
type: 'string',
enum: ['cognitive', 'cyclomatic', 'nesting', 'mi', 'volume', 'effort', 'bugs', 'loc'],
description: 'Sort metric',
default: 'cognitive',
},
above_threshold: {
type: 'boolean',
description: 'Only functions exceeding warn thresholds',
default: false,
},
health: {
type: 'boolean',
description: 'Include Halstead and Maintainability Index metrics',
default: false,
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
kind: {
type: 'string',
description: 'Filter by symbol kind (function, method, class, etc.)',
},
offset: { type: 'number', description: 'Skip this many results (pagination, default: 0)' },
},
},
},
{
name: 'manifesto',
description:
'Evaluate manifesto rules and return pass/fail verdicts for code health. Checks function complexity, file metrics, and cycle rules against configured thresholds.',
inputSchema: {
type: 'object',
properties: {
file: { type: 'string', description: 'Scope to file (partial match)' },
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
kind: {
type: 'string',
description: 'Filter by symbol kind (function, method, class, etc.)',
},
...PAGINATION_PROPS,
},
},
},
{
name: 'communities',
description:
'Detect natural module boundaries using Louvain community detection. Compares discovered communities against directory structure and surfaces architectural drift.',
inputSchema: {
type: 'object',
properties: {
functions: {
type: 'boolean',
description: 'Function-level instead of file-level',
default: false,
},
resolution: {
type: 'number',
description: 'Louvain resolution parameter (higher = more communities)',
default: 1.0,
},
drift: {
type: 'boolean',
description: 'Show only drift analysis (omit community member lists)',
default: false,
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
...PAGINATION_PROPS,
},
},
},
{
name: 'code_owners',
description:
'Show CODEOWNERS mapping for files and functions. Shows ownership coverage, per-owner breakdown, and cross-owner boundary edges.',
inputSchema: {
type: 'object',
properties: {
file: { type: 'string', description: 'Scope to a specific file (partial match)' },
owner: { type: 'string', description: 'Filter to a specific owner (e.g. @team-name)' },
boundary: {
type: 'boolean',
description: 'Show cross-owner boundary edges',
default: false,
},
kind: {
type: 'string',
description: 'Filter by symbol kind (function, method, class, etc.)',
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
},
},
},
{
name: 'audit',
description:
'Composite report combining explain, fn-impact, and health metrics for a file or function. Returns structure, blast radius, complexity, and threshold breaches in one call.',
inputSchema: {
type: 'object',
properties: {
target: { type: 'string', description: 'File path or function name' },
depth: { type: 'number', description: 'Impact analysis depth (default: 3)', default: 3 },
file: { type: 'string', description: 'Scope to file (partial match)' },
kind: {
type: 'string',
description: 'Filter by symbol kind (function, method, class, etc.)',
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
},
required: ['target'],
},
},
{
name: 'batch_query',
description:
'Run a query command against multiple targets in one call. Returns all results in a single JSON payload — ideal for multi-agent dispatch.',
inputSchema: {
type: 'object',
properties: {
command: {
type: 'string',
enum: [
'fn-impact',
'context',
'explain',
'where',
'query',
'fn',
'impact',
'deps',
'flow',
'complexity',
],
description: 'The query command to run for each target',
},
targets: {
type: 'array',
items: { type: 'string' },
description: 'List of target names (symbol names or file paths depending on command)',
},
depth: {
type: 'number',
description: 'Traversal depth (for fn-impact, context, fn, flow)',
},
file: {
type: 'string',
description: 'Scope to file (partial match)',
},
kind: {
type: 'string',
enum: ALL_SYMBOL_KINDS,
description: 'Filter symbol kind',
},
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
},
required: ['command', 'targets'],
},
},
{
name: 'branch_compare',
description:
'Compare code structure between two git refs (branches, tags, commits). Shows added/removed/changed symbols and transitive caller impact using temporary git worktrees.',
inputSchema: {
type: 'object',
properties: {
base: { type: 'string', description: 'Base git ref (branch, tag, or commit SHA)' },
target: { type: 'string', description: 'Target git ref to compare against base' },
depth: { type: 'number', description: 'Max transitive caller depth', default: 3 },
no_tests: { type: 'boolean', description: 'Exclude test files', default: false },
format: {
type: 'string',
enum: ['json', 'mermaid'],
description: 'Output format (default: json)',
},
},
required: ['base', 'target'],
},
},
];
const LIST_REPOS_TOOL = {
name: 'list_repos',
description: 'List all repositories registered in the codegraph registry',
inputSchema: {
type: 'object',
properties: {},
},
};
/**
* Build the tool list based on multi-repo mode.
* @param {boolean} multiRepo - If true, inject `repo` prop into each tool and append `list_repos`
* @returns {object[]}
*/
function buildToolList(multiRepo) {
if (!multiRepo) return BASE_TOOLS;
return [
...BASE_TOOLS.map((tool) => ({
...tool,
inputSchema: {
...tool.inputSchema,
properties: { ...tool.inputSchema.properties, ...REPO_PROP },
},
})),
LIST_REPOS_TOOL,
];
}
// Backward-compatible export: full multi-repo tool list
const TOOLS = buildToolList(true);
export { TOOLS, buildToolList };
/**
* Start the MCP server.
* This function requires @modelcontextprotocol/sdk to be installed.
*
* @param {string} [customDbPath] - Path to a specific graph.db
* @param {object} [options]
* @param {boolean} [options.multiRepo] - Enable multi-repo access (default: false)
* @param {string[]} [options.allowedRepos] - Restrict access to these repo names only
*/
export async function startMCPServer(customDbPath, options = {}) {
const { allowedRepos } = options;
const multiRepo = options.multiRepo || !!allowedRepos;
let Server, StdioServerTransport, ListToolsRequestSchema, CallToolRequestSchema;
try {
const sdk = await import('@modelcontextprotocol/sdk/server/index.js');
Server = sdk.Server;
const transport = await import('@modelcontextprotocol/sdk/server/stdio.js');
StdioServerTransport = transport.StdioServerTransport;
const types = await import('@modelcontextprotocol/sdk/types.js');
ListToolsRequestSchema = types.ListToolsRequestSchema;
CallToolRequestSchema = types.CallToolRequestSchema;
} catch {
console.error(
'MCP server requires @modelcontextprotocol/sdk.\n' +
'Install it with: npm install @modelcontextprotocol/sdk',
);
process.exit(1);
}
// Lazy import query functions to avoid circular deps at module load
const {
queryNameData,
impactAnalysisData,
moduleMapData,
fileDepsData,
fnDepsData,
fnImpactData,
pathData,
contextData,
explainData,
whereData,
diffImpactData,
listFunctionsData,
rolesData,
} = await import('./queries.js');
const require = createRequire(import.meta.url);
const Database = require('better-sqlite3');
const server = new Server(
{ name: 'codegraph', version: '1.0.0' },
{ capabilities: { tools: {} } },
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: buildToolList(multiRepo),
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
if (!multiRepo && args.repo) {
throw new Error(
'Multi-repo access is disabled. Restart with `codegraph mcp --multi-repo` to access other repositories.',
);
}
if (!multiRepo && name === 'list_repos') {
throw new Error(
'Multi-repo access is disabled. Restart with `codegraph mcp --multi-repo` to list repositories.',
);
}
let dbPath = customDbPath || undefined;
if (args.repo) {
if (allowedRepos && !allowedRepos.includes(args.repo)) {
throw new Error(`Repository "${args.repo}" is not in the allowed repos list.`);
}
const { resolveRepoDbPath } = await import('./registry.js');
const resolved = resolveRepoDbPath(args.repo);
if (!resolved)
throw new Error(
`Repository "${args.repo}" not found in registry or its database is missing.`,
);
dbPath = resolved;
}
let result;
switch (name) {
case 'query_function':
result = queryNameData(args.name, dbPath, {
noTests: args.no_tests,
limit: Math.min(args.limit ?? MCP_DEFAULTS.query_function, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
});
break;
case 'file_deps':
result = fileDepsData(args.file, dbPath, {
noTests: args.no_tests,
limit: Math.min(args.limit ?? MCP_DEFAULTS.file_deps, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
});
break;
case 'impact_analysis':
result = impactAnalysisData(args.file, dbPath, {
noTests: args.no_tests,
limit: Math.min(args.limit ?? MCP_DEFAULTS.impact_analysis, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
});
break;
case 'find_cycles': {
const db = new Database(findDbPath(dbPath), { readonly: true });
const cycles = findCycles(db);
db.close();
result = { cycles, count: cycles.length };
break;
}
case 'module_map':
result = moduleMapData(dbPath, args.limit || 20, { noTests: args.no_tests });
break;
case 'fn_deps':
result = fnDepsData(args.name, dbPath, {
depth: args.depth,
file: args.file,
kind: args.kind,
noTests: args.no_tests,
limit: Math.min(args.limit ?? MCP_DEFAULTS.fn_deps, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
});
break;
case 'fn_impact':
result = fnImpactData(args.name, dbPath, {
depth: args.depth,
file: args.file,
kind: args.kind,
noTests: args.no_tests,
limit: Math.min(args.limit ?? MCP_DEFAULTS.fn_impact, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
});
break;
case 'symbol_path':
result = pathData(args.from, args.to, dbPath, {
maxDepth: args.max_depth,
edgeKinds: args.edge_kinds,
reverse: args.reverse,
fromFile: args.from_file,
toFile: args.to_file,
kind: args.kind,
noTests: args.no_tests,
});
break;
case 'context':
result = contextData(args.name, dbPath, {
depth: args.depth,
file: args.file,
kind: args.kind,
noSource: args.no_source,
noTests: args.no_tests,
includeTests: args.include_tests,
limit: Math.min(args.limit ?? MCP_DEFAULTS.context, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
});
break;
case 'explain':
result = explainData(args.target, dbPath, {
noTests: args.no_tests,
limit: Math.min(args.limit ?? MCP_DEFAULTS.explain, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
});
break;
case 'where':
result = whereData(args.target, dbPath, {
file: args.file_mode,
noTests: args.no_tests,
limit: Math.min(args.limit ?? MCP_DEFAULTS.where, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
});
break;
case 'diff_impact':
if (args.format === 'mermaid') {
result = diffImpactMermaid(dbPath, {
staged: args.staged,
ref: args.ref,
depth: args.depth,
noTests: args.no_tests,
});
} else {
result = diffImpactData(dbPath, {
staged: args.staged,
ref: args.ref,
depth: args.depth,
noTests: args.no_tests,
limit: Math.min(args.limit ?? MCP_DEFAULTS.diff_impact, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
});
}
break;
case 'semantic_search': {
const mode = args.mode || 'hybrid';
const searchOpts = {
limit: Math.min(args.limit ?? MCP_DEFAULTS.semantic_search, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
minScore: args.min_score,
};
if (mode === 'keyword') {
const { ftsSearchData } = await import('./embedder.js');
result = ftsSearchData(args.query, dbPath, searchOpts);
if (result === null) {
return {
content: [
{
type: 'text',
text: 'No FTS5 index found. Run `codegraph embed` to build the keyword index.',
},
],
isError: true,
};
}
} else if (mode === 'semantic') {
const { searchData } = await import('./embedder.js');
result = await searchData(args.query, dbPath, searchOpts);
if (result === null) {
return {
content: [
{
type: 'text',
text: 'Semantic search unavailable. Run `codegraph embed` first.',
},
],
isError: true,
};
}
} else {
// hybrid (default) — falls back to semantic if no FTS5
const { hybridSearchData, searchData } = await import('./embedder.js');
result = await hybridSearchData(args.query, dbPath, searchOpts);
if (result === null) {
result = await searchData(args.query, dbPath, searchOpts);
if (result === null) {
return {
content: [
{
type: 'text',
text: 'Semantic search unavailable. Run `codegraph embed` first.',
},
],
isError: true,
};
}
}
}
break;
}
case 'export_graph': {
const { exportDOT, exportMermaid, exportJSON } = await import('./export.js');
const db = new Database(findDbPath(dbPath), { readonly: true });
const fileLevel = args.file_level !== false;
const exportLimit = args.limit
? Math.min(args.limit, MCP_MAX_LIMIT)
: MCP_DEFAULTS.export_graph;
switch (args.format) {
case 'dot':
result = exportDOT(db, { fileLevel, limit: exportLimit });
break;
case 'mermaid':
result = exportMermaid(db, { fileLevel, limit: exportLimit });
break;
case 'json':
result = exportJSON(db, {
limit: exportLimit,
offset: args.offset ?? 0,
});
break;
default:
db.close();
return {
content: [
{
type: 'text',
text: `Unknown format: ${args.format}. Use dot, mermaid, or json.`,
},
],
isError: true,
};
}
db.close();
break;
}
case 'list_functions':
result = listFunctionsData(dbPath, {
file: args.file,
pattern: args.pattern,
noTests: args.no_tests,
limit: Math.min(args.limit ?? MCP_DEFAULTS.list_functions, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
});
break;
case 'node_roles':
result = rolesData(dbPath, {
role: args.role,
file: args.file,
noTests: args.no_tests,
limit: Math.min(args.limit ?? MCP_DEFAULTS.node_roles, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
});
break;
case 'structure': {
const { structureData } = await import('./structure.js');
result = structureData(dbPath, {
directory: args.directory,
depth: args.depth,
sort: args.sort,
full: args.full,
limit: Math.min(args.limit ?? MCP_DEFAULTS.structure, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
});
break;
}
case 'hotspots': {
const { hotspotsData } = await import('./structure.js');
result = hotspotsData(dbPath, {
metric: args.metric,
level: args.level,
limit: Math.min(args.limit ?? MCP_DEFAULTS.hotspots, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
noTests: args.no_tests,
});
break;
}
case 'co_changes': {
const { coChangeData, coChangeTopData } = await import('./cochange.js');
result = args.file
? coChangeData(args.file, dbPath, {
limit: Math.min(args.limit ?? MCP_DEFAULTS.co_changes, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
minJaccard: args.min_jaccard,
noTests: args.no_tests,
})
: coChangeTopData(dbPath, {
limit: Math.min(args.limit ?? MCP_DEFAULTS.co_changes, MCP_MAX_LIMIT),
offset: args.offset ?? 0,
minJaccard: args.min_jaccard,
noTests: args.no_tests,