-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathserver.go
More file actions
3017 lines (2732 loc) · 110 KB
/
Copy pathserver.go
File metadata and controls
3017 lines (2732 loc) · 110 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
package server
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/enola-labs/enola/internal/config"
"github.com/enola-labs/enola/internal/engine"
"github.com/enola-labs/enola/internal/facts"
"github.com/enola-labs/enola/pkg/mcputil"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// Version is set at build time via -ldflags.
var Version = "dev"
// Server wraps the MCP server and connects it to the snapshot engine.
type Server struct {
mcp *mcp.Server
eng *engine.Engine
cfg *config.Config
startTime time.Time
toolCallback func(string)
// snapshotsGenerated records whether generate_snapshot has run at least once
// in this session. It distinguishes a user-driven multi-repo session from a
// store that was merely pre-populated by AutoLoadSnapshot at startup, so the
// auto-append heuristic never fires on top of auto-loaded-only state.
snapshotsGenerated bool
}
// New creates a new MCP server wired to the given engine.
func New(eng *engine.Engine, cfg *config.Config) (*Server, error) {
s := &Server{
eng: eng,
cfg: cfg,
}
mcpServer := mcp.NewServer(&mcp.Implementation{
Name: "enola",
Version: Version,
}, &mcp.ServerOptions{
Instructions: "Use this server to explore a repository's architecture as queryable facts. Run generate_snapshot first to index a codebase, then use explore, query_facts, show_symbol, traverse, find_path, and impact_analysis to understand code structure, dependencies, and change impact. Explainers run automatically during generate_snapshot and compute findings (dependency cycles, layer violations, unused/dead routes, god-classes, hotspots, and more) — fetch them with query_insights rather than re-deriving them by hand. To find backend HTTP routes that no loaded client calls, take a multi-repo (append-mode) snapshot of the backend plus its clients, then call query_insights(explainer='unused-routes') or query_facts(kind=route, prop=unmatched_by_clients, prop_value=true). Supports Go, TypeScript, Kotlin, Ruby, Python, Swift, Java, C++, and OpenAPI.",
})
s.mcp = mcpServer
s.registerTools()
return s, nil
}
// Run starts the MCP server on the stdio transport.
func (s *Server) Run(ctx context.Context) error {
s.startTime = time.Now()
log.Println("[server] starting MCP server on stdio transport")
return s.mcp.Run(ctx, &mcp.StdioTransport{})
}
// SetToolCallback sets a callback invoked each time a tool is called.
// The callback receives the tool name. It is safe to call before Run().
func (s *Server) SetToolCallback(cb func(string)) {
s.toolCallback = cb
}
// GetStartTime returns the time the server started (zero value if Run() hasn't been called).
func (s *Server) GetStartTime() time.Time {
return s.startTime
}
// MCPServer returns the underlying MCP server so that enterprise (or third-party)
// code can register additional, license-gated tools alongside the OSS tools.
func (s *Server) MCPServer() *mcp.Server {
return s.mcp
}
// generateSnapshotArgs are the arguments for the generate_snapshot tool.
type generateSnapshotArgs struct {
RepoPath string `json:"repo_path" jsonschema:"Path to the repository to analyze. Defaults to the configured repo path."`
Append bool `json:"append,omitempty" jsonschema:"If true, keep existing facts and add new ones with repo-prefixed file paths (for multi-repo analysis). Default false."`
}
// queryFactsArgs are the arguments for the query_facts tool.
type queryFactsArgs struct {
Kind string `json:"kind,omitempty" jsonschema:"Filter by fact kind: module, symbol, route, storage, dependency, or service (service = a whole repo, used as a node in the cross-repo graph)"`
File string `json:"file,omitempty" jsonschema:"Filter by file path"`
Name string `json:"name,omitempty" jsonschema:"Filter by name using substring match"`
Relation string `json:"relation,omitempty" jsonschema:"Filter by relation kind: declares, imports, calls, implements, or depends_on"`
Prop string `json:"prop,omitempty" jsonschema:"Filter by property name (e.g. source, symbol_kind, exported, framework, storage_kind, role, method, unmatched_by_clients). output_mode=summary surfaces notable boolean flags (like unmatched_by_clients) present in the result set."`
PropValue string `json:"prop_value,omitempty" jsonschema:"Filter by property value (requires prop to be set)"`
// Batch filters — OR within dimension, AND across dimensions
Names []string `json:"names,omitempty" jsonschema:"Filter by multiple exact names (OR). Use instead of name for batch lookups."`
Files []string `json:"files,omitempty" jsonschema:"Filter by multiple file paths (OR). Use instead of file for batch lookups."`
Kinds []string `json:"kinds,omitempty" jsonschema:"Filter by multiple kinds (OR). Use instead of kind for batch lookups."`
FilePrefix string `json:"file_prefix,omitempty" jsonschema:"Filter by file path prefix (e.g. internal/server to match all files in that directory)"`
Repo string `json:"repo,omitempty" jsonschema:"Filter by repository label (set in multi-repo/append mode, e.g. 'go-service')"`
// Pagination
Offset int `json:"offset,omitempty" jsonschema:"Number of results to skip for pagination. Default 0."`
Limit int `json:"limit,omitempty" jsonschema:"Maximum number of results to return (1-500). Default 100."`
// Relation expansion
IncludeRelated bool `json:"include_related,omitempty" jsonschema:"If true, inline the full fact data for each relation target instead of just the target name"`
// Output format
OutputMode string `json:"output_mode,omitempty" jsonschema:"Output format: 'full' (DEFAULT, JSON facts), 'compact' (markdown table), 'names' (just names+files), or 'summary' (counts only: total + breakdown by kind and top files — cheapest, use to size a result set before fetching it)."`
MaxTokens int `json:"max_tokens,omitempty" jsonschema:"Optional hard cap on output size (approx tokens). Output is truncated with a notice. Default: no cap."`
}
// enrichedFact wraps a Fact with resolved relation targets.
type enrichedFact struct {
facts.Fact
RelatedFacts []facts.Fact `json:"related_facts,omitempty"`
}
// queryResponse is the structured response for query_facts when advanced features are used.
type queryResponse struct {
Facts any `json:"facts"`
Total int `json:"total"`
Offset int `json:"offset"`
Limit int `json:"limit"`
HasMore bool `json:"has_more"`
}
// renderCompact formats facts as a markdown table for minimal token usage.
func renderCompact(results []facts.Fact, total int) string {
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Found %d results (showing %d):\n\n", total, len(results)))
sb.WriteString("| Kind | Name | File | Line |\n")
sb.WriteString("|------|------|------|------|\n")
for _, f := range results {
sb.WriteString(fmt.Sprintf("| %s | %s | %s | %d |\n", f.Kind, f.Name, f.File, f.Line))
}
return sb.String()
}
// renderNamesOnly returns just names and files, one per line.
func renderNamesOnly(results []facts.Fact, total int) string {
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Found %d results (showing %d):\n\n", total, len(results)))
for _, f := range results {
sb.WriteString(fmt.Sprintf("%s %s:%d\n", f.Name, f.File, f.Line))
}
return sb.String()
}
// renderQuerySummary returns counts only — total plus a breakdown by kind and the
// top files — so the caller can size a result set before fetching the facts
// themselves. The breakdown is computed over the returned sample (results); when
// total exceeds the sample it is annotated as approximate.
// notableBoolProps are high-signal boolean fact properties surfaced in the
// query_facts summary so a caller sizing a result set discovers actionable
// flags (e.g. dead routes) without already knowing the prop name exists.
var notableBoolProps = []string{"unmatched_by_clients"}
func renderQuerySummary(results []facts.Fact, total int) string {
var sb strings.Builder
fmt.Fprintf(&sb, "Found **%d** matching facts.\n\n", total)
byKind := map[string]int{}
byFile := map[string]int{}
flagCounts := map[string]int{}
for _, f := range results {
byKind[f.Kind]++
if f.File != "" {
byFile[f.File]++
}
for _, p := range notableBoolProps {
if f.Props != nil && f.Props[p] == true {
flagCounts[p]++
}
}
}
if len(byKind) > 0 {
sb.WriteString("## By kind\n\n")
for _, k := range topCounts(byKind, len(byKind)) {
fmt.Fprintf(&sb, "- %s: %d\n", k, byKind[k])
}
sb.WriteString("\n")
}
if len(flagCounts) > 0 {
sb.WriteString("## Flags\n\n")
for _, p := range topCounts(flagCounts, len(flagCounts)) {
fmt.Fprintf(&sb, "- %s=true: %d — list with query_facts(prop=%q, prop_value=true); see the summarized finding via query_insights\n", p, flagCounts[p], p)
}
sb.WriteString("\n")
}
if len(byFile) > 0 {
sb.WriteString("## Top files\n\n")
for _, f := range topCounts(byFile, 10) {
fmt.Fprintf(&sb, "- %s: %d\n", f, byFile[f])
}
sb.WriteString("\n")
}
if total > len(results) {
fmt.Fprintf(&sb, "_Breakdown computed over a sample of %d of %d matches; counts are approximate. Re-run with filters to narrow, or output_mode=compact/names to list facts._\n", len(results), total)
}
return sb.String()
}
// filterInsights returns the insights matching all of the supplied filters.
// explainer is matched case-insensitively against Insight.Source; repo matches
// the repo-prefix path segment of each insight's evidence files (insights have
// no structured repo field) — see insightBelongsToRepo; minConfidence keeps
// insights at or above the bar. multiRepo reports whether the snapshot spans
// more than one repo, which selects strict vs. legacy repo matching.
func filterInsights(insights []facts.Insight, explainer, repo string, minConfidence float64, multiRepo bool) []facts.Insight {
repoLC := strings.ToLower(strings.TrimSpace(repo))
var out []facts.Insight
for _, in := range insights {
if explainer != "" && !strings.EqualFold(in.Source, strings.TrimSpace(explainer)) {
continue
}
if in.Confidence < minConfidence {
continue
}
if repoLC != "" && !insightBelongsToRepo(in, repoLC, multiRepo) {
continue
}
out = append(out, in)
}
return out
}
// pathInRepo reports whether a repo-prefixed evidence path (e.g.
// "golf/internal/x.go") belongs to repo (given lowercased). Matching is on the
// first path segment, so "golf" does not match "golf-ui/..." or
// "my-golf-journal-*".
func pathInRepo(path, repoLC string) bool {
p := strings.ToLower(strings.TrimSpace(path))
return p == repoLC || strings.HasPrefix(p, repoLC+"/")
}
// insightBelongsToRepo reports whether an insight is about repo (given
// lowercased). In multi-repo snapshots evidence paths are repo-prefixed, so we
// match the path-segment of each evidence File/Fact exactly. The title
// substring match is dropped there because titles aren't reliably repo-qualified
// and over-match shared tokens (e.g. "golf" in "golf-ui"). Single-repo snapshots
// don't prefix evidence paths, so there we keep the legacy substring heuristic —
// it can't leak across repos because there are no siblings.
func insightBelongsToRepo(in facts.Insight, repoLC string, multiRepo bool) bool {
for _, ev := range in.Evidence {
if pathInRepo(ev.File, repoLC) || pathInRepo(ev.Fact, repoLC) {
return true
}
}
if multiRepo {
return false
}
// Single-repo legacy fallback (unchanged behavior).
if strings.Contains(strings.ToLower(in.Title), repoLC) {
return true
}
for _, ev := range in.Evidence {
if strings.Contains(strings.ToLower(ev.File), repoLC) ||
strings.Contains(strings.ToLower(ev.Fact), repoLC) {
return true
}
}
return false
}
// renderInsightsSummary lists one row per insight (explainer, confidence, title)
// with a by-explainer tally — the cheapest way to size and triage findings.
func renderInsightsSummary(insights []facts.Insight) string {
var sb strings.Builder
fmt.Fprintf(&sb, "Found **%d** insight(s).\n\n", len(insights))
bySource := map[string]int{}
for _, in := range insights {
bySource[insightSource(in)]++
}
if len(bySource) > 0 {
sb.WriteString("## By explainer\n\n")
for _, s := range topCounts(bySource, len(bySource)) {
fmt.Fprintf(&sb, "- %s: %d\n", s, bySource[s])
}
sb.WriteString("\n")
}
sb.WriteString("## Insights\n\n")
sb.WriteString("| Explainer | Confidence | Title |\n|---|---|---|\n")
for _, in := range insights {
fmt.Fprintf(&sb, "| %s | %.2f | %s |\n", insightSource(in), in.Confidence, oneLine(in.Title))
}
sb.WriteString("\n_Use output_mode='compact' for descriptions, evidence, and suggested actions, or 'full' for complete JSON._\n")
return sb.String()
}
// renderInsightsCompact renders each insight with its description, an evidence
// sample (capped), and suggested actions.
func renderInsightsCompact(insights []facts.Insight) string {
const evidenceSample = 10
var sb strings.Builder
fmt.Fprintf(&sb, "Found **%d** insight(s).\n\n", len(insights))
for i, in := range insights {
fmt.Fprintf(&sb, "### %d. %s\n", i+1, in.Title)
fmt.Fprintf(&sb, "- explainer: %s · confidence: %.2f\n", insightSource(in), in.Confidence)
if in.Description != "" {
fmt.Fprintf(&sb, "- %s\n", in.Description)
}
if len(in.Evidence) > 0 {
fmt.Fprintf(&sb, "- evidence (%d):\n", len(in.Evidence))
shown := len(in.Evidence)
if shown > evidenceSample {
shown = evidenceSample
}
for _, ev := range in.Evidence[:shown] {
fmt.Fprintf(&sb, " - %s\n", formatEvidence(ev))
}
if len(in.Evidence) > shown {
fmt.Fprintf(&sb, " - … and %d more (output_mode='full' for all)\n", len(in.Evidence)-shown)
}
}
if len(in.Actions) > 0 {
sb.WriteString("- suggested actions:\n")
for _, a := range in.Actions {
fmt.Fprintf(&sb, " - %s\n", a)
}
}
sb.WriteString("\n")
}
return sb.String()
}
// insightSource returns the producing explainer name, or a placeholder when unset.
func insightSource(in facts.Insight) string {
if in.Source == "" {
return "—"
}
return in.Source
}
// formatEvidence joins an evidence record's non-empty fields into one line.
func formatEvidence(ev facts.Evidence) string {
var parts []string
for _, p := range []string{ev.Fact, ev.Symbol, ev.File} {
if p != "" {
parts = append(parts, p)
}
}
s := strings.Join(parts, " ")
if ev.Detail != "" {
if s != "" {
s += " — " + ev.Detail
} else {
s = ev.Detail
}
}
return s
}
// oneLine collapses newlines and escapes pipes so a string is safe inside a
// single markdown table cell.
func oneLine(s string) string {
s = strings.ReplaceAll(s, "\n", " ")
return strings.ReplaceAll(s, "|", "\\|")
}
// registerTools adds MCP tools for snapshot generation and fact querying.
func (s *Server) registerTools() {
// Tool: generate_snapshot
mcp.AddTool(s.mcp, &mcp.Tool{
Name: "generate_snapshot",
Description: "Index a repository and extract its architecture as queryable facts. " +
"Supports Go, TypeScript, Kotlin, Ruby, Python, Swift, Java, C++, and OpenAPI. " +
"Produces facts of kind: module, symbol, route, storage, dependency, service. " +
"Run this first before any other tool. Re-run after code changes. " +
"In multi-repo mode, call with append=true for each additional repo after the first; " +
"enola auto-enables append when it detects you have switched to a different repo.",
}, func(ctx context.Context, req *mcp.CallToolRequest, args generateSnapshotArgs) (*mcp.CallToolResult, any, error) {
if s.toolCallback != nil {
s.toolCallback("generate_snapshot")
}
repoPath := args.RepoPath
if repoPath == "" {
repoPath = s.cfg.Repo
}
absRepo, err := filepath.Abs(repoPath)
if err != nil {
return errorResult(fmt.Sprintf("invalid repo path: %v", err)), nil, nil
}
// Auto-enable append mode when switching to a different repo while facts
// from another repo are already loaded — but only once this session has
// explicitly generated a snapshot. A store pre-populated solely by
// AutoLoadSnapshot must not trigger append: an explicit/default
// append=false resets and discards the auto-loaded state.
appendMode := args.Append
autoAppended := false
if !appendMode && s.snapshotsGenerated && s.eng.Store().Count() > 0 && s.eng.Snapshot() != nil {
prevRepo := s.eng.Snapshot().Meta.RepoPath
if prevRepo != "" && prevRepo != absRepo {
appendMode = true
autoAppended = true
log.Printf("[server] auto-enabled append mode: switching from %s to %s", prevRepo, absRepo)
}
}
// A fresh (non-append) snapshot that discards an auto-loaded store is
// silent otherwise; log it so the reset is visible.
if !appendMode && !s.snapshotsGenerated && s.eng.Store().Count() > 0 && s.eng.Snapshot() != nil {
if prevRepo := s.eng.Snapshot().Meta.RepoPath; prevRepo != "" && prevRepo != absRepo {
log.Printf("[server] discarding auto-loaded snapshot from %s; generating fresh single-repo snapshot for %s", prevRepo, absRepo)
}
}
snapshot, err := s.eng.GenerateSnapshot(ctx, absRepo, appendMode)
if err != nil {
return errorResult(fmt.Sprintf("snapshot generation failed: %v", err)), nil, nil
}
s.snapshotsGenerated = true
// Write artifacts to disk
if err := s.eng.WriteArtifacts(absRepo); err != nil {
log.Printf("[server] warning: failed to write artifacts: %v", err)
}
// Return summary
summary := fmt.Sprintf(
"Snapshot generated successfully.\n\n"+
"- Repository: %s\n"+
"- Facts: %d\n"+
"- Insights: %d\n"+
"- Artifacts: %d\n"+
"- Duration: %s\n"+
"- Extractors: %v\n"+
"- Explainers: %v\n\n"+
"Fetch the computed findings with query_insights (e.g. query_insights(explainer='unused-routes') for HTTP routes no loaded client calls); use query_facts or explore to inspect the raw facts.",
snapshot.Meta.RepoPath,
snapshot.Meta.FactCount,
snapshot.Meta.InsightCount,
len(snapshot.Artifacts),
snapshot.Meta.Duration,
snapshot.Meta.Extractors,
snapshot.Meta.Explainers,
)
if appendMode {
repoLabel := filepath.Base(absRepo)
autoNote := ""
if autoAppended {
autoNote = " (auto-enabled: different repo detected)"
}
summary += fmt.Sprintf(
"\n\n**Multi-repo mode active%s.** Repo label: %q\n"+
"- Filter by repo: query_facts(repo=%q)\n"+
"- File paths are prefixed: e.g. %s/src/...\n"+
"- Generate additional repos with append=true (sequentially, not in parallel).",
autoNote, repoLabel, repoLabel, repoLabel,
)
// Report the cross-repo "graph of graphs" links derived from this set.
crossEdges, _ := s.eng.Store().QueryAdvanced(facts.QueryOpts{
Kind: facts.KindDependency, Prop: "type", PropValue: "cross_repo", Limit: 500,
})
services := s.eng.Store().ByKind(facts.KindService)
summary += fmt.Sprintf(
"\n- **Cross-repo graph:** %d service node(s), %d cross-repo dependency edge(s). "+
"Traverse between repos with traverse(start=%q) / find_path, list edges with "+
"query_facts(kind=\"service\") or query_facts(prop=\"type\", prop_value=\"cross_repo\").",
len(services), len(crossEdges), repoLabel,
)
}
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: summary},
},
}, nil, nil
})
// Tool: query_facts
mcp.AddTool(s.mcp, &mcp.Tool{
Name: "query_facts",
Description: "Precision filter over extracted facts. Use after explore when you need specific subsets — " +
"e.g. all symbols in a file, all external dependencies, all routes. " +
"Fact kinds: module, symbol, route, storage, dependency, service. " +
"name= is a substring match; names= is exact (batch). files= and kinds= are OR filters; combined with other fields they are AND. " +
"output_mode: 'full' (default JSON) → 'compact' (markdown table) → 'names' (names+files) → 'summary' (counts only). " +
"Use output_mode='summary' first to size an unfamiliar result set, then 'compact'/'names' to save tokens on large sets, and pass max_tokens to hard-cap output. " +
"For dependencies, set prop='source' prop_value='internal'|'external'|'stdlib' to filter noise. " +
"Supports pagination via offset/limit (default 100, max 500).",
}, func(ctx context.Context, req *mcp.CallToolRequest, args queryFactsArgs) (*mcp.CallToolResult, any, error) {
if s.toolCallback != nil {
s.toolCallback("query_facts")
}
store := s.eng.Store()
if store.Count() == 0 {
return errorResult("No facts available. Run generate_snapshot first."), nil, nil
}
// Normalize absolute filesystem paths to store-relative paths.
normFile := s.normalizeToRelative(args.File)
normPrefix := s.normalizeToRelative(args.FilePrefix)
var normFiles []string
for _, f := range args.Files {
normFiles = append(normFiles, s.normalizeToRelative(f))
}
// In multi-repo mode, expand the file prefix to include repo labels
// if the user provided a bare relative path (e.g. "src/" instead of "golf-ui/src/").
prefixes := s.expandFilePrefix(normPrefix)
mode := resolveOutputMode(args.OutputMode, modeFull)
// Summary mode aggregates over as many matches as the store allows (cap 500)
// so the by-kind/by-file breakdown reflects the widest available sample.
limit := args.Limit
if mode == modeSummary {
limit = 500
}
// Query with the first (or only) prefix.
opts := facts.QueryOpts{
Kind: args.Kind,
Kinds: args.Kinds,
File: normFile,
Files: normFiles,
FilePrefix: prefixes[0],
Name: args.Name,
Names: args.Names,
Repo: args.Repo,
RelKind: args.Relation,
Prop: args.Prop,
PropValue: args.PropValue,
Offset: args.Offset,
Limit: limit,
}
results, total := store.QueryAdvanced(opts)
// If multiple repo labels matched, merge results from additional prefixes.
for _, p := range prefixes[1:] {
opts.FilePrefix = p
extra, extraTotal := store.QueryAdvanced(opts)
results = append(results, extra...)
total += extraTotal
}
// Non-JSON output modes: return text instead of JSON.
switch mode {
case modeSummary:
return textResult(capTokens(renderQuerySummary(results, total), args.MaxTokens, false)), nil, nil
case modeCompact:
return textResult(capTokens(renderCompact(results, total), args.MaxTokens, false)), nil, nil
case modeNames:
return textResult(capTokens(renderNamesOnly(results, total), args.MaxTokens, false)), nil, nil
}
// Determine if advanced features are in use (triggers structured response)
useAdvanced := args.IncludeRelated || args.Offset > 0 || args.Limit > 0 ||
len(args.Names) > 0 || len(args.Files) > 0 || len(args.Kinds) > 0 ||
args.FilePrefix != "" || args.Repo != ""
// Enrich with related facts if requested
var output any
if args.IncludeRelated {
enriched := make([]enrichedFact, len(results))
seen := make(map[string]struct{}) // deduplicate related facts
for i, f := range results {
enriched[i] = enrichedFact{Fact: f}
for _, rel := range f.Relations {
if _, dup := seen[rel.Target]; dup {
continue
}
seen[rel.Target] = struct{}{}
related := store.LookupByExactName(rel.Target)
enriched[i].RelatedFacts = append(enriched[i].RelatedFacts, related...)
}
}
output = enriched
} else {
output = results
}
if useAdvanced {
limit := args.Limit
if limit <= 0 {
limit = 100
}
if limit > 500 {
limit = 500
}
resp := queryResponse{
Facts: output,
Total: total,
Offset: args.Offset,
Limit: limit,
HasMore: total > args.Offset+len(results),
}
return jsonResultCapped(resp, args.MaxTokens)
}
// Legacy format: raw JSON array (backwards compatible)
data, err := json.MarshalIndent(output, "", " ")
if err != nil {
return errorResult(fmt.Sprintf("failed to marshal results: %v", err)), nil, nil
}
text := string(data)
if total > len(results) {
text += fmt.Sprintf("\n\n... (showing %d of %d results, refine your query or use offset/limit for pagination)", len(results), total)
}
return textResult(capTokens(text, args.MaxTokens, true)), nil, nil
})
// Tool: show_symbol
mcp.AddTool(s.mcp, &mcp.Tool{
Name: "show_symbol",
Description: "Return the source code implementation of a named symbol. " +
"Prefers exact name match; falls back to substring match and returns up to 5 results. " +
"Default context: 60 lines (asymmetric: ~15 before declaration, ~45 after). " +
"Use context_lines to widen or narrow the window. " +
"Works in both single-repo and multi-repo (append) mode.",
}, func(ctx context.Context, req *mcp.CallToolRequest, args showSymbolArgs) (*mcp.CallToolResult, any, error) {
if s.toolCallback != nil {
s.toolCallback("show_symbol")
}
snapshot := s.eng.Snapshot()
if snapshot == nil {
return errorResult("No snapshot available. Run generate_snapshot first."), nil, nil
}
store := s.eng.Store()
if store.Count() == 0 {
return errorResult("No facts available. Run generate_snapshot first."), nil, nil
}
if args.Name == "" {
return errorResult("name is required"), nil, nil
}
// Prefer exact match to avoid substring noise (e.g. "Transaction" matching "AutoTransactionsTogglePatch").
results := store.LookupByExactName(args.Name)
// Filter to symbols only
symbolResults := results[:0]
for _, r := range results {
if r.Kind == facts.KindSymbol {
symbolResults = append(symbolResults, r)
}
}
results = symbolResults
if len(results) == 0 {
results = store.Query("symbol", "", args.Name, "")
}
if len(results) == 0 {
return errorResult(fmt.Sprintf("No symbols matching %q", args.Name)), nil, nil
}
contextLines := args.ContextLines
if contextLines <= 0 {
contextLines = 60
}
// Limit to 5 results
if len(results) > 5 {
results = results[:5]
}
var sb strings.Builder
for i, fact := range results {
if i > 0 {
sb.WriteString("\n---\n\n")
}
// Header
sb.WriteString(fmt.Sprintf("### %s\n", fact.Name))
sb.WriteString(fmt.Sprintf("File: %s Line: %d\n", fact.File, fact.Line))
// Show props summary
if sig, ok := fact.Props["signature"].(string); ok {
sb.WriteString(fmt.Sprintf("Signature:\n```\n%s\n```\n", sig))
}
if comp, ok := fact.Props["ios_component"].(string); ok {
sb.WriteString(fmt.Sprintf("iOS Component: %s\n", comp))
}
sb.WriteString("\n")
// Read source file (handles both single-repo and multi-repo paths)
absFile := s.eng.ResolveFactFile(&fact)
source, err := readSourceWindow(absFile, fact.Line, contextLines)
if err != nil {
sb.WriteString(fmt.Sprintf("_Could not read source: %v_\n", err))
continue
}
lang := "go"
if l, ok := fact.Props["language"].(string); ok && l != "" {
lang = l
}
sb.WriteString(fmt.Sprintf("```%s\n%s\n```\n", lang, source))
}
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: sb.String()},
},
}, nil, nil
})
// Tool: explore
mcp.AddTool(s.mcp, &mcp.Tool{
Name: "explore",
Description: "Primary exploration tool — use this first after generate_snapshot. " +
"Given a module name, file path, symbol name, or directory prefix, returns a structured markdown summary: " +
"symbols (with kinds and line numbers), direct dependencies, and reverse dependents. " +
"At depth=2 the default output_mode='summary' returns an aggregated Insights section (dependency hotspots, cycle/layer warnings, size metrics) — \"what is architecturally significant\" — instead of a raw symbol-relations dump; set output_mode='compact'/'full' to get the per-symbol relations list instead. " +
"'Module' means a package-level grouping (e.g. a Go package or TypeScript file group), not a repo. " +
"Accepts absolute filesystem paths — they are normalised automatically. Pass max_tokens to hard-cap large directory/module output. " +
"Use query_facts for precise filtering, traverse for multi-hop graph walks.",
}, func(ctx context.Context, req *mcp.CallToolRequest, args exploreArgs) (*mcp.CallToolResult, any, error) {
if s.toolCallback != nil {
s.toolCallback("explore")
}
store := s.eng.Store()
if store.Count() == 0 {
return errorResult("No facts available. Run generate_snapshot first."), nil, nil
}
if args.Focus == "" {
return errorResult("focus is required"), nil, nil
}
depth := args.Depth
if depth <= 0 {
depth = 1
}
if depth > 2 {
depth = 2
}
var sb strings.Builder
// Normalize absolute filesystem paths to store-relative paths.
focus := s.normalizeToRelative(args.Focus)
// Try to determine focus type by matching against store indexes.
// Priority: exact module name > exact file > symbol name substring > file prefix (directory)
// Special case: "." means the repo root (from normalizing an absolute path that
// equals the snapshot RepoPath). Route directly to directory exploration to avoid
// "." accidentally substring-matching dotted symbol names.
// At depth=2 the default 'summary' mode replaces the raw per-symbol relations
// dump with an aggregated Insights section. compact/full keep the dump.
mode := resolveOutputMode(args.OutputMode, modeSummary)
switch {
case focus == "." && s.exploreDirectory(store, focus, &sb):
case focus != "." && s.exploreModule(store, focus, depth, mode, &sb):
case focus != "." && s.exploreModuleSubstring(store, focus, depth, mode, &sb):
case focus != "." && s.exploreFile(store, focus, depth, &sb):
case focus != "." && s.exploreSymbol(store, focus, depth, &sb):
case s.exploreDirectory(store, focus, &sb):
default:
return errorResult(fmt.Sprintf("No facts matching focus %q. Try a module name, file path, symbol name, or directory prefix.", focus)), nil, nil
}
return textResult(capTokens(sb.String(), args.MaxTokens, false)), nil, nil
})
// Tool: traverse
mcp.AddTool(s.mcp, &mcp.Tool{
Name: "traverse",
Description: "Walk the dependency/call graph from a starting node. " +
"direction='forward' answers \"what does X depend on?\"; direction='reverse' answers \"what depends on X?\". " +
"start= accepts substring match plus scoped prefixes (repo:, kind:, file:) and package-qualified names (e.g. 'domain/cart.CartService') to disambiguate; returns ranked candidates with confidence when ambiguous. " +
"relation_kinds filter: imports, calls, declares, implements, depends_on, has_method. " +
"Forward traversal from a struct/interface follows has_method edges to its methods (and then their calls). " +
"Reverse traversal from a struct/interface automatically includes its methods and constructor as origins, so it surfaces callers (including cross-repo) that reference the type only through a method — matching impact_analysis. " +
"Note: interface method calls cannot be statically bound to a concrete implementation, so such call edges may be absent or appear as unresolved nodes. " +
"node_kinds filters output (not traversal itself): module, symbol, dependency, route, storage. " +
"TOKEN COST — output_mode ladder: 'summary' (DEFAULT) aggregates counts by node/relation kind, internal/external split, and hottest modules (small, no node list); 'compact' lists nodes grouped by depth; 'full' returns the raw JSON node/edge graph and can be VERY large. " +
"Start with summary; escalate to compact/full only when you need specific nodes. Always keep max_depth/max_nodes bounded, and pass max_tokens to hard-cap the response. " +
"Defaults: max_depth=5, max_nodes=100. Use instead of repeated explore calls for transitive relationships.",
}, func(ctx context.Context, req *mcp.CallToolRequest, args traverseArgs) (*mcp.CallToolResult, any, error) {
if s.toolCallback != nil {
s.toolCallback("traverse")
}
store := s.eng.Store()
if store.Count() == 0 {
return errorResult("No facts available. Run generate_snapshot first."), nil, nil
}
graph := store.Graph()
if graph == nil {
return errorResult("No graph available. Run generate_snapshot first."), nil, nil
}
if args.Start == "" {
return errorResult("start is required"), nil, nil
}
// Resolve start name: try exact match first, then substring
startName, res, err := s.resolveNodeName(store, args.Start)
if err != nil {
return errorResult(err.Error()), nil, nil
}
mode := resolveOutputMode(args.OutputMode, modeSummary)
// Over threshold: refuse to guess; return resolution with empty results.
if res != nil && res.Matched == "" {
resp := traverseResponse{
Resolution: res,
TraversalResult: facts.TraversalResult{
Nodes: []facts.TraversalNode{},
Edges: []facts.TraversalEdge{},
},
}
if wantsFullOutput(mode) {
return jsonResultCapped(resp, args.MaxTokens)
}
if wantsSummary(mode) {
return textResult(capTokens(s.renderTraverseSummary(store, resp, args.Start, ""), args.MaxTokens, false)), nil, nil
}
return textResult(capTokens(renderTraverseCompact(resp, args.Start, ""), args.MaxTokens, false)), nil, nil
}
direction := args.Direction
if direction == "" {
direction = "forward"
}
if direction != "forward" && direction != "reverse" {
return errorResult("direction must be 'forward' or 'reverse'"), nil, nil
}
// Reverse traversal of a type must seed its methods + constructor (callers
// reference those, not the bare type), matching impact_analysis — otherwise
// cross-repo and same-repo dependents are missed. Forward already follows
// has_method edges from the type, so it needs no rollup.
var result facts.TraversalResult
if direction == "reverse" {
result = graph.TraverseFrom(graph.RollupSeeds(startName), direction, args.RelationKinds, args.NodeKinds, args.MaxDepth, args.MaxNodes)
} else {
result = graph.Traverse(startName, direction, args.RelationKinds, args.NodeKinds, args.MaxDepth, args.MaxNodes)
}
resp := traverseResponse{Resolution: res, TraversalResult: result}
if wantsFullOutput(mode) {
return jsonResultCapped(resp, args.MaxTokens)
}
if wantsSummary(mode) {
return textResult(capTokens(s.renderTraverseSummary(store, resp, startName, direction), args.MaxTokens, false)), nil, nil
}
return textResult(capTokens(renderTraverseCompact(resp, startName, direction), args.MaxTokens, false)), nil, nil
})
// Tool: find_path
mcp.AddTool(s.mcp, &mcp.Tool{
Name: "find_path",
Description: "Find the shortest path (BFS, by hop count) between two nodes in the architectural graph. " +
"Answers \"how does X reach Y?\" or \"what is the call chain from A to B?\". " +
"from= and to= use substring match with smart disambiguation, and accept scoped prefixes " +
"(repo:, kind:, file:) plus PACKAGE-QUALIFIED names to pin down a common short name — e.g. " +
"to=\"ticket.Repository\" or to=\"repo:golf domain/cart.CartService\" resolves where bare " +
"\"Repository\"/\"CartService\" would be ambiguous. " +
"When an endpoint is ambiguous, find_path TRIES the top candidates (and, for a type, its methods/constructor) " +
"and returns the first path it finds; the response carries resolution objects with the ranked candidates. " +
"If no path connects any candidate pair, found=false and a 'note' explains whether the endpoints were " +
"ambiguous (with the candidates tried) or resolved uniquely but unreachable within max_depth hops.",
}, func(ctx context.Context, req *mcp.CallToolRequest, args findPathArgs) (*mcp.CallToolResult, any, error) {
if s.toolCallback != nil {
s.toolCallback("find_path")
}
store := s.eng.Store()
if store.Count() == 0 {
return errorResult("No facts available. Run generate_snapshot first."), nil, nil
}
graph := store.Graph()
if graph == nil {
return errorResult("No graph available. Run generate_snapshot first."), nil, nil
}
if args.From == "" || args.To == "" {
return errorResult("both 'from' and 'to' are required"), nil, nil
}
fromName, fromRes, err := s.resolveNodeName(store, args.From)
if err != nil {
return errorResult(fmt.Sprintf("from: %v", err)), nil, nil
}
toName, toRes, err := s.resolveNodeName(store, args.To)
if err != nil {
return errorResult(fmt.Sprintf("to: %v", err)), nil, nil
}
// Build ranked candidate lists for each endpoint (most-likely first) and try
// a path across the combinations rather than silently giving up when a name
// is ambiguous. This delivers the "give me vague names and I'll find the
// connection" behavior.
fromCands := s.pathCandidates(store, args.From, fromName, fromRes)
toCands := s.pathCandidates(store, args.To, toName, toRes)
if len(fromCands) == 0 || len(toCands) == 0 {
return jsonResult(findPathResponse{
FromResolution: fromRes,
ToResolution: toRes,
PathResult: facts.PathResult{From: fromName, To: toName, Found: false},
Note: "could not resolve both endpoints to a graph node",
FromTried: fromCands,
ToTried: toCands,
})
}
result := s.bestPath(graph, fromCands, toCands, args.RelationKinds, args.MaxDepth)
resp := findPathResponse{
FromResolution: fromRes,
ToResolution: toRes,
PathResult: result,
FromTried: fromCands,
ToTried: toCands,
}
if !result.Found {
ambiguous := len(fromCands) > 1 || len(toCands) > 1
if ambiguous {
resp.Note = fmt.Sprintf("no path within %d hops between any candidate pair "+
"(from: %d candidate(s), to: %d candidate(s)). Narrow with a package-qualified "+
"name (e.g. \"repo:<label> pkg.Type\") — see from_tried/to_tried.",
effectiveMaxDepth(args.MaxDepth), len(fromCands), len(toCands))
} else {
resp.Note = fmt.Sprintf("both endpoints resolved uniquely, but no path connects them within %d hops",
effectiveMaxDepth(args.MaxDepth))
}
}
return jsonResult(resp)
})
// Tool: impact_analysis
mcp.AddTool(s.mcp, &mcp.Tool{
Name: "impact_analysis",
Description: "Compute the blast radius of changing a target node: all nodes that transitively depend on it, grouped by hop depth. " +
"Use for refactoring planning and change risk assessment. " +
"target= uses substring match with smart disambiguation. " +
"Default: reverse direction only (what breaks if target changes). " +
"Set include_forward=true to also see what the target itself depends on (useful for understanding what could break the target). " +
"TOKEN COST — output_mode ladder: 'summary' (DEFAULT) gives the accurate total dependent count plus breakdowns by kind/depth, hotspot modules, cross-repo reach, and any cycle/layer insights touching the target (small, no node list); 'compact' lists dependents grouped by hop depth; 'full' returns the raw JSON by_depth/edges graph and can be VERY large. " +
"Start with summary; escalate only when you need the specific nodes. Keep max_depth/max_nodes bounded and pass max_tokens to hard-cap the response. " +
"Defaults: max_depth=3, max_nodes=200.",
}, func(ctx context.Context, req *mcp.CallToolRequest, args impactAnalysisArgs) (*mcp.CallToolResult, any, error) {
if s.toolCallback != nil {
s.toolCallback("impact_analysis")
}
store := s.eng.Store()
if store.Count() == 0 {
return errorResult("No facts available. Run generate_snapshot first."), nil, nil
}
graph := store.Graph()
if graph == nil {
return errorResult("No graph available. Run generate_snapshot first."), nil, nil
}
if args.Target == "" {
return errorResult("target is required"), nil, nil
}
targetName, res, err := s.resolveNodeName(store, args.Target)
if err != nil {
return errorResult(err.Error()), nil, nil
}
mode := resolveOutputMode(args.OutputMode, modeSummary)
// Over threshold: refuse to guess; return resolution with empty results.
if res != nil && res.Matched == "" {
resp := impactResponse{
Resolution: res,
ImpactResult: facts.ImpactResult{
Target: args.Target,
ByDepth: map[int][]facts.TraversalNode{},
Edges: []facts.TraversalEdge{},
},
}
if wantsFullOutput(mode) {
return jsonResultCapped(resp, args.MaxTokens)
}
if wantsSummary(mode) {
return textResult(capTokens(s.renderImpactSummary(resp), args.MaxTokens, false)), nil, nil
}
return textResult(capTokens(renderImpactCompact(resp), args.MaxTokens, false)), nil, nil
}
result := graph.ImpactSet(targetName, args.MaxDepth, args.MaxNodes, args.IncludeForward)
resp := impactResponse{Resolution: res, ImpactResult: result}
if wantsFullOutput(mode) {
return jsonResultCapped(resp, args.MaxTokens)
}
if wantsSummary(mode) {
return textResult(capTokens(s.renderImpactSummary(resp), args.MaxTokens, false)), nil, nil
}
return textResult(capTokens(renderImpactCompact(resp), args.MaxTokens, false)), nil, nil