-
-
Notifications
You must be signed in to change notification settings - Fork 340
Expand file tree
/
Copy pathmcp.go
More file actions
602 lines (524 loc) · 19.9 KB
/
Copy pathmcp.go
File metadata and controls
602 lines (524 loc) · 19.9 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
// SPDX-License-Identifier: MIT
package main
import (
"cmp"
"context"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"github.com/boyter/scc/v4/processor"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
// mcpMu serializes MCP tool calls so concurrent requests
// don't race on processor package globals.
var mcpMu sync.Mutex
func startMCPServer() {
mcpServer := server.NewMCPServer(
"scc",
processor.Version,
server.WithToolCapabilities(false),
)
analyzeTool := mcp.NewTool("analyze",
mcp.WithDescription(`Count lines of code, comments, blanks and estimate complexity for a project directory or file. Supports 200+ languages.
Returns per-language summary with:
- files: number of source files
- lines: total lines
- code: lines of actual code
- comment: lines of comments
- blank: blank lines
- complexity: estimated cyclomatic complexity
- cognitive: nesting-weighted cognitive complexity (only when cognitive=true; 0 otherwise)
- bytes: total size in bytes
Also returns COCOMO cost/schedule estimates and optionally LOCOMO (LLM cost) estimates.
Use by_file with sort=complexity to find the most complex files in a project.`),
mcp.WithString("path",
mcp.Description("Directory or file path to analyze. Defaults to current directory."),
),
mcp.WithString("sort",
mcp.Description("Column to sort results by: files, name, lines, blank, code, comment, complexity, bytes. Default: files."),
),
mcp.WithBoolean("by_file",
mcp.Description("If true, return per-file results instead of per-language summary. Useful with sort to find e.g. the most complex or largest files. Use with limit to control response size."),
),
mcp.WithNumber("limit",
mcp.Description("Maximum number of files to return per language when by_file is true. Defaults to 10. Set to -1 for unlimited."),
),
mcp.WithString("include_ext",
mcp.Description("Comma-separated list of file extensions to include (e.g. 'go,java,js')."),
),
mcp.WithString("exclude_ext",
mcp.Description("Comma-separated list of file extensions to exclude (e.g. 'json,xml')."),
),
mcp.WithBoolean("no_duplicates",
mcp.Description("Remove duplicate files from stats."),
),
mcp.WithBoolean("no_min_gen",
mcp.Description("Exclude minified or generated files."),
),
mcp.WithBoolean("cognitive",
mcp.Description("Compute nesting-weighted cognitive complexity in addition to cyclomatic complexity. Adds a 'cognitive' field to per-language, per-file and totals results. Off by default; when off the field is 0."),
),
mcp.WithBoolean("locomo",
mcp.Description("Include LOCOMO (LLM Output COst MOdel) cost estimation in results."),
),
mcp.WithString("locomo_preset",
mcp.Description("LOCOMO model preset: large (GPT-4/Opus class), medium (Sonnet class), small (Haiku class), local (local LLM). Default: medium."),
),
)
mcpServer.AddTool(analyzeTool, mcpAnalyzeHandler)
hotspotsTool := mcp.NewTool("hotspots",
mcp.WithDescription(`Rank the files in a git repository by "hotspot" score: complexity × change-frequency over recent history. Hotspots are the files most likely to need refactoring or the most attention during review — high complexity that also changes often.
Walks the repo's git log (most recent commits first) and returns, per surviving file:
- file: path relative to the repo root
- language: detected language
- complexity: estimated cyclomatic complexity at HEAD
- commits: number of commits touching the file within the window
- linesChanged: total added + removed lines across the window
- authors: distinct authors (folded via .mailmap)
- codeChurn / commentChurn: added lines classified as code vs comment
- score: 0–100, normalised complexity × commits (higher = hotter)
Also returns the history window walked (depth, commit count, date range). Requires path to be inside a git repository.`),
mcp.WithString("path",
mcp.Description("Directory inside the git repository to analyze. Defaults to current directory."),
),
mcp.WithNumber("depth",
mcp.Description("Maximum number of recent commits to walk. Defaults to 1000. Set to 0 for unlimited (slower on large repos)."),
),
mcp.WithNumber("limit",
mcp.Description("Maximum number of files to return, highest-scoring first. Defaults to 50. Set to -1 for unlimited."),
),
)
mcpServer.AddTool(hotspotsTool, mcpHotspotsHandler)
couplingTool := mcp.NewTool("coupling",
mcp.WithDescription(`Return change-coupling from a git repository's history — files that historically change together. Has two modes, selected by whether the 'file' argument is set.
WITH 'file' — the target file's "blast radius": the other files that change together with it. Use this before editing a file to discover what else you will likely need to read or change. For the target, returns each coupled file with:
- file: path relative to the repo root
- shared: number of commits that changed BOTH the target and this file
- partnerCommits: this file's own commit count in the window
- couple: P(this file changes | you changed the target), 0–100 — the blast-radius probability
- reverse: P(target changes | this file changed), 0–100 — a large gap from couple marks a hub-style (asymmetric) link rather than a true peer coupling
Partners are ranked by degree (highest first; base-rate corrected). Also returns the target's own commit count (targetCommits) and the history window walked.
WITHOUT 'file' — the repo-wide all-pairs overview: every file pair that changes together, strongest first. For each pair, returns:
- fileA, fileB: the two coupled paths, relative to the repo root
- shared: number of commits that changed BOTH files
- commitsA, commitsB: each file's own commit count in the window
- degree: symmetric coupling ratio shared/(commitsA+commitsB−shared), 0–100
Pairs are ranked strongest first (most shared commits). Also returns the history window walked.
Requires path to be inside a git repository.`),
mcp.WithString("file",
mcp.Description("Optional target file path (relative to the repo, as it appears at HEAD). Set it for the per-file blast-radius view; omit it for the repo-wide all-pairs report."),
),
mcp.WithString("path",
mcp.Description("Directory inside the git repository to analyze. Defaults to current directory."),
),
mcp.WithNumber("depth",
mcp.Description("Maximum number of recent commits to walk. Defaults to 1000. Set to 0 for unlimited (slower on large repos)."),
),
mcp.WithNumber("limit",
mcp.Description("Maximum rows to return, strongest first — coupled files in per-file mode, file pairs in all-pairs mode. Defaults to 50. Set to -1 for unlimited."),
),
)
mcpServer.AddTool(couplingTool, mcpCouplingHandler)
errLogger := log.New(os.Stderr, "scc-mcp: ", log.LstdFlags)
if err := server.ServeStdio(mcpServer, server.WithErrorLogger(errLogger)); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "scc-mcp: server error: %v\n", err)
os.Exit(1)
}
}
type mcpAnalyzeResponse struct {
Path string `json:"path"`
Languages []mcpLanguageResult `json:"languages"`
Totals mcpTotals `json:"totals"`
COCOMO *mcpCOCOMO `json:"cocomo,omitempty"`
LOCOMO *mcpLOCOMO `json:"locomo,omitempty"`
FileCount int64 `json:"totalFiles"`
TotalLines int64 `json:"totalLines"`
TotalCode int64 `json:"totalCode"`
}
type mcpLanguageResult struct {
Name string `json:"name"`
Files int64 `json:"files"`
Lines int64 `json:"lines"`
Code int64 `json:"code"`
Comment int64 `json:"comment"`
Blank int64 `json:"blank"`
Complexity int64 `json:"complexity"`
Cognitive int64 `json:"cognitive"`
Bytes int64 `json:"bytes"`
FileList []mcpFileResult `json:"fileList,omitempty"`
}
type mcpFileResult struct {
Location string `json:"location"`
Filename string `json:"filename"`
Language string `json:"language"`
Lines int64 `json:"lines"`
Code int64 `json:"code"`
Comment int64 `json:"comment"`
Blank int64 `json:"blank"`
Complexity int64 `json:"complexity"`
Cognitive int64 `json:"cognitive"`
Bytes int64 `json:"bytes"`
}
type mcpTotals struct {
Files int64 `json:"files"`
Lines int64 `json:"lines"`
Code int64 `json:"code"`
Comment int64 `json:"comment"`
Blank int64 `json:"blank"`
Complexity int64 `json:"complexity"`
Cognitive int64 `json:"cognitive"`
Bytes int64 `json:"bytes"`
}
type mcpCOCOMO struct {
EstimatedCost float64 `json:"estimatedCost"`
EstimatedScheduleMonths float64 `json:"estimatedScheduleMonths"`
EstimatedPeople float64 `json:"estimatedPeople"`
}
type mcpLOCOMO struct {
Cost float64 `json:"cost"`
InputTokens float64 `json:"inputTokens"`
OutputTokens float64 `json:"outputTokens"`
GenerationSeconds float64 `json:"generationSeconds"`
ReviewHours float64 `json:"reviewHours"`
Preset string `json:"preset"`
AverageComplexityMult float64 `json:"averageComplexityMultiplier"`
Cycles float64 `json:"cycles"`
}
func mcpAnalyzeHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
// Extract parameters
path := "."
if p, ok := args["path"].(string); ok && p != "" {
path = p
}
// Resolve to absolute path
absPath, err := filepath.Abs(path)
if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("invalid path: %v", err)), nil
}
// Verify path can be accessed
if _, err := os.Stat(absPath); err != nil {
return mcp.NewToolResultError(fmt.Sprintf("path cannot be accessed: %s: %v", absPath, err)), nil
}
// Serialize access to processor globals so concurrent MCP
// requests don't race on shared state.
mcpMu.Lock()
defer mcpMu.Unlock()
// Configure processor globals for this request.
// Some defaults are normally set by cobra flags which the MCP path
// bypasses, so we set them explicitly here.
processor.DirFilePaths = []string{absPath}
processor.Format = "json"
processor.Cocomo = false
processor.Size = false
processor.Files = false
processor.PathDenyList = []string{".git", ".hg", ".svn"}
processor.ExcludeFilename = []string{"package-lock.json", "Cargo.lock", "yarn.lock", "pubspec.lock", "Podfile.lock", "pnpm-lock.yaml"}
if sortBy, ok := args["sort"].(string); ok && sortBy != "" {
processor.SortBy = sortBy
} else {
processor.SortBy = "files"
}
if byFile, ok := args["by_file"].(bool); ok && byFile {
processor.Files = true
}
fileLimit := 10 // default limit when by_file is true
if l, ok := args["limit"].(float64); ok {
if l < 0 {
fileLimit = 0 // -1 (or any negative) means unlimited
} else {
fileLimit = int(l)
}
}
if includeExt, ok := args["include_ext"].(string); ok && includeExt != "" {
processor.AllowListExtensions = splitAndTrimExtensions(includeExt)
} else {
processor.AllowListExtensions = []string{}
}
if excludeExt, ok := args["exclude_ext"].(string); ok && excludeExt != "" {
processor.ExcludeListExtensions = splitAndTrimExtensions(excludeExt)
} else {
processor.ExcludeListExtensions = []string{}
}
if noDups, ok := args["no_duplicates"].(bool); ok && noDups {
processor.Duplicates = true
} else {
processor.Duplicates = false
}
if noMinGen, ok := args["no_min_gen"].(bool); ok && noMinGen {
processor.IgnoreMinifiedGenerate = true
// GeneratedMarkers is normally set by cobra flag defaults which
// the MCP path bypasses, so set them here.
if len(processor.GeneratedMarkers) == 0 {
processor.GeneratedMarkers = []string{"do not edit", "<auto-generated />"}
}
} else {
processor.IgnoreMinifiedGenerate = false
}
if cognitive, ok := args["cognitive"].(bool); ok && cognitive {
processor.Cognitive = true
} else {
processor.Cognitive = false
}
if locomo, ok := args["locomo"].(bool); ok && locomo {
processor.Locomo = true
} else {
processor.Locomo = false
}
if locomoPreset, ok := args["locomo_preset"].(string); ok && locomoPreset != "" {
processor.LocomoPresetName = locomoPreset
} else {
processor.LocomoPresetName = "medium"
}
processor.ConfigureLazy(true)
// Run the analysis
language, err := processor.ProcessResult()
if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("analysis failed: %v", err)), nil
}
// Build response
var totals mcpTotals
langs := make([]mcpLanguageResult, 0, len(language))
for _, l := range language {
lr := mcpLanguageResult{
Name: l.Name,
Files: l.Count,
Lines: l.Lines,
Code: l.Code,
Comment: l.Comment,
Blank: l.Blank,
Complexity: l.Complexity,
Cognitive: l.Cognitive,
Bytes: l.Bytes,
}
if processor.Files && len(l.Files) > 0 {
files := l.Files
// Sort files within each language by the same criteria
// used for languages so per-file output is ordered and
// limit returns the top N rather than an arbitrary slice.
sortFileJobs(files)
if fileLimit > 0 && len(files) > fileLimit {
files = files[:fileLimit]
}
lr.FileList = make([]mcpFileResult, 0, len(files))
for _, f := range files {
lr.FileList = append(lr.FileList, mcpFileResult{
Location: f.Location,
Filename: f.Filename,
Language: f.Language,
Lines: f.Lines,
Code: f.Code,
Comment: f.Comment,
Blank: f.Blank,
Complexity: f.Complexity,
Cognitive: f.Cognitive,
Bytes: f.Bytes,
})
}
}
langs = append(langs, lr)
totals.Files += l.Count
totals.Lines += l.Lines
totals.Code += l.Code
totals.Comment += l.Comment
totals.Blank += l.Blank
totals.Complexity += l.Complexity
totals.Cognitive += l.Cognitive
totals.Bytes += l.Bytes
}
resp := mcpAnalyzeResponse{
Path: absPath,
Languages: langs,
Totals: totals,
FileCount: totals.Files,
TotalLines: totals.Lines,
TotalCode: totals.Code,
}
// COCOMO estimate
estimatedEffort := processor.EstimateEffort(totals.Code, processor.EAF)
estimatedCost := processor.EstimateCost(estimatedEffort, processor.AverageWage, processor.Overhead)
estimatedScheduleMonths := processor.EstimateScheduleMonths(estimatedEffort)
estimatedPeople := 0.0
if estimatedScheduleMonths > 0 {
estimatedPeople = estimatedEffort / estimatedScheduleMonths
}
resp.COCOMO = &mcpCOCOMO{
EstimatedCost: estimatedCost,
EstimatedScheduleMonths: estimatedScheduleMonths,
EstimatedPeople: estimatedPeople,
}
// LOCOMO estimate if requested
if processor.Locomo {
result := processor.LocomoEstimate(totals.Code, totals.Complexity)
resp.LOCOMO = &mcpLOCOMO{
Cost: result.Cost,
InputTokens: result.InputTokens,
OutputTokens: result.OutputTokens,
GenerationSeconds: result.GenerationSeconds,
ReviewHours: result.ReviewHours,
Preset: result.Preset,
AverageComplexityMult: result.AverageComplexityMult,
Cycles: result.IterationFactor,
}
}
// Serialize to JSON
jsonBytes, err := jsonMarshal(resp)
if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("failed to serialize results: %v", err)), nil
}
return mcp.NewToolResultText(string(jsonBytes)), nil
}
func mcpHotspotsHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
path := "."
if p, ok := args["path"].(string); ok && p != "" {
path = p
}
absPath, err := filepath.Abs(path)
if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("invalid path: %v", err)), nil
}
if _, err := os.Stat(absPath); err != nil {
return mcp.NewToolResultError(fmt.Sprintf("path cannot be accessed: %s: %v", absPath, err)), nil
}
// Serialize access to processor globals so concurrent MCP
// requests don't race on shared state.
mcpMu.Lock()
defer mcpMu.Unlock()
// HistoryDepth is normally set by a cobra flag default which the MCP path
// bypasses, so set it explicitly. Default mirrors the CLI's 1000.
processor.HistoryDepth = 1000
if d, ok := args["depth"].(float64); ok {
if d < 0 {
d = 0
}
processor.HistoryDepth = int(d)
}
fileLimit := 50 // default cap so responses stay bounded for the model
if l, ok := args["limit"].(float64); ok {
if l < 0 {
fileLimit = 0 // -1 (or any negative) means unlimited
} else {
fileLimit = int(l)
}
}
// Build the language database (ExtensionToLanguage etc.) and enable lazy
// per-language feature loading. Process() does this before the hotspots
// report on the cobra path; the analyze handler gets it via ProcessResult.
// Without ProcessConstants the HEAD tree can't be classified, so every
// file is dropped and the report comes back empty.
processor.ProcessConstants()
processor.ConfigureLazy(true)
out, err := processor.HotspotsJSONReport(absPath, fileLimit)
if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("hotspots analysis failed: %v", err)), nil
}
return mcp.NewToolResultText(out), nil
}
func mcpCouplingHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
target, _ := args["file"].(string)
path := "."
if p, ok := args["path"].(string); ok && p != "" {
path = p
}
absPath, err := filepath.Abs(path)
if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("invalid path: %v", err)), nil
}
if _, err := os.Stat(absPath); err != nil {
return mcp.NewToolResultError(fmt.Sprintf("path cannot be accessed: %s: %v", absPath, err)), nil
}
// Serialize access to processor globals so concurrent MCP requests don't
// race on shared state.
mcpMu.Lock()
defer mcpMu.Unlock()
processor.HistoryDepth = 1000
if d, ok := args["depth"].(float64); ok {
if d < 0 {
d = 0
}
processor.HistoryDepth = int(d)
}
fileLimit := 50
if l, ok := args["limit"].(float64); ok {
if l < 0 {
fileLimit = 0
} else {
fileLimit = int(l)
}
}
processor.ProcessConstants()
processor.ConfigureLazy(true)
// file set → per-file blast radius; file omitted → repo-wide all-pairs.
var out string
if target != "" {
out, err = processor.CouplingForJSONReport(absPath, target, fileLimit)
} else {
out, err = processor.CouplingJSONReport(absPath, fileLimit)
}
if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("coupling analysis failed: %v", err)), nil
}
return mcp.NewToolResultText(out), nil
}
func jsonMarshal(v any) ([]byte, error) {
return json.MarshalIndent(v, "", " ")
}
// sortFileJobs sorts a slice of FileJob pointers using the current
// processor.SortBy value so that the most relevant files come first.
func sortFileJobs(files []*processor.FileJob) {
switch processor.SortBy {
case "name", "names", "language", "languages", "lang", "langs":
slices.SortFunc(files, func(a, b *processor.FileJob) int {
return strings.Compare(a.Filename, b.Filename)
})
case "line", "lines":
slices.SortFunc(files, func(a, b *processor.FileJob) int {
return cmp.Compare(b.Lines, a.Lines)
})
case "blank", "blanks":
slices.SortFunc(files, func(a, b *processor.FileJob) int {
return cmp.Compare(b.Blank, a.Blank)
})
case "code", "codes":
slices.SortFunc(files, func(a, b *processor.FileJob) int {
return cmp.Compare(b.Code, a.Code)
})
case "comment", "comments":
slices.SortFunc(files, func(a, b *processor.FileJob) int {
return cmp.Compare(b.Comment, a.Comment)
})
case "complexity", "complexitys":
slices.SortFunc(files, func(a, b *processor.FileJob) int {
return cmp.Compare(b.Complexity, a.Complexity)
})
case "byte", "bytes":
slices.SortFunc(files, func(a, b *processor.FileJob) int {
return cmp.Compare(b.Bytes, a.Bytes)
})
default:
slices.SortFunc(files, func(a, b *processor.FileJob) int {
return cmp.Compare(b.Lines, a.Lines)
})
}
}
// splitAndTrimExtensions splits a comma-separated string into
// trimmed, non-empty extension entries.
func splitAndTrimExtensions(s string) []string {
parts := strings.Split(s, ",")
result := make([]string, 0, len(parts))
for _, p := range parts {
p = strings.TrimSpace(p)
if p != "" {
result = append(result, p)
}
}
return result
}