-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1940 lines (1658 loc) · 67.9 KB
/
Copy pathmain.go
File metadata and controls
1940 lines (1658 loc) · 67.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
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 main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"log/slog"
"os"
"strings"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
"github.com/sgaunet/gitlab-mcp/internal/app"
"github.com/sgaunet/gitlab-mcp/internal/logger"
)
// Version information injected at build time.
var version = "dev"
const (
defaultLimit = 100
defaultStateOpened = "opened"
defaultStateClosed = "closed"
)
// ToolCategoryFlags controls which tool categories are enabled.
type ToolCategoryFlags struct {
Issues bool // Issue management tools
Labels bool // Label management tools
ProjectMetadata bool // Project metadata tools
Epics bool // Epic management tools (Premium/Ultimate tier)
Pipelines bool // CI/CD pipeline tools
MergeRequests bool // Merge request management tools
}
// Error variables for static errors.
var (
ErrInvalidStateValue = errors.New("state must be 'opened' or 'closed'")
ErrGroupPathRequired = errors.New("group_path is required and must be a non-empty string")
ErrEpicIIDRequired = errors.New("epic_iid is required and must be a number")
ErrEpicIIDMustBePositive = errors.New("epic_iid must be greater than 0")
ErrProjectPathRequired = errors.New("project_path is required and must be a non-empty string")
ErrIssueIIDRequired = errors.New("issue_iid is required and must be a number")
ErrIssueIIDMustBePositive = errors.New("issue_iid must be greater than 0")
ErrInvalidJobStatus = errors.New("invalid job status")
ErrJobIDRequired = errors.New("job_id must be a number")
ErrJobIDMustBePositive = errors.New("job_id must be positive")
)
// setupListIssuesTool creates and registers the list_issues tool.
//
//nolint:cyclop,funlen // Parameter extraction requires multiple branches
func setupListIssuesTool(s *server.MCPServer, appInstance *app.App, debugLogger *slog.Logger) {
listIssuesTool := mcp.NewTool("list_issues",
mcp.WithDescription("List issues for a GitLab project by project path. "+
"By default, includes issues from both the project and its parent group(s) for comprehensive visibility. "+
"Use include_group_issues=false to retrieve only project-level issues."),
mcp.WithString("project_path",
mcp.Required(),
mcp.Description("GitLab project path including all namespaces (e.g., 'namespace/project-name' or "+
"'company/department/team/project'). Run 'git remote -v' to find the full path from the repository URL"),
),
mcp.WithString("state",
mcp.Description("Filter by issue state: opened, closed, or all (default: opened)"),
),
mcp.WithString("labels",
mcp.Description("Comma-separated list of labels to filter by"),
),
mcp.WithNumber("limit",
mcp.Description("Maximum number of issues to return (default: 100, max: 100)"),
),
mcp.WithBoolean("include_group_issues",
mcp.Description("Include issues from parent group(s). Defaults to true for comprehensive results. "+
"Set to false to retrieve only project-level issues."),
),
)
s.AddTool(listIssuesTool, func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
debugLogger.Debug("Received list_issues tool request", "args", args)
// Extract project_path
projectPath, ok := args["project_path"].(string)
if !ok || projectPath == "" {
debugLogger.Error("project_path is not a valid string", "value", args["project_path"])
return mcp.NewToolResultError("project_path must be a non-empty string"), nil
}
// Extract optional parameters
opts := &app.ListIssuesOptions{
State: defaultStateOpened, // default
Limit: defaultLimit, // default
IncludeGroupIssues: true, // default to true for comprehensive results
}
if state, ok := args["state"].(string); ok && state != "" {
opts.State = state
}
if labels, ok := args["labels"].(string); ok && labels != "" {
opts.Labels = labels
}
if limitFloat, ok := args["limit"].(float64); ok {
opts.Limit = int64(limitFloat)
}
// Extract include_group_issues (defaults to true)
if includeGroupIssues, ok := args["include_group_issues"].(bool); ok {
opts.IncludeGroupIssues = includeGroupIssues
}
debugLogger.Debug("Processing list_issues request", "project_path", projectPath, "opts", opts)
// Call the app method
issues, err := appInstance.ListProjectIssues(projectPath, opts)
if err != nil {
debugLogger.Error("Failed to list project issues", "error", err, "project_path", projectPath)
return mcp.NewToolResultError(fmt.Sprintf("Failed to list project issues: %v", err)), nil
}
// Convert issues to JSON
jsonData, err := json.Marshal(issues)
if err != nil {
debugLogger.Error("Failed to marshal issues to JSON", "error", err)
return mcp.NewToolResultError("Failed to format issues response"), nil
}
debugLogger.Info("Successfully retrieved project issues", "count", len(issues), "project_path", projectPath)
return mcp.NewToolResultText(string(jsonData)), nil
})
}
// setupCreateIssueTool creates and registers the create_issues tool.
func setupCreateIssueTool(s *server.MCPServer, appInstance *app.App, debugLogger *slog.Logger) {
createIssueTool := mcp.NewTool("create_issues",
mcp.WithDescription("Create a new issue for a GitLab project by project path"),
mcp.WithString("project_path",
mcp.Required(),
mcp.Description("GitLab project path including all namespaces (e.g., 'namespace/project-name' or "+
"'company/department/team/project'). Run 'git remote -v' to find the full path from the repository URL"),
),
mcp.WithString("title",
mcp.Required(),
mcp.Description("Issue title"),
),
mcp.WithString("description",
mcp.Description("Issue description"),
),
mcp.WithArray("labels",
mcp.Description("Array of labels to assign to the issue. Labels must exist in the project. "+
"Use list_labels tool to see available labels. Set GITLAB_VALIDATE_LABELS=false to disable validation."),
),
mcp.WithArray("assignees",
mcp.Description("Array of user IDs to assign to the issue"),
),
)
s.AddTool(createIssueTool, handleCreateIssueRequest(appInstance, debugLogger))
}
// handleCreateIssueRequest handles the create_issues tool request.
func handleCreateIssueRequest(
appInstance *app.App,
debugLogger *slog.Logger,
) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
debugLogger.Debug("Received create_issues tool request", "args", args)
// Extract project_path
projectPath, ok := args["project_path"].(string)
if !ok || projectPath == "" {
debugLogger.Error("project_path is not a valid string", "value", args["project_path"])
return mcp.NewToolResultError("project_path must be a non-empty string"), nil
}
// Extract title (required)
title, ok := args["title"].(string)
if !ok || title == "" {
debugLogger.Error("title is missing or not a string", "value", args["title"])
return mcp.NewToolResultError("title must be a non-empty string"), nil
}
// Extract options
opts := extractCreateIssueOptions(args, title)
debugLogger.Debug("Processing create_issues request", "project_path", projectPath, "title", title)
// Call the app method
issue, err := appInstance.CreateProjectIssue(projectPath, opts)
if err != nil {
debugLogger.Error("Failed to create issue", "error", err, "project_path", projectPath, "title", title)
return mcp.NewToolResultError(fmt.Sprintf("Failed to create issue: %v", err)), nil
}
// Convert issue to JSON
jsonData, err := json.Marshal(issue)
if err != nil {
debugLogger.Error("Failed to marshal issue to JSON", "error", err)
return mcp.NewToolResultError("Failed to format issue response"), nil
}
debugLogger.Info("Successfully created issue",
"id", issue.ID,
"iid", issue.IID,
"project_path", projectPath,
"title", issue.Title)
return mcp.NewToolResultText(string(jsonData)), nil
}
}
// extractCreateIssueOptions extracts create issue options from arguments.
func extractCreateIssueOptions(args map[string]any, title string) *app.CreateIssueOptions {
opts := &app.CreateIssueOptions{
Title: title,
}
// Extract optional description
if description, ok := args["description"].(string); ok {
opts.Description = description
}
// Extract optional labels
if labelsInterface, ok := args["labels"].([]any); ok {
labels := make([]string, 0, len(labelsInterface))
for _, label := range labelsInterface {
if labelStr, ok := label.(string); ok {
labels = append(labels, labelStr)
}
}
opts.Labels = labels
}
// Extract optional assignees
if assigneesInterface, ok := args["assignees"].([]any); ok {
assignees := make([]int64, 0, len(assigneesInterface))
for _, assignee := range assigneesInterface {
if assigneeFloat, ok := assignee.(float64); ok {
assignees = append(assignees, int64(assigneeFloat))
}
}
opts.Assignees = assignees
}
return opts
}
// setupUpdateIssueTool creates and registers the update_issues tool.
func setupUpdateIssueTool(s *server.MCPServer, appInstance *app.App, debugLogger *slog.Logger) {
updateIssueTool := mcp.NewTool("update_issues",
mcp.WithDescription("Update an existing issue for a GitLab project by project path"),
mcp.WithString("project_path",
mcp.Required(),
mcp.Description("GitLab project path including all namespaces (e.g., 'namespace/project-name' or "+
"'company/department/team/project'). Run 'git remote -v' to find the full path from the repository URL"),
),
mcp.WithNumber("issue_iid",
mcp.Required(),
mcp.Description("Issue internal ID (IID) to update"),
),
mcp.WithString("title",
mcp.Description("Updated issue title"),
),
mcp.WithString("description",
mcp.Description("Updated issue description"),
),
mcp.WithString("state",
mcp.Description("Issue state: 'opened' or 'closed'"),
),
mcp.WithArray("labels",
mcp.Description("Array of labels to assign to the issue. Labels must exist in the project. "+
"Use list_labels tool to see available labels. Set GITLAB_VALIDATE_LABELS=false to disable validation."),
),
mcp.WithArray("assignees",
mcp.Description("Array of user IDs to assign to the issue"),
),
)
s.AddTool(updateIssueTool, handleUpdateIssueRequest(appInstance, debugLogger))
}
// handleUpdateIssueRequest handles the update_issues tool request.
func handleUpdateIssueRequest(
appInstance *app.App,
debugLogger *slog.Logger,
) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
debugLogger.Debug("Received update_issues tool request", "args", args)
// Extract project_path
projectPath, ok := args["project_path"].(string)
if !ok || projectPath == "" {
debugLogger.Error("project_path is not a valid string", "value", args["project_path"])
return mcp.NewToolResultError("project_path must be a non-empty string"), nil
}
// Extract issue_iid (required)
issueIIDFloat, ok := args["issue_iid"].(float64)
if !ok {
debugLogger.Error("issue_iid is missing or not a number", "value", args["issue_iid"])
return mcp.NewToolResultError("issue_iid must be a number"), nil
}
issueIID := int64(issueIIDFloat)
// Extract options
opts, err := extractUpdateIssueOptions(args, debugLogger)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
debugLogger.Debug("Processing update_issues request", "project_path", projectPath, "issue_iid", issueIID)
// Call the app method
issue, err := appInstance.UpdateProjectIssue(projectPath, issueIID, opts)
if err != nil {
debugLogger.Error("Failed to update issue", "error", err, "project_path", projectPath, "issue_iid", issueIID)
return mcp.NewToolResultError(fmt.Sprintf("Failed to update issue: %v", err)), nil
}
// Convert issue to JSON
jsonData, err := json.Marshal(issue)
if err != nil {
debugLogger.Error("Failed to marshal issue to JSON", "error", err)
return mcp.NewToolResultError("Failed to format issue response"), nil
}
debugLogger.Info("Successfully updated issue", "id", issue.ID, "iid", issue.IID, "project_path", projectPath)
return mcp.NewToolResultText(string(jsonData)), nil
}
}
// extractUpdateIssueOptions extracts update issue options from arguments.
func extractUpdateIssueOptions(args map[string]any, debugLogger *slog.Logger) (*app.UpdateIssueOptions, error) {
opts := &app.UpdateIssueOptions{}
// Extract basic string fields
extractUpdateStringFields(args, opts)
// Extract and validate state
if err := extractUpdateState(args, opts, debugLogger); err != nil {
return nil, err
}
// Extract array fields
extractUpdateArrayFields(args, opts)
return opts, nil
}
// extractUpdateStringFields extracts string fields for update options.
func extractUpdateStringFields(args map[string]any, opts *app.UpdateIssueOptions) {
if title, ok := args["title"].(string); ok && title != "" {
opts.Title = title
}
if description, ok := args["description"].(string); ok {
opts.Description = description
}
}
// extractUpdateState extracts and validates the state field.
func extractUpdateState(args map[string]any, opts *app.UpdateIssueOptions, debugLogger *slog.Logger) error {
if state, ok := args["state"].(string); ok && state != "" {
if state != defaultStateOpened && state != defaultStateClosed {
debugLogger.Error("invalid state value", "state", state)
return ErrInvalidStateValue
}
opts.State = state
}
return nil
}
// extractUpdateArrayFields extracts array fields for update options.
func extractUpdateArrayFields(args map[string]any, opts *app.UpdateIssueOptions) {
// Extract optional labels
if labelsInterface, ok := args["labels"].([]any); ok {
labels := make([]string, 0, len(labelsInterface))
for _, label := range labelsInterface {
if labelStr, ok := label.(string); ok {
labels = append(labels, labelStr)
}
}
opts.Labels = labels
}
// Extract optional assignees
if assigneesInterface, ok := args["assignees"].([]any); ok {
assignees := make([]int64, 0, len(assigneesInterface))
for _, assignee := range assigneesInterface {
if assigneeFloat, ok := assignee.(float64); ok {
assignees = append(assignees, int64(assigneeFloat))
}
}
opts.Assignees = assignees
}
}
// setupListLabelsTool creates and registers the list_labels tool.
func setupListLabelsTool(s *server.MCPServer, appInstance *app.App, debugLogger *slog.Logger) {
listLabelsTool := mcp.NewTool("list_labels",
mcp.WithDescription("List labels for a GitLab project by project path"),
mcp.WithString("project_path",
mcp.Required(),
mcp.Description("GitLab project path including all namespaces (e.g., 'namespace/project-name' or "+
"'company/department/team/project'). Run 'git remote -v' to find the full path from the repository URL"),
),
mcp.WithBoolean("with_counts",
mcp.Description("Include issue and merge request counts (default: false)"),
),
mcp.WithBoolean("include_ancestor_groups",
mcp.Description("Include labels from ancestor groups (default: false)"),
),
mcp.WithString("search",
mcp.Description("Filter labels by search keyword"),
),
mcp.WithNumber("limit",
mcp.Description("Maximum number of labels to return (default: 100, max: 100)"),
),
)
s.AddTool(listLabelsTool, handleListLabelsRequest(appInstance, debugLogger))
}
// handleListLabelsRequest handles the list_labels tool request.
func handleListLabelsRequest(
appInstance *app.App,
debugLogger *slog.Logger,
) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
debugLogger.Debug("Received list_labels tool request", "args", args)
// Extract project_path
projectPath, ok := args["project_path"].(string)
if !ok || projectPath == "" {
debugLogger.Error("project_path is not a valid string", "value", args["project_path"])
return mcp.NewToolResultError("project_path must be a non-empty string"), nil
}
// Extract optional parameters
opts := extractListLabelsOptions(args)
debugLogger.Debug("Processing list_labels request", "project_path", projectPath, "opts", opts)
// Call the app method
labels, err := appInstance.ListProjectLabels(projectPath, opts)
if err != nil {
debugLogger.Error("Failed to list project labels", "error", err, "project_path", projectPath)
return mcp.NewToolResultError(fmt.Sprintf("Failed to list project labels: %v", err)), nil
}
// Convert labels to JSON
jsonData, err := json.Marshal(labels)
if err != nil {
debugLogger.Error("Failed to marshal labels to JSON", "error", err)
return mcp.NewToolResultError("Failed to format labels response"), nil
}
debugLogger.Info("Successfully retrieved project labels", "count", len(labels), "project_path", projectPath)
return mcp.NewToolResultText(string(jsonData)), nil
}
}
// extractListLabelsOptions extracts list labels options from arguments.
func extractListLabelsOptions(args map[string]any) *app.ListLabelsOptions {
opts := &app.ListLabelsOptions{
Limit: defaultLimit, // default
}
if withCounts, ok := args["with_counts"].(bool); ok {
opts.WithCounts = &withCounts
}
if includeAncestorGroups, ok := args["include_ancestor_groups"].(bool); ok {
opts.IncludeAncestorGroups = &includeAncestorGroups
}
if search, ok := args["search"].(string); ok && search != "" {
opts.Search = search
}
if limitFloat, ok := args["limit"].(float64); ok {
opts.Limit = int64(limitFloat)
}
return opts
}
// setupListEpicsTool creates and registers the list_epics tool.
func setupListEpicsTool(s *server.MCPServer, appInstance *app.App, debugLogger *slog.Logger) {
listEpicsTool := mcp.NewTool("list_epics",
mcp.WithDescription("List epics for a GitLab group by group path. "+
"Note: Epics require GitLab Premium or Ultimate tier. "+
"Free/Starter tier instances will return a helpful error message."),
mcp.WithString("group_path",
mcp.Required(),
mcp.Description("GitLab group path (e.g., 'myorg' or 'parent/subgroup'). "+
"Groups contain multiple projects and use epics to organize work across projects."),
),
mcp.WithString("state",
mcp.Description("Filter by epic state: opened, closed, or all (default: opened)"),
),
mcp.WithNumber("limit",
mcp.Description("Maximum number of epics to return (default: 100, max: 100)"),
),
)
s.AddTool(listEpicsTool, handleListEpicsRequest(appInstance, debugLogger))
}
// handleListEpicsRequest handles the list_epics tool request.
func handleListEpicsRequest(
appInstance *app.App,
debugLogger *slog.Logger,
) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
debugLogger.Debug("Received list_epics tool request", "args", args)
// Extract group_path
groupPath, ok := args["group_path"].(string)
if !ok || groupPath == "" {
debugLogger.Error("group_path is not a valid string", "value", args["group_path"])
return mcp.NewToolResultError("group_path must be a non-empty string"), nil
}
// Extract optional parameters
opts := &app.ListEpicsOptions{
State: defaultStateOpened,
Limit: defaultLimit,
}
if state, ok := args["state"].(string); ok && state != "" {
opts.State = state
}
if limitFloat, ok := args["limit"].(float64); ok {
opts.Limit = int64(limitFloat)
}
debugLogger.Debug("Processing list_epics request", "group_path", groupPath, "opts", opts)
// Call the app method
epics, err := appInstance.ListGroupEpics(groupPath, opts)
if err != nil {
debugLogger.Error("Failed to list group epics", "error", err, "group_path", groupPath)
if errors.Is(err, app.ErrEpicsTierRequired) {
return mcp.NewToolResultError(fmt.Sprintf(
"Failed to list epics: %v\n\n"+
"Epics are a GitLab Premium/Ultimate feature. If you're on a Free tier, "+
"consider using issues for work tracking instead. "+
"See: https://docs.gitlab.com/ee/user/group/epics/",
err,
)), nil
}
return mcp.NewToolResultError(fmt.Sprintf("Failed to list group epics: %v", err)), nil
}
// Convert to JSON
jsonData, err := json.Marshal(epics)
if err != nil {
debugLogger.Error("Failed to marshal epics to JSON", "error", err)
return mcp.NewToolResultError("Failed to format epics response"), nil
}
debugLogger.Info("Successfully retrieved group epics", "count", len(epics), "group_path", groupPath)
return mcp.NewToolResultText(string(jsonData)), nil
}
}
// setupCreateEpicTool creates and registers the create_epic tool.
func setupCreateEpicTool(s *server.MCPServer, appInstance *app.App, debugLogger *slog.Logger) {
createEpicTool := mcp.NewTool("create_epic",
mcp.WithDescription("Create a new epic in a GitLab group. "+
"Note: Epics require GitLab Premium or Ultimate tier."),
mcp.WithString("group_path",
mcp.Required(),
mcp.Description("GitLab group path (e.g., 'myorg' or 'parent/subgroup')"),
),
mcp.WithString("title",
mcp.Required(),
mcp.Description("Epic title"),
),
mcp.WithString("description",
mcp.Description("Epic description (optional)"),
),
mcp.WithArray("labels",
mcp.Description("Array of label names (optional). Labels must exist in the group. "+
"Set GITLAB_VALIDATE_LABELS=false to disable validation."),
),
mcp.WithString("start_date",
mcp.Description("Start date in YYYY-MM-DD format (optional)"),
),
mcp.WithString("due_date",
mcp.Description("Due date in YYYY-MM-DD format (optional)"),
),
mcp.WithBoolean("confidential",
mcp.Description("Whether epic is confidential (default: false)"),
),
)
s.AddTool(createEpicTool, handleCreateEpicRequest(appInstance, debugLogger))
}
// setupUpdateEpicTool creates and registers the update_epic tool.
func setupUpdateEpicTool(s *server.MCPServer, appInstance *app.App, debugLogger *slog.Logger) {
updateEpicTool := mcp.NewTool("update_epic",
mcp.WithDescription("Update an existing epic in a GitLab group. "+
"Note: Epics require GitLab Premium or Ultimate tier."),
mcp.WithString("group_path",
mcp.Required(),
mcp.Description("GitLab group path (e.g., 'myorg' or 'parent/subgroup')"),
),
mcp.WithNumber("epic_iid",
mcp.Required(),
mcp.Description("Epic internal ID (IID) to update"),
),
mcp.WithString("title",
mcp.Description("Updated epic title (optional)"),
),
mcp.WithString("description",
mcp.Description("Updated epic description (optional)"),
),
mcp.WithArray("labels",
mcp.Description("Array of label names to set (optional). "+
"Labels must exist in the group. Set GITLAB_VALIDATE_LABELS=false to disable validation."),
),
mcp.WithString("start_date",
mcp.Description("Start date in YYYY-MM-DD format (optional)"),
),
mcp.WithString("due_date",
mcp.Description("Due date in YYYY-MM-DD format (optional)"),
),
mcp.WithString("state",
mcp.Description("Epic state: 'opened' or 'closed' (optional)"),
),
mcp.WithBoolean("confidential",
mcp.Description("Whether epic is confidential (optional)"),
),
)
s.AddTool(updateEpicTool, handleUpdateEpicRequest(appInstance, debugLogger))
}
// handleCreateEpicRequest handles the create_epic tool request.
func handleCreateEpicRequest(
appInstance *app.App,
debugLogger *slog.Logger,
) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
debugLogger.Debug("Received create_epic tool request", "args", args)
// Extract and validate parameters
groupPath, opts, validationErr := extractCreateEpicParams(args, debugLogger)
if validationErr != nil {
return validationErr, nil
}
debugLogger.Debug("Processing create_epic request", "group_path", groupPath, "opts", opts)
// Call the app method
epic, appErr := appInstance.CreateGroupEpic(groupPath, opts)
if appErr != nil {
return handleCreateEpicError(appErr, groupPath, debugLogger), nil
}
// Convert to JSON
jsonData, err := json.Marshal(epic)
if err != nil {
debugLogger.Error("Failed to marshal epic to JSON", "error", err)
return mcp.NewToolResultError("Failed to format epic response"), nil
}
debugLogger.Info("Successfully created epic", "id", epic.ID, "iid", epic.IID, "group_path", groupPath)
return mcp.NewToolResultText(string(jsonData)), nil
}
}
// handleUpdateEpicRequest handles the update_epic tool request.
func handleUpdateEpicRequest(
appInstance *app.App,
debugLogger *slog.Logger,
) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
debugLogger.Debug("Received update_epic tool request", "args", args)
// Extract and validate parameters
groupPath, epicIID, opts, validationErr := extractUpdateEpicParams(args, debugLogger)
if validationErr != nil {
return validationErr, nil
}
debugLogger.Debug("Processing update_epic request",
"group_path", groupPath, "epic_iid", epicIID, "opts", opts)
// Call the app method
epic, appErr := appInstance.UpdateGroupEpic(groupPath, epicIID, opts)
if appErr != nil {
debugLogger.Error("Failed to update epic", "error", appErr,
"group_path", groupPath, "epic_iid", epicIID)
if errors.Is(appErr, app.ErrEpicsTierRequired) {
return mcp.NewToolResultError(fmt.Sprintf(
"Failed to update epic: %v\n\n"+
"Epics are a GitLab Premium/Ultimate feature. "+
"See: https://docs.gitlab.com/ee/user/group/epics/",
appErr,
)), nil
}
return mcp.NewToolResultError(fmt.Sprintf("Failed to update epic: %v", appErr)), nil
}
// Convert to JSON
jsonData, err := json.Marshal(epic)
if err != nil {
debugLogger.Error("Failed to marshal epic to JSON", "error", err)
return mcp.NewToolResultError("Failed to format epic response"), nil
}
debugLogger.Info("Successfully updated epic",
"id", epic.ID, "iid", epic.IID, "group_path", groupPath)
return mcp.NewToolResultText(string(jsonData)), nil
}
}
// setupAddIssueToEpicTool creates and registers the add_issue_to_epic tool.
func setupAddIssueToEpicTool(s *server.MCPServer, appInstance *app.App, debugLogger *slog.Logger) {
addIssueToEpicTool := mcp.NewTool("add_issue_to_epic",
mcp.WithDescription("Attach an issue to an epic (Premium/Ultimate tier). "+
"Note: The Epics API is deprecated and will be removed in GitLab API v5. "+
"Consider using Work Items API for future implementations."),
mcp.WithString("group_path",
mcp.Required(),
mcp.Description("GitLab group path containing the epic (e.g., 'myorg' or 'parent/subgroup'). "+
"Run 'git remote -v' to find the full path from the repository URL"),
),
mcp.WithNumber("epic_iid",
mcp.Required(),
mcp.Description("Epic internal ID (IID) to attach the issue to"),
),
mcp.WithString("project_path",
mcp.Required(),
mcp.Description("GitLab project path containing the issue (e.g., 'namespace/project-name')"),
),
mcp.WithNumber("issue_iid",
mcp.Required(),
mcp.Description("Issue internal ID (IID) to attach to the epic"),
),
)
s.AddTool(addIssueToEpicTool, handleAddIssueToEpicRequest(appInstance, debugLogger))
}
// handleAddIssueToEpicRequest handles the add_issue_to_epic tool request.
func handleAddIssueToEpicRequest(
appInstance *app.App,
debugLogger *slog.Logger,
) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
debugLogger.Debug("Received add_issue_to_epic tool request", "args", args)
// Extract and validate parameters
opts, err := extractAddIssueToEpicParams(args)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
debugLogger.Debug("Processing add_issue_to_epic request", "opts", opts)
// Call the app method
epicIssue, err := appInstance.AddIssueToEpic(opts)
if err != nil {
if errors.Is(err, app.ErrEpicsTierRequired) {
return mcp.NewToolResultError(
"This feature requires GitLab Premium or Ultimate. " +
"See https://docs.gitlab.com/ee/user/group/epics/ for more information.",
), nil
}
return mcp.NewToolResultError(err.Error()), nil
}
// Convert to JSON
jsonData, err := json.Marshal(epicIssue)
if err != nil {
debugLogger.Error("Failed to marshal epic issue to JSON", "error", err)
return mcp.NewToolResultError("Failed to format epic issue response"), nil
}
debugLogger.Info("Successfully added issue to epic",
"issue_id", epicIssue.ID, "issue_iid", epicIssue.IID, "epic_iid", epicIssue.EpicIID)
return mcp.NewToolResultText(string(jsonData)), nil
}
}
// setupGetLatestPipelineTool creates and registers the get_latest_pipeline tool.
func setupGetLatestPipelineTool(s *server.MCPServer, appInstance *app.App, debugLogger *slog.Logger) {
getLatestPipelineTool := mcp.NewTool("get_latest_pipeline",
mcp.WithDescription("Get the latest pipeline for a GitLab project by project path. "+
"Returns the most recently updated pipeline, optionally filtered by branch/tag."),
mcp.WithString("project_path",
mcp.Required(),
mcp.Description("GitLab project path including all namespaces (e.g., 'namespace/project-name' or "+
"'company/department/team/project'). Run 'git remote -v' to find the full path from the repository URL"),
),
mcp.WithString("ref",
mcp.Description("Optional: filter by branch or tag name (e.g., 'main', 'develop', 'v1.0.0')"),
),
)
s.AddTool(getLatestPipelineTool, handleGetLatestPipelineRequest(appInstance, debugLogger))
}
// handleGetLatestPipelineRequest handles the get_latest_pipeline tool request.
func handleGetLatestPipelineRequest(
appInstance *app.App,
debugLogger *slog.Logger,
) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
debugLogger.Debug("Received get_latest_pipeline tool request", "args", args)
// Extract project_path
projectPath, ok := args["project_path"].(string)
if !ok || projectPath == "" {
debugLogger.Error("project_path is not a valid string", "value", args["project_path"])
return mcp.NewToolResultError("project_path must be a non-empty string"), nil
}
// Extract optional parameters
opts := &app.GetLatestPipelineOptions{}
if ref, ok := args["ref"].(string); ok && ref != "" {
opts.Ref = ref
}
debugLogger.Debug("Processing get_latest_pipeline request", "project_path", projectPath, "opts", opts)
// Call the app method
pipeline, err := appInstance.GetLatestPipeline(projectPath, opts)
if err != nil {
debugLogger.Error("Failed to get latest pipeline", "error", err, "project_path", projectPath)
return mcp.NewToolResultError(fmt.Sprintf("Failed to get latest pipeline: %v", err)), nil
}
// Convert pipeline to JSON
jsonData, err := json.Marshal(pipeline)
if err != nil {
debugLogger.Error("Failed to marshal pipeline to JSON", "error", err)
return mcp.NewToolResultError("Failed to format pipeline response"), nil
}
debugLogger.Info("Successfully retrieved latest pipeline",
"pipeline_id", pipeline.ID,
"status", pipeline.Status,
"project_path", projectPath)
return mcp.NewToolResultText(string(jsonData)), nil
}
}
// setupListPipelineJobsTool creates and registers the list_pipeline_jobs tool.
func setupListPipelineJobsTool(s *server.MCPServer, appInstance *app.App, debugLogger *slog.Logger) {
listPipelineJobsTool := mcp.NewTool("list_pipeline_jobs",
mcp.WithDescription("List all jobs for a GitLab pipeline with filtering options. "+
"If pipeline_id is not provided, retrieves jobs from the latest pipeline. "+
"Useful for debugging CI/CD failures and analyzing pipeline execution."),
mcp.WithString("project_path",
mcp.Required(),
mcp.Description("GitLab project path including all namespaces (e.g., 'namespace/project-name')"),
),
mcp.WithNumber("pipeline_id",
mcp.Description("Optional: specific pipeline ID. If not provided, uses the latest pipeline."),
),
mcp.WithString("ref",
mcp.Description("Optional: branch or tag name for finding the latest pipeline (e.g., 'main', 'develop'). "+
"Only used when pipeline_id is not provided."),
),
mcp.WithArray("scope",
mcp.Description("Optional: filter jobs by status. Can include: 'created', 'pending', 'running', "+
"'success', 'failed', 'canceled', 'skipped', 'manual', 'scheduled'. "+
"Example: ['failed', 'canceled'] to show only failed and canceled jobs."),
),
mcp.WithString("stage",
mcp.Description("Optional: filter jobs by stage name (e.g., 'build', 'test', 'deploy'). Case-sensitive."),
),
)
s.AddTool(listPipelineJobsTool, handleListPipelineJobsRequest(appInstance, debugLogger))
}
// handleListPipelineJobsRequest handles the list_pipeline_jobs tool request.
func handleListPipelineJobsRequest(
appInstance *app.App,
debugLogger *slog.Logger,
) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args := request.GetArguments()
debugLogger.Debug("Received list_pipeline_jobs tool request", "args", args)
projectPath, ok := args["project_path"].(string)
if !ok || projectPath == "" {
debugLogger.Error("project_path is not a valid string", "value", args["project_path"])
return mcp.NewToolResultError("project_path must be a non-empty string"), nil
}
opts, err := extractListPipelineJobsOptions(args, debugLogger)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
debugLogger.Debug("Processing list_pipeline_jobs request", "project_path", projectPath, "opts", opts)
jobs, err := appInstance.ListPipelineJobs(projectPath, opts)
if err != nil {
debugLogger.Error("Failed to list pipeline jobs", "error", err, "project_path", projectPath)
return mcp.NewToolResultError(fmt.Sprintf("Failed to list pipeline jobs: %v", err)), nil
}
jsonData, err := json.Marshal(jobs)
if err != nil {
debugLogger.Error("Failed to marshal jobs to JSON", "error", err)
return mcp.NewToolResultError("Failed to format jobs response"), nil
}
debugLogger.Info("Successfully retrieved pipeline jobs", "count", len(jobs), "project_path", projectPath)
return mcp.NewToolResultText(string(jsonData)), nil
}
}
// extractListPipelineJobsOptions extracts and validates options from MCP request arguments.
//
//nolint:cyclop // Option extraction and validation requires multiple branches
func extractListPipelineJobsOptions(
args map[string]any,
debugLogger *slog.Logger,
) (*app.ListPipelineJobsOptions, error) {
opts := &app.ListPipelineJobsOptions{}
if pipelineIDFloat, ok := args["pipeline_id"].(float64); ok {
pipelineID := int64(pipelineIDFloat)
opts.PipelineID = &pipelineID
}
if ref, ok := args["ref"].(string); ok && ref != "" {
opts.Ref = ref
}
if scopeInterface, ok := args["scope"].([]any); ok && len(scopeInterface) > 0 {
scopes := make([]string, 0, len(scopeInterface))
for _, s := range scopeInterface {
if statusStr, ok := s.(string); ok {
if !isValidJobStatus(statusStr) {
debugLogger.Warn("Invalid job status in scope", "status", statusStr)
return nil, fmt.Errorf(
"%w: '%s'. Valid: created, pending, running, success, failed, canceled, skipped, manual, scheduled",
ErrInvalidJobStatus, statusStr,
)
}
scopes = append(scopes, statusStr)
}
}
opts.Scope = scopes
}
if stage, ok := args["stage"].(string); ok && stage != "" {
opts.Stage = stage
}
return opts, nil
}
// isValidJobStatus checks if a job status is valid.
func isValidJobStatus(status string) bool {
validStatuses := map[string]bool{
"created": true, "waiting_for_resource": true, "preparing": true,
"pending": true, "running": true, "success": true,
"failed": true, "canceled": true, "skipped": true,
"manual": true, "scheduled": true,
}
return validStatuses[status]
}
// setupGetJobLogTool creates and registers the get_job_log tool.
func setupGetJobLogTool(s *server.MCPServer, appInstance *app.App, debugLogger *slog.Logger) {
getJobLogTool := mcp.NewTool("get_job_log",
mcp.WithDescription("Retrieve complete log output for a specific GitLab CI/CD job. "+
"Returns job metadata along with the full trace/log content. "+
"Useful for debugging job failures and analyzing execution details."),
mcp.WithString("project_path",
mcp.Required(),
mcp.Description("GitLab project path including all namespaces (e.g., 'namespace/project-name')"),