forked from boyter/scc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp.go
More file actions
409 lines (362 loc) · 12.4 KB
/
Copy pathmcp.go
File metadata and controls
409 lines (362 loc) · 12.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
// SPDX-License-Identifier: MIT
package main
import (
"cmp"
"context"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"github.com/boyter/scc/v3/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
- 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("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)
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"`
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"`
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"`
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 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,
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,
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.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 jsonMarshal(v interface{}) ([]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
}