-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathprojects.go
More file actions
1477 lines (1306 loc) · 48.8 KB
/
projects.go
File metadata and controls
1477 lines (1306 loc) · 48.8 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 github
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
ghErrors "github.com/github/github-mcp-server/pkg/errors"
"github.com/github/github-mcp-server/pkg/inventory"
"github.com/github/github-mcp-server/pkg/scopes"
"github.com/github/github-mcp-server/pkg/translations"
"github.com/github/github-mcp-server/pkg/utils"
"github.com/google/go-github/v82/github"
"github.com/google/jsonschema-go/jsonschema"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/shurcooL/githubv4"
)
const (
ProjectUpdateFailedError = "failed to update a project item"
ProjectAddFailedError = "failed to add a project item"
ProjectDeleteFailedError = "failed to delete a project item"
ProjectListFailedError = "failed to list project items"
ProjectStatusUpdateListFailedError = "failed to list project status updates"
ProjectStatusUpdateGetFailedError = "failed to get project status update"
ProjectStatusUpdateCreateFailedError = "failed to create project status update"
ProjectResolveIDFailedError = "failed to resolve project ID"
MaxProjectsPerPage = 50
)
// Method constants for consolidated project tools
const (
projectsMethodListProjects = "list_projects"
projectsMethodListProjectFields = "list_project_fields"
projectsMethodListProjectItems = "list_project_items"
projectsMethodGetProject = "get_project"
projectsMethodGetProjectField = "get_project_field"
projectsMethodGetProjectItem = "get_project_item"
projectsMethodAddProjectItem = "add_project_item"
projectsMethodUpdateProjectItem = "update_project_item"
projectsMethodDeleteProjectItem = "delete_project_item"
projectsMethodListProjectStatusUpdates = "list_project_status_updates"
projectsMethodGetProjectStatusUpdate = "get_project_status_update"
projectsMethodCreateProjectStatusUpdate = "create_project_status_update"
)
// GraphQL types for ProjectV2 status updates
type statusUpdateNode struct {
ID githubv4.ID
Body *githubv4.String
Status *githubv4.String
CreatedAt githubv4.DateTime
StartDate *githubv4.String
TargetDate *githubv4.String
Creator struct {
Login githubv4.String
}
}
type statusUpdateConnection struct {
Nodes []statusUpdateNode
PageInfo PageInfoFragment
}
// statusUpdatesUserQuery is the GraphQL query for listing status updates on a user-owned project.
type statusUpdatesUserQuery struct {
User struct {
ProjectV2 struct {
StatusUpdates statusUpdateConnection `graphql:"statusUpdates(first: $first, after: $after, orderBy: {field: CREATED_AT, direction: DESC})"`
} `graphql:"projectV2(number: $projectNumber)"`
} `graphql:"user(login: $owner)"`
}
// statusUpdatesOrgQuery is the GraphQL query for listing status updates on an org-owned project.
type statusUpdatesOrgQuery struct {
Organization struct {
ProjectV2 struct {
StatusUpdates statusUpdateConnection `graphql:"statusUpdates(first: $first, after: $after, orderBy: {field: CREATED_AT, direction: DESC})"`
} `graphql:"projectV2(number: $projectNumber)"`
} `graphql:"organization(login: $owner)"`
}
// statusUpdateNodeQuery is the GraphQL query for fetching a single status update by node ID.
type statusUpdateNodeQuery struct {
Node struct {
StatusUpdate statusUpdateNode `graphql:"... on ProjectV2StatusUpdate"`
} `graphql:"node(id: $id)"`
}
// CreateProjectV2StatusUpdateInput is the input for the createProjectV2StatusUpdate mutation.
// Defined locally because the shurcooL/githubv4 library does not include this type.
type CreateProjectV2StatusUpdateInput struct {
ProjectID githubv4.ID `json:"projectId"`
Body *githubv4.String `json:"body,omitempty"`
Status *githubv4.String `json:"status,omitempty"`
StartDate *githubv4.String `json:"startDate,omitempty"`
TargetDate *githubv4.String `json:"targetDate,omitempty"`
ClientMutationID *githubv4.String `json:"clientMutationId,omitempty"`
}
// validProjectV2StatusUpdateStatuses is the set of valid status values for the createProjectV2StatusUpdate mutation.
var validProjectV2StatusUpdateStatuses = map[string]bool{
"INACTIVE": true,
"ON_TRACK": true,
"AT_RISK": true,
"OFF_TRACK": true,
"COMPLETE": true,
}
func convertToMinimalStatusUpdate(node statusUpdateNode) MinimalProjectStatusUpdate {
var creator *MinimalUser
if login := string(node.Creator.Login); login != "" {
creator = &MinimalUser{Login: login}
}
return MinimalProjectStatusUpdate{
ID: fmt.Sprintf("%v", node.ID),
Body: derefString(node.Body),
Status: derefString(node.Status),
CreatedAt: node.CreatedAt.Time.Format(time.RFC3339),
StartDate: derefString(node.StartDate),
TargetDate: derefString(node.TargetDate),
Creator: creator,
}
}
func derefString(s *githubv4.String) string {
if s == nil {
return ""
}
return string(*s)
}
// ProjectsList returns the tool and handler for listing GitHub Projects resources.
func ProjectsList(t translations.TranslationHelperFunc) inventory.ServerTool {
tool := NewTool(
ToolsetMetadataProjects,
mcp.Tool{
Name: "projects_list",
Description: t("TOOL_PROJECTS_LIST_DESCRIPTION",
`Tools for listing GitHub Projects resources.
Use this tool to list projects for a user or organization, or list project fields and items for a specific project.
`),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_PROJECTS_LIST_USER_TITLE", "List GitHub Projects resources"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"method": {
Type: "string",
Description: "The action to perform",
Enum: []any{
projectsMethodListProjects,
projectsMethodListProjectFields,
projectsMethodListProjectItems,
projectsMethodListProjectStatusUpdates,
},
},
"owner_type": {
Type: "string",
Description: "Owner type (user or org). If not provided, will automatically try both.",
Enum: []any{"user", "org"},
},
"owner": {
Type: "string",
Description: "The owner (user or organization login). The name is not case sensitive.",
},
"project_number": {
Type: "number",
Description: "The project's number. Required for 'list_project_fields', 'list_project_items', and 'list_project_status_updates' methods.",
},
"query": {
Type: "string",
Description: `Filter/query string. For list_projects: filter by title text and state (e.g. "roadmap is:open"). For list_project_items: advanced filtering using GitHub's project filtering syntax.`,
},
"fields": {
Type: "array",
Description: "Field IDs to include when listing project items (e.g. [\"102589\", \"985201\"]). CRITICAL: Always provide to get field values. Without this, only titles returned. Only used for 'list_project_items' method.",
Items: &jsonschema.Schema{
Type: "string",
},
},
"per_page": {
Type: "number",
Description: fmt.Sprintf("Results per page (max %d)", MaxProjectsPerPage),
},
"after": {
Type: "string",
Description: "Forward pagination cursor from previous pageInfo.nextCursor.",
},
"before": {
Type: "string",
Description: "Backward pagination cursor from previous pageInfo.prevCursor (rare).",
},
},
Required: []string{"method", "owner"},
},
},
[]scopes.Scope{scopes.ReadProject},
func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
method, err := RequiredParam[string](args, "method")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err := OptionalParam[string](args, "owner_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
switch method {
case projectsMethodListProjects:
return listProjects(ctx, client, args, owner, ownerType)
default:
// All other methods require project_number and ownerType detection
if ownerType == "" {
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err = detectOwnerType(ctx, client, owner, projectNumber)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
}
switch method {
case projectsMethodListProjectFields:
return listProjectFields(ctx, client, args, owner, ownerType)
case projectsMethodListProjectItems:
return listProjectItems(ctx, client, args, owner, ownerType)
case projectsMethodListProjectStatusUpdates:
gqlClient, err := deps.GetGQLClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
return listProjectStatusUpdates(ctx, gqlClient, args, owner, ownerType)
default:
return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", method)), nil, nil
}
}
},
)
return tool
}
// ProjectsGet returns the tool and handler for getting GitHub Projects resources.
func ProjectsGet(t translations.TranslationHelperFunc) inventory.ServerTool {
tool := NewTool(
ToolsetMetadataProjects,
mcp.Tool{
Name: "projects_get",
Description: t("TOOL_PROJECTS_GET_DESCRIPTION", `Get details about specific GitHub Projects resources.
Use this tool to get details about individual projects, project fields, and project items by their unique IDs.
`),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_PROJECTS_GET_USER_TITLE", "Get details of GitHub Projects resources"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"method": {
Type: "string",
Description: "The method to execute",
Enum: []any{
projectsMethodGetProject,
projectsMethodGetProjectField,
projectsMethodGetProjectItem,
projectsMethodGetProjectStatusUpdate,
},
},
"owner_type": {
Type: "string",
Description: "Owner type (user or org). If not provided, will be automatically detected.",
Enum: []any{"user", "org"},
},
"owner": {
Type: "string",
Description: "The owner (user or organization login). The name is not case sensitive.",
},
"project_number": {
Type: "number",
Description: "The project's number.",
},
"field_id": {
Type: "number",
Description: "The field's ID. Required for 'get_project_field' method.",
},
"item_id": {
Type: "number",
Description: "The item's ID. Required for 'get_project_item' method.",
},
"fields": {
Type: "array",
Description: "Specific list of field IDs to include in the response when getting a project item (e.g. [\"102589\", \"985201\", \"169875\"]). If not provided, only the title field is included. Only used for 'get_project_item' method.",
Items: &jsonschema.Schema{
Type: "string",
},
},
"status_update_id": {
Type: "string",
Description: "The node ID of the project status update. Required for 'get_project_status_update' method.",
},
},
Required: []string{"method"},
},
},
[]scopes.Scope{scopes.ReadProject},
func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
method, err := RequiredParam[string](args, "method")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Handle get_project_status_update early — it only needs status_update_id
if method == projectsMethodGetProjectStatusUpdate {
statusUpdateID, err := RequiredParam[string](args, "status_update_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
gqlClient, err := deps.GetGQLClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
return getProjectStatusUpdate(ctx, gqlClient, statusUpdateID)
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err := OptionalParam[string](args, "owner_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Detect owner type if not provided
if ownerType == "" {
ownerType, err = detectOwnerType(ctx, client, owner, projectNumber)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
}
switch method {
case projectsMethodGetProject:
return getProject(ctx, client, owner, ownerType, projectNumber)
case projectsMethodGetProjectField:
fieldID, err := RequiredBigInt(args, "field_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
return getProjectField(ctx, client, owner, ownerType, projectNumber, fieldID)
case projectsMethodGetProjectItem:
itemID, err := RequiredBigInt(args, "item_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
fields, err := OptionalBigIntArrayParam(args, "fields")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
return getProjectItem(ctx, client, owner, ownerType, projectNumber, itemID, fields)
default:
return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", method)), nil, nil
}
},
)
return tool
}
// ProjectsWrite returns the tool and handler for modifying GitHub Projects resources.
func ProjectsWrite(t translations.TranslationHelperFunc) inventory.ServerTool {
tool := NewTool(
ToolsetMetadataProjects,
mcp.Tool{
Name: "projects_write",
Description: t("TOOL_PROJECTS_WRITE_DESCRIPTION", "Add, update, or delete project items, or create status updates in a GitHub Project."),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_PROJECTS_WRITE_USER_TITLE", "Modify GitHub Project items"),
ReadOnlyHint: false,
DestructiveHint: jsonschema.Ptr(true),
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"method": {
Type: "string",
Description: "The method to execute",
Enum: []any{
projectsMethodAddProjectItem,
projectsMethodUpdateProjectItem,
projectsMethodDeleteProjectItem,
projectsMethodCreateProjectStatusUpdate,
},
},
"owner_type": {
Type: "string",
Description: "Owner type (user or org). If not provided, will be automatically detected.",
Enum: []any{"user", "org"},
},
"owner": {
Type: "string",
Description: "The project owner (user or organization login). The name is not case sensitive.",
},
"project_number": {
Type: "number",
Description: "The project's number.",
},
"item_id": {
Type: "number",
Description: "The project item ID. Required for 'update_project_item' and 'delete_project_item' methods.",
},
"item_type": {
Type: "string",
Description: "The item's type, either issue or pull_request. Required for 'add_project_item' method.",
Enum: []any{"issue", "pull_request"},
},
"item_owner": {
Type: "string",
Description: "The owner (user or organization) of the repository containing the issue or pull request. Required for 'add_project_item' method.",
},
"item_repo": {
Type: "string",
Description: "The name of the repository containing the issue or pull request. Required for 'add_project_item' method.",
},
"issue_number": {
Type: "number",
Description: "The issue number (use when item_type is 'issue' for 'add_project_item' method). Provide either issue_number or pull_request_number.",
},
"pull_request_number": {
Type: "number",
Description: "The pull request number (use when item_type is 'pull_request' for 'add_project_item' method). Provide either issue_number or pull_request_number.",
},
"updated_field": {
Type: "object",
Description: "Object consisting of the ID of the project field to update and the new value for the field. To clear the field, set value to null. Example: {\"id\": 123456, \"value\": \"New Value\"}. Required for 'update_project_item' method.",
},
"body": {
Type: "string",
Description: "The body of the status update (markdown). Used for 'create_project_status_update' method.",
},
"status": {
Type: "string",
Description: "The status of the project. Used for 'create_project_status_update' method.",
Enum: []any{"INACTIVE", "ON_TRACK", "AT_RISK", "OFF_TRACK", "COMPLETE"},
},
"start_date": {
Type: "string",
Description: "The start date of the status update in YYYY-MM-DD format. Used for 'create_project_status_update' method.",
},
"target_date": {
Type: "string",
Description: "The target date of the status update in YYYY-MM-DD format. Used for 'create_project_status_update' method.",
},
},
Required: []string{"method", "owner", "project_number"},
},
},
[]scopes.Scope{scopes.Project},
func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
method, err := RequiredParam[string](args, "method")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err := OptionalParam[string](args, "owner_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
gqlClient, err := deps.GetGQLClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Detect owner type if not provided
if ownerType == "" {
ownerType, err = detectOwnerType(ctx, client, owner, projectNumber)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
}
switch method {
case projectsMethodAddProjectItem:
itemType, err := RequiredParam[string](args, "item_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
itemOwner, err := RequiredParam[string](args, "item_owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
itemRepo, err := RequiredParam[string](args, "item_repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var itemNumber int
switch itemType {
case "issue":
itemNumber, err = RequiredInt(args, "issue_number")
if err != nil {
return utils.NewToolResultError("issue_number is required when item_type is 'issue'"), nil, nil
}
case "pull_request":
itemNumber, err = RequiredInt(args, "pull_request_number")
if err != nil {
return utils.NewToolResultError("pull_request_number is required when item_type is 'pull_request'"), nil, nil
}
default:
return utils.NewToolResultError("item_type must be either 'issue' or 'pull_request'"), nil, nil
}
return addProjectItem(ctx, gqlClient, owner, ownerType, projectNumber, itemOwner, itemRepo, itemNumber, itemType)
case projectsMethodUpdateProjectItem:
itemID, err := RequiredBigInt(args, "item_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
rawUpdatedField, exists := args["updated_field"]
if !exists {
return utils.NewToolResultError("missing required parameter: updated_field"), nil, nil
}
fieldValue, ok := rawUpdatedField.(map[string]any)
if !ok || fieldValue == nil {
return utils.NewToolResultError("updated_field must be an object"), nil, nil
}
return updateProjectItem(ctx, client, owner, ownerType, projectNumber, itemID, fieldValue)
case projectsMethodDeleteProjectItem:
itemID, err := RequiredBigInt(args, "item_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
return deleteProjectItem(ctx, client, owner, ownerType, projectNumber, itemID)
case projectsMethodCreateProjectStatusUpdate:
body, err := OptionalParam[string](args, "body")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
status, err := OptionalParam[string](args, "status")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
startDate, err := OptionalParam[string](args, "start_date")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
targetDate, err := OptionalParam[string](args, "target_date")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
return createProjectStatusUpdate(ctx, gqlClient, owner, ownerType, projectNumber, body, status, startDate, targetDate)
default:
return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", method)), nil, nil
}
},
)
return tool
}
// Helper functions for consolidated projects tools
func listProjects(ctx context.Context, client *github.Client, args map[string]any, owner, ownerType string) (*mcp.CallToolResult, any, error) {
queryStr, err := OptionalParam[string](args, "query")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
pagination, err := extractPaginationOptionsFromArgs(args)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var resp *github.Response
var projects []*github.ProjectV2
var queryPtr *string
if queryStr != "" {
queryPtr = &queryStr
}
minimalProjects := []MinimalProject{}
opts := &github.ListProjectsOptions{
ListProjectsPaginationOptions: pagination,
Query: queryPtr,
}
// If owner_type not provided, fetch from both user and org
switch ownerType {
case "":
return listProjectsFromBothOwnerTypes(ctx, client, owner, opts)
case "org":
projects, resp, err = client.Projects.ListOrganizationProjects(ctx, owner, opts)
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to list projects",
resp,
err,
), nil, nil
}
default:
projects, resp, err = client.Projects.ListUserProjects(ctx, owner, opts)
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to list projects",
resp,
err,
), nil, nil
}
}
// For specified owner_type, process normally
if ownerType != "" {
defer func() { _ = resp.Body.Close() }()
for _, project := range projects {
mp := convertToMinimalProject(project)
mp.OwnerType = ownerType
minimalProjects = append(minimalProjects, *mp)
}
response := map[string]any{
"projects": minimalProjects,
"pageInfo": buildPageInfo(resp),
}
r, err := json.Marshal(response)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
return nil, nil, fmt.Errorf("unexpected state in listProjects")
}
// listProjectsFromBothOwnerTypes fetches projects from both user and org endpoints
// when owner_type is not specified, combining the results with owner_type labels.
func listProjectsFromBothOwnerTypes(ctx context.Context, client *github.Client, owner string, opts *github.ListProjectsOptions) (*mcp.CallToolResult, any, error) {
var minimalProjects []MinimalProject
var resp *github.Response
// Fetch user projects
userProjects, userResp, userErr := client.Projects.ListUserProjects(ctx, owner, opts)
if userErr == nil && userResp.StatusCode == http.StatusOK {
for _, project := range userProjects {
mp := convertToMinimalProject(project)
mp.OwnerType = "user"
minimalProjects = append(minimalProjects, *mp)
}
_ = userResp.Body.Close()
}
// Fetch org projects
orgProjects, orgResp, orgErr := client.Projects.ListOrganizationProjects(ctx, owner, opts)
if orgErr == nil && orgResp.StatusCode == http.StatusOK {
for _, project := range orgProjects {
mp := convertToMinimalProject(project)
mp.OwnerType = "org"
minimalProjects = append(minimalProjects, *mp)
}
resp = orgResp // Use org response for pagination info
} else if userResp != nil {
resp = userResp // Fallback to user response
}
// If both failed, return error
if (userErr != nil || userResp == nil || userResp.StatusCode != http.StatusOK) &&
(orgErr != nil || orgResp == nil || orgResp.StatusCode != http.StatusOK) {
return utils.NewToolResultError(fmt.Sprintf("failed to list projects for owner '%s': not found as user or organization", owner)), nil, nil
}
response := map[string]any{
"projects": minimalProjects,
"note": "Results include both user and org projects. Each project includes 'owner_type' field. Pagination is limited when owner_type is not specified - specify 'owner_type' for full pagination support.",
}
if resp != nil {
response["pageInfo"] = buildPageInfo(resp)
defer func() { _ = resp.Body.Close() }()
}
r, err := json.Marshal(response)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
func listProjectFields(ctx context.Context, client *github.Client, args map[string]any, owner, ownerType string) (*mcp.CallToolResult, any, error) {
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
pagination, err := extractPaginationOptionsFromArgs(args)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var resp *github.Response
var projectFields []*github.ProjectV2Field
opts := &github.ListProjectsOptions{
ListProjectsPaginationOptions: pagination,
}
if ownerType == "org" {
projectFields, resp, err = client.Projects.ListOrganizationProjectFields(ctx, owner, projectNumber, opts)
} else {
projectFields, resp, err = client.Projects.ListUserProjectFields(ctx, owner, projectNumber, opts)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to list project fields",
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
response := map[string]any{
"fields": projectFields,
"pageInfo": buildPageInfo(resp),
}
r, err := json.Marshal(response)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
func listProjectItems(ctx context.Context, client *github.Client, args map[string]any, owner, ownerType string) (*mcp.CallToolResult, any, error) {
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
queryStr, err := OptionalParam[string](args, "query")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
fields, err := OptionalBigIntArrayParam(args, "fields")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
pagination, err := extractPaginationOptionsFromArgs(args)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var resp *github.Response
var projectItems []*github.ProjectV2Item
var queryPtr *string
if queryStr != "" {
queryPtr = &queryStr
}
opts := &github.ListProjectItemsOptions{
Fields: fields,
ListProjectsOptions: github.ListProjectsOptions{
ListProjectsPaginationOptions: pagination,
Query: queryPtr,
},
}
if ownerType == "org" {
projectItems, resp, err = client.Projects.ListOrganizationProjectItems(ctx, owner, projectNumber, opts)
} else {
projectItems, resp, err = client.Projects.ListUserProjectItems(ctx, owner, projectNumber, opts)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
ProjectListFailedError,
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
response := map[string]any{
"items": projectItems,
"pageInfo": buildPageInfo(resp),
}
r, err := json.Marshal(response)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
func getProject(ctx context.Context, client *github.Client, owner, ownerType string, projectNumber int) (*mcp.CallToolResult, any, error) {
var resp *github.Response
var project *github.ProjectV2
var err error
if ownerType == "org" {
project, resp, err = client.Projects.GetOrganizationProject(ctx, owner, projectNumber)
} else {
project, resp, err = client.Projects.GetUserProject(ctx, owner, projectNumber)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to get project",
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("failed to read response body: %w", err)
}
return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get project", resp, body), nil, nil
}
minimalProject := convertToMinimalProject(project)
r, err := json.Marshal(minimalProject)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
func getProjectField(ctx context.Context, client *github.Client, owner, ownerType string, projectNumber int, fieldID int64) (*mcp.CallToolResult, any, error) {
var resp *github.Response
var projectField *github.ProjectV2Field
var err error
if ownerType == "org" {
projectField, resp, err = client.Projects.GetOrganizationProjectField(ctx, owner, projectNumber, fieldID)
} else {
projectField, resp, err = client.Projects.GetUserProjectField(ctx, owner, projectNumber, fieldID)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to get project field",
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("failed to read response body: %w", err)
}
return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get project field", resp, body), nil, nil
}
r, err := json.Marshal(projectField)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
func getProjectItem(ctx context.Context, client *github.Client, owner, ownerType string, projectNumber int, itemID int64, fields []int64) (*mcp.CallToolResult, any, error) {
var resp *github.Response
var projectItem *github.ProjectV2Item
var opts *github.GetProjectItemOptions
var err error
if len(fields) > 0 {
opts = &github.GetProjectItemOptions{
Fields: fields,
}
}
if ownerType == "org" {
projectItem, resp, err = client.Projects.GetOrganizationProjectItem(ctx, owner, projectNumber, itemID, opts)
} else {
projectItem, resp, err = client.Projects.GetUserProjectItem(ctx, owner, projectNumber, itemID, opts)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to get project item",
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("failed to read response body: %w", err)
}
return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get project item", resp, body), nil, nil
}
r, err := json.Marshal(projectItem)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
func updateProjectItem(ctx context.Context, client *github.Client, owner, ownerType string, projectNumber int, itemID int64, fieldValue map[string]any) (*mcp.CallToolResult, any, error) {
updatePayload, err := buildUpdateProjectItem(fieldValue)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var resp *github.Response
var updatedItem *github.ProjectV2Item
if ownerType == "org" {
updatedItem, resp, err = client.Projects.UpdateOrganizationProjectItem(ctx, owner, projectNumber, itemID, updatePayload)
} else {
updatedItem, resp, err = client.Projects.UpdateUserProjectItem(ctx, owner, projectNumber, itemID, updatePayload)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
ProjectUpdateFailedError,
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("failed to read response body: %w", err)
}
return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, ProjectUpdateFailedError, resp, body), nil, nil
}
r, err := json.Marshal(updatedItem)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
func deleteProjectItem(ctx context.Context, client *github.Client, owner, ownerType string, projectNumber int, itemID int64) (*mcp.CallToolResult, any, error) {
var resp *github.Response