forked from github/github-mcp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathissues_test.go
More file actions
5267 lines (4877 loc) · 182 KB
/
Copy pathissues_test.go
File metadata and controls
5267 lines (4877 loc) · 182 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 (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/github/github-mcp-server/internal/githubv4mock"
"github.com/github/github-mcp-server/internal/toolsnaps"
"github.com/github/github-mcp-server/pkg/http/headers"
transportpkg "github.com/github/github-mcp-server/pkg/http/transport"
"github.com/github/github-mcp-server/pkg/inventory"
"github.com/github/github-mcp-server/pkg/translations"
"github.com/google/go-github/v89/github"
"github.com/google/jsonschema-go/jsonschema"
"github.com/shurcooL/githubv4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var defaultGQLClient *githubv4.Client = githubv4.NewClient(newRepoAccessHTTPClient())
type repoAccessKey struct {
owner string
repo string
}
type repoAccessValue struct {
isPrivate bool
}
type repoAccessMockTransport struct {
responses map[repoAccessKey]repoAccessValue
}
func newRepoAccessHTTPClient() *http.Client {
responses := map[repoAccessKey]repoAccessValue{
{owner: "owner2", repo: "repo2"}: {isPrivate: true},
{owner: "owner", repo: "repo"}: {isPrivate: false},
}
return &http.Client{Transport: &repoAccessMockTransport{responses: responses}}
}
const issueReadEnrichmentQueryString = "query($ids:[ID!]!){nodes(ids: $ids){... on Issue{id,issueFieldValues(first: 25){nodes{__typename,... on IssueFieldDateValue{field{... on IssueFieldDate{name,fullDatabaseId},... on IssueFieldNumber{name,fullDatabaseId},... on IssueFieldSingleSelect{name,fullDatabaseId},... on IssueFieldText{name,fullDatabaseId}},value},... on IssueFieldNumberValue{field{... on IssueFieldDate{name,fullDatabaseId},... on IssueFieldNumber{name,fullDatabaseId},... on IssueFieldSingleSelect{name,fullDatabaseId},... on IssueFieldText{name,fullDatabaseId}},valueNumber: value},... on IssueFieldSingleSelectValue{field{... on IssueFieldDate{name,fullDatabaseId},... on IssueFieldNumber{name,fullDatabaseId},... on IssueFieldSingleSelect{name,fullDatabaseId},... on IssueFieldText{name,fullDatabaseId}},value},... on IssueFieldTextValue{field{... on IssueFieldDate{name,fullDatabaseId},... on IssueFieldNumber{name,fullDatabaseId},... on IssueFieldSingleSelect{name,fullDatabaseId},... on IssueFieldText{name,fullDatabaseId}},value}}},parent{number,title,state,url,author{login},repository{nameWithOwner}},subIssuesSummary{total,completed,percentCompleted}}}}"
// newIssueReadEnrichmentMatcher builds a matcher for the issue_read `get` enrichment query for a
// single issue node ID.
func newIssueReadEnrichmentMatcher(nodeID string, response githubv4mock.GQLResponse) githubv4mock.Matcher {
return githubv4mock.NewQueryMatcher(
issueReadEnrichmentQueryString,
map[string]any{"ids": []any{nodeID}},
response,
)
}
func (rt *repoAccessMockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if req.Body == nil {
return nil, fmt.Errorf("missing request body")
}
var payload struct {
Query string `json:"query"`
Variables map[string]any `json:"variables"`
}
if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
return nil, err
}
_ = req.Body.Close()
owner := toString(payload.Variables["owner"])
repo := toString(payload.Variables["name"])
value, ok := rt.responses[repoAccessKey{owner: owner, repo: repo}]
if !ok {
value = repoAccessValue{isPrivate: false}
}
data := map[string]any{}
if strings.Contains(payload.Query, "viewer") {
data["viewer"] = map[string]any{"login": "test-viewer"}
}
if strings.Contains(payload.Query, "repository") {
data["repository"] = map[string]any{"isPrivate": value.isPrivate}
}
responseBody, err := json.Marshal(map[string]any{"data": data})
if err != nil {
return nil, err
}
resp := &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(bytes.NewReader(responseBody)),
}
resp.Header.Set("Content-Type", "application/json")
return resp, nil
}
func toString(v any) string {
switch value := v.(type) {
case string:
return value
case fmt.Stringer:
return value.String()
case nil:
return ""
default:
return fmt.Sprintf("%v", value)
}
}
func Test_GetIssue(t *testing.T) {
// Verify tool definition once
serverTool := IssueRead(translations.NullTranslationHelper)
tool := serverTool.Tool
require.NoError(t, toolsnaps.Test(tool.Name, tool))
assert.Equal(t, "issue_read", tool.Name)
assert.NotEmpty(t, tool.Description)
assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "method")
assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "owner")
assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "repo")
assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "issue_number")
assert.ElementsMatch(t, tool.InputSchema.(*jsonschema.Schema).Required, []string{"method", "owner", "repo", "issue_number"})
// Setup mock issue for success case
mockIssue := &github.Issue{
Number: github.Ptr(42),
Title: github.Ptr("Test Issue"),
Body: github.Ptr("This is a test issue"),
State: github.Ptr("open"),
HTMLURL: github.Ptr("https://github.com/owner/repo/issues/42"),
User: &github.User{
Login: github.Ptr("testuser"),
},
Repository: &github.Repository{
Name: github.Ptr("repo"),
Owner: &github.User{
Login: github.Ptr("owner"),
},
},
}
mockIssue2 := &github.Issue{
Number: github.Ptr(422),
Title: github.Ptr("Test Issue 2"),
Body: github.Ptr("This is a test issue 2"),
State: github.Ptr("open"),
HTMLURL: github.Ptr("https://github.com/owner/repo/issues/42"),
User: &github.User{
Login: github.Ptr("testuser2"),
},
Repository: &github.Repository{
Name: github.Ptr("repo2"),
Owner: &github.User{
Login: github.Ptr("owner2"),
},
},
}
tests := []struct {
name string
mockedClient *http.Client
requestArgs map[string]any
expectHandlerError bool
expectResultError bool
expectedIssue *github.Issue
expectedErrMsg string
lockdownEnabled bool
restPermission string
}{
{
name: "successful issue retrieval",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, mockIssue),
}),
requestArgs: map[string]any{
"method": "get",
"owner": "owner2",
"repo": "repo2",
"issue_number": float64(42),
},
expectedIssue: mockIssue,
},
{
name: "issue not found",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusNotFound, `{"message": "Issue not found"}`),
}),
requestArgs: map[string]any{
"method": "get",
"owner": "owner",
"repo": "repo",
"issue_number": float64(999),
},
expectHandlerError: true,
expectedErrMsg: "failed to get issue",
},
{
name: "lockdown enabled - private repository",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, mockIssue2),
}),
requestArgs: map[string]any{
"method": "get",
"owner": "owner2",
"repo": "repo2",
"issue_number": float64(422),
},
expectedIssue: mockIssue2,
lockdownEnabled: true,
restPermission: "none",
},
{
name: "lockdown enabled - user lacks push access",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, mockIssue),
}),
requestArgs: map[string]any{
"method": "get",
"owner": "owner",
"repo": "repo",
"issue_number": float64(42),
},
expectResultError: true,
expectedErrMsg: "access to issue details is restricted by lockdown mode",
lockdownEnabled: true,
restPermission: "read",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
client := mustNewGHClient(t, tc.mockedClient)
var restClient *github.Client
if tc.restPermission != "" {
restClient = mockRESTPermissionServer(t, tc.restPermission, nil)
}
cache := stubRepoAccessCache(restClient, 15*time.Minute)
flags := stubFeatureFlags(map[string]bool{"lockdown-mode": tc.lockdownEnabled})
deps := BaseDeps{
Client: client,
GQLClient: defaultGQLClient,
RepoAccessCache: cache,
Flags: flags,
}
handler := serverTool.Handler(deps)
request := createMCPRequest(tc.requestArgs)
result, err := handler(ContextWithDeps(context.Background(), deps), &request)
if tc.expectHandlerError {
require.Error(t, err)
assert.Contains(t, err.Error(), tc.expectedErrMsg)
return
}
require.NoError(t, err)
require.NotNil(t, result)
if tc.expectResultError {
errorContent := getErrorResult(t, result)
assert.Contains(t, errorContent.Text, tc.expectedErrMsg)
return
}
textContent := getTextResult(t, result)
var returnedIssue MinimalIssue
err = json.Unmarshal([]byte(textContent.Text), &returnedIssue)
require.NoError(t, err)
assert.Equal(t, tc.expectedIssue.GetNumber(), returnedIssue.Number)
assert.Equal(t, tc.expectedIssue.GetTitle(), returnedIssue.Title)
assert.Equal(t, tc.expectedIssue.GetBody(), returnedIssue.Body)
assert.Equal(t, tc.expectedIssue.GetState(), returnedIssue.State)
assert.Equal(t, tc.expectedIssue.GetHTMLURL(), returnedIssue.HTMLURL)
assert.Equal(t, tc.expectedIssue.GetUser().GetLogin(), returnedIssue.User.Login)
})
}
}
func Test_IssueRead_IFC_InsidersMode(t *testing.T) {
t.Parallel()
serverTool := IssueRead(translations.NullTranslationHelper)
mockIssue := &github.Issue{
Number: github.Ptr(1),
Title: github.Ptr("Test"),
Body: github.Ptr("body"),
State: github.Ptr("open"),
HTMLURL: github.Ptr("https://github.com/octocat/repo/issues/1"),
User: &github.User{Login: github.Ptr("u")},
}
mockComments := []*github.IssueComment{
{Body: github.Ptr("hello"), User: &github.User{Login: github.Ptr("u")}},
}
makeMockClient := func(isPrivate bool, repoStatus int) *http.Client {
handlers := map[string]http.HandlerFunc{
GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, mockIssue),
GetReposIssuesCommentsByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, mockComments),
}
if repoStatus != 0 && repoStatus != http.StatusOK {
handlers[GetReposByOwnerByRepo] = mockResponse(t, repoStatus, "boom")
} else {
handlers[GetReposByOwnerByRepo] = mockResponse(t, http.StatusOK, map[string]any{
"name": "repo",
"private": isPrivate,
})
}
return MockHTTPClientWithHandlers(handlers)
}
getReq := map[string]any{
"method": "get",
"owner": "octocat",
"repo": "repo",
"issue_number": float64(1),
}
commentsReq := map[string]any{
"method": "get_comments",
"owner": "octocat",
"repo": "repo",
"issue_number": float64(1),
}
t.Run("insiders mode disabled omits ifc label", func(t *testing.T) {
deps := BaseDeps{
Client: mustNewGHClient(t, makeMockClient(false, 0)),
}
handler := serverTool.Handler(deps)
request := createMCPRequest(getReq)
result, err := handler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.False(t, result.IsError)
assert.Nil(t, result.Meta)
})
t.Run("insiders mode enabled on public repo emits public untrusted", func(t *testing.T) {
deps := BaseDeps{
Client: mustNewGHClient(t, makeMockClient(false, 0)),
featureChecker: featureCheckerFor(FeatureFlagIFCLabels),
}
handler := serverTool.Handler(deps)
request := createMCPRequest(getReq)
result, err := handler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.False(t, result.IsError)
require.NotNil(t, result.Meta)
ifcMap := unmarshalIFC(t, result.Meta["ifc"])
assert.Equal(t, "untrusted", ifcMap["integrity"])
assert.Equal(t, "public", ifcMap["confidentiality"])
})
t.Run("insiders mode enabled on private repo with get_comments emits private trusted", func(t *testing.T) {
deps := BaseDeps{
Client: mustNewGHClient(t, makeMockClient(true, 0)),
featureChecker: featureCheckerFor(FeatureFlagIFCLabels),
}
handler := serverTool.Handler(deps)
request := createMCPRequest(commentsReq)
result, err := handler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.False(t, result.IsError)
require.NotNil(t, result.Meta)
ifcMap := unmarshalIFC(t, result.Meta["ifc"])
assert.Equal(t, "trusted", ifcMap["integrity"])
assert.Equal(t, "private", ifcMap["confidentiality"])
})
t.Run("insiders mode skips ifc label when visibility lookup fails", func(t *testing.T) {
deps := BaseDeps{
Client: mustNewGHClient(t, makeMockClient(false, http.StatusInternalServerError)),
featureChecker: featureCheckerFor(FeatureFlagIFCLabels),
}
handler := serverTool.Handler(deps)
request := createMCPRequest(getReq)
result, err := handler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.False(t, result.IsError, "tool call should still succeed when visibility lookup fails")
if result.Meta != nil {
_, hasIFC := result.Meta["ifc"]
assert.False(t, hasIFC, "ifc label should be omitted when visibility lookup fails")
}
})
}
func Test_GetIssue_FieldValues(t *testing.T) {
// The raw REST issue_field_values are always cleared. Enriched field_values are
// only populated via GraphQL when the issue has a node ID; this issue has none,
// so field_values stays empty.
serverTool := IssueRead(translations.NullTranslationHelper)
mockIssueWithFields := &github.Issue{
Number: github.Ptr(99),
Title: github.Ptr("Issue with field values"),
Body: github.Ptr("body"),
State: github.Ptr("open"),
HTMLURL: github.Ptr("https://github.com/owner/repo/issues/99"),
User: &github.User{
Login: github.Ptr("testuser"),
},
IssueFieldValues: []*github.IssueFieldValue{
{
IssueFieldID: 1001,
NodeID: "FV_node_1",
DataType: "single_select",
Value: "High",
SingleSelectOption: &github.IssueFieldValueSingleSelectOption{
ID: 42,
Name: "High",
Color: "red",
},
},
{
IssueFieldID: 1002,
NodeID: "FV_node_2",
DataType: "text",
Value: "some text value",
},
},
}
mockedClient := MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, mockIssueWithFields),
})
cache := stubRepoAccessCache(nil, 15*time.Minute)
flags := stubFeatureFlags(map[string]bool{"lockdown-mode": false})
deps := BaseDeps{
Client: mustNewGHClient(t, mockedClient),
GQLClient: defaultGQLClient,
RepoAccessCache: cache,
Flags: flags,
}
handler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"method": "get",
"owner": "owner",
"repo": "repo",
"issue_number": float64(99),
})
result, err := handler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.NotNil(t, result)
textContent := getTextResult(t, result)
var returnedIssue MinimalIssue
err = json.Unmarshal([]byte(textContent.Text), &returnedIssue)
require.NoError(t, err)
// Raw REST IssueFieldValues must be cleared, and no enriched field_values are
// present because this issue has no node ID.
assert.Empty(t, returnedIssue.IssueFieldValues, "raw REST issue_field_values should not be exposed")
assert.Empty(t, returnedIssue.FieldValues, "enriched field_values should not be present without a node ID")
}
func Test_GetIssue_FieldValues_Enriched(t *testing.T) {
// Verify the enriched field_values are populated via GraphQL when the issue has
// a node ID, and the raw REST issue_field_values stays cleared.
serverTool := IssueRead(translations.NullTranslationHelper)
mockIssueWithFields := &github.Issue{
Number: github.Ptr(99),
NodeID: github.Ptr("I_node_99"),
Title: github.Ptr("Issue with field values"),
Body: github.Ptr("body"),
State: github.Ptr("open"),
HTMLURL: github.Ptr("https://github.com/owner/repo/issues/99"),
User: &github.User{
Login: github.Ptr("testuser"),
},
IssueFieldValues: []*github.IssueFieldValue{
{
IssueFieldID: 1001,
NodeID: "FV_node_1",
DataType: "single_select",
Value: "High",
},
},
}
restClient := MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, mockIssueWithFields),
})
gqlResponse := githubv4mock.DataResponse(map[string]any{
"nodes": []map[string]any{
{
"id": "I_node_99",
"issueFieldValues": map[string]any{
"nodes": []map[string]any{
{
"__typename": "IssueFieldSingleSelectValue",
"field": map[string]any{"name": "priority"},
"value": "P1",
},
{
"__typename": "IssueFieldNumberValue",
"field": map[string]any{"name": "estimate"},
"valueNumber": 2.5,
},
},
},
"parent": nil,
"subIssuesSummary": map[string]any{"total": 0, "completed": 0, "percentCompleted": 0},
},
},
})
matcher := newIssueReadEnrichmentMatcher("I_node_99", gqlResponse)
gqlClient := githubv4.NewClient(githubv4mock.NewMockedHTTPClient(matcher))
cache := stubRepoAccessCache(nil, 15*time.Minute)
deps := BaseDeps{
Client: mustNewGHClient(t, restClient),
GQLClient: gqlClient,
RepoAccessCache: cache,
}
handler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"method": "get",
"owner": "owner",
"repo": "repo",
"issue_number": float64(99),
})
result, err := handler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.NotNil(t, result)
require.False(t, result.IsError, "expected result to not be an error")
textContent := getTextResult(t, result)
var returnedIssue MinimalIssue
err = json.Unmarshal([]byte(textContent.Text), &returnedIssue)
require.NoError(t, err)
// Raw REST IssueFieldValues is always cleared.
assert.Empty(t, returnedIssue.IssueFieldValues, "raw REST issue_field_values should not be exposed")
// Enriched FieldValues comes from the GraphQL nodes() round-trip.
require.Len(t, returnedIssue.FieldValues, 2, "field_values should be populated from GraphQL")
assert.Equal(t, "priority", returnedIssue.FieldValues[0].Field)
assert.Equal(t, "P1", returnedIssue.FieldValues[0].Value)
assert.Equal(t, "estimate", returnedIssue.FieldValues[1].Field)
assert.Equal(t, "2.5", returnedIssue.FieldValues[1].Value)
// With no parent and no sub-issues, the routing booleans are explicit false and the
// optional relationship payloads are omitted.
assert.Equal(t, github.Ptr(false), returnedIssue.HasParent, "has_parent should be false without a parent")
assert.Equal(t, github.Ptr(false), returnedIssue.HasChildren, "has_children should be false without sub-issues")
assert.Nil(t, returnedIssue.Parent, "parent should be omitted when there is no parent")
assert.Nil(t, returnedIssue.SubIssuesSummary, "sub_issues_summary should be omitted with no sub-issues")
}
func Test_GetIssue_HierarchyEnrichment(t *testing.T) {
mockIssue := &github.Issue{
Number: github.Ptr(2990),
NodeID: github.Ptr("I_node_2990"),
Title: github.Ptr("Child issue"),
State: github.Ptr("open"),
HTMLURL: github.Ptr("https://github.com/owner/repo/issues/2990"),
User: &github.User{Login: github.Ptr("author")},
}
parentNode := map[string]any{
"number": 2820,
"title": "Parent issue",
"state": "OPEN",
"url": "https://github.com/owner/repo/issues/2820",
"author": map[string]any{"login": "parentauthor"},
"repository": map[string]any{
"nameWithOwner": "owner/repo",
},
}
tests := []struct {
name string
parent any
summary map[string]any
lockdown bool
assertResponse func(t *testing.T, issue MinimalIssue)
}{
{
name: "parent and children present",
parent: parentNode,
summary: map[string]any{"total": 4, "completed": 1, "percentCompleted": 25},
assertResponse: func(t *testing.T, issue MinimalIssue) {
assert.Equal(t, github.Ptr(true), issue.HasParent)
assert.Equal(t, github.Ptr(true), issue.HasChildren)
require.NotNil(t, issue.Parent)
assert.Equal(t, 2820, issue.Parent.Number)
assert.Equal(t, "Parent issue", issue.Parent.Title)
assert.Equal(t, "OPEN", issue.Parent.State)
assert.Equal(t, "owner/repo", issue.Parent.Repository)
require.NotNil(t, issue.SubIssuesSummary)
assert.Equal(t, 4, issue.SubIssuesSummary.Total)
assert.Equal(t, 1, issue.SubIssuesSummary.Completed)
assert.Equal(t, 25, issue.SubIssuesSummary.PercentCompleted)
},
},
{
name: "no parent omits parent and sets has_parent false",
parent: nil,
summary: map[string]any{"total": 0, "completed": 0, "percentCompleted": 0},
assertResponse: func(t *testing.T, issue MinimalIssue) {
assert.Equal(t, github.Ptr(false), issue.HasParent)
assert.Nil(t, issue.Parent)
},
},
{
name: "has_children is false when total is zero even with completed nonzero",
parent: nil,
summary: map[string]any{"total": 0, "completed": 1, "percentCompleted": 0},
assertResponse: func(t *testing.T, issue MinimalIssue) {
assert.Equal(t, github.Ptr(false), issue.HasChildren)
assert.Nil(t, issue.SubIssuesSummary)
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
restClient := MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, mockIssue),
})
gqlResponse := githubv4mock.DataResponse(map[string]any{
"nodes": []map[string]any{
{
"id": "I_node_2990",
"issueFieldValues": map[string]any{"nodes": []map[string]any{}},
"parent": tc.parent,
"subIssuesSummary": tc.summary,
},
},
})
matcher := newIssueReadEnrichmentMatcher("I_node_2990", gqlResponse)
gqlClient := githubv4.NewClient(githubv4mock.NewMockedHTTPClient(matcher))
deps := BaseDeps{
Client: mustNewGHClient(t, restClient),
GQLClient: gqlClient,
RepoAccessCache: stubRepoAccessCache(nil, 15*time.Minute),
Flags: stubFeatureFlags(map[string]bool{"lockdown-mode": tc.lockdown}),
}
serverTool := IssueRead(translations.NullTranslationHelper)
handler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"method": "get",
"owner": "owner",
"repo": "repo",
"issue_number": float64(2990),
})
result, err := handler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.NotNil(t, result)
require.False(t, result.IsError, "expected result to not be an error")
var returnedIssue MinimalIssue
require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &returnedIssue))
tc.assertResponse(t, returnedIssue)
})
}
}
func Test_GetIssue_HierarchyEnrichment_Lockdown(t *testing.T) {
mockIssue := &github.Issue{
Number: github.Ptr(2990),
NodeID: github.Ptr("I_node_2990"),
Title: github.Ptr("Child issue"),
State: github.Ptr("open"),
HTMLURL: github.Ptr("https://github.com/owner/repo/issues/2990"),
User: &github.User{Login: github.Ptr("author")},
}
parentNode := map[string]any{
"number": 2820,
"title": "Sensitive parent title",
"state": "OPEN",
"url": "https://github.com/owner/repo/issues/2820",
"author": map[string]any{"login": "parentauthor"},
"repository": map[string]any{
"nameWithOwner": "owner/repo",
},
}
// In lockdown mode the issue's own author must be verified as safe (mirrors the existing
// REST lockdown gate). The repo-access cache performs push-access checks against its own
// REST client: the issue author ("author") has write access, while the parent author
// ("parentauthor") only has read access and so cannot be verified as safe. The parent
// reference is therefore omitted entirely, while has_parent stays true so an agent can
// still route to get_parent.
restClient := MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, mockIssue),
})
permClient := mockRESTPermissionServer(t, "read", map[string]string{"author": "write"})
gqlResponse := githubv4mock.DataResponse(map[string]any{
"nodes": []map[string]any{
{
"id": "I_node_2990",
"issueFieldValues": map[string]any{"nodes": []map[string]any{}},
"parent": parentNode,
"subIssuesSummary": map[string]any{"total": 0, "completed": 0, "percentCompleted": 0},
},
},
})
matcher := newIssueReadEnrichmentMatcher("I_node_2990", gqlResponse)
gqlClient := githubv4.NewClient(githubv4mock.NewMockedHTTPClient(matcher))
deps := BaseDeps{
Client: mustNewGHClient(t, restClient),
GQLClient: gqlClient,
RepoAccessCache: stubRepoAccessCache(permClient, 15*time.Minute),
Flags: stubFeatureFlags(map[string]bool{"lockdown-mode": true}),
}
serverTool := IssueRead(translations.NullTranslationHelper)
handler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"method": "get",
"owner": "owner",
"repo": "repo",
"issue_number": float64(2990),
})
result, err := handler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.NotNil(t, result)
require.False(t, result.IsError, "expected result to not be an error")
var returnedIssue MinimalIssue
require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &returnedIssue))
require.Nil(t, returnedIssue.Parent, "parent reference should be omitted under lockdown when it cannot be verified safe")
assert.Equal(t, github.Ptr(true), returnedIssue.HasParent, "has_parent should still be true so agents can route to get_parent")
}
func Test_GetIssue_HierarchyEnrichment_QueryFailureReturnsBaseIssue(t *testing.T) {
mockIssue := &github.Issue{
Number: github.Ptr(2990),
NodeID: github.Ptr("I_node_2990"),
Title: github.Ptr("Child issue"),
State: github.Ptr("open"),
HTMLURL: github.Ptr("https://github.com/owner/repo/issues/2990"),
User: &github.User{Login: github.Ptr("author")},
}
restClient := MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, mockIssue),
})
matcher := newIssueReadEnrichmentMatcher("I_node_2990", githubv4mock.ErrorResponse("enrichment failed"))
gqlClient := githubv4.NewClient(githubv4mock.NewMockedHTTPClient(matcher))
deps := BaseDeps{
Client: mustNewGHClient(t, restClient),
GQLClient: gqlClient,
RepoAccessCache: stubRepoAccessCache(nil, 15*time.Minute),
Flags: stubFeatureFlags(map[string]bool{"lockdown-mode": false}),
}
serverTool := IssueRead(translations.NullTranslationHelper)
handler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"method": "get",
"owner": "owner",
"repo": "repo",
"issue_number": float64(2990),
})
result, err := handler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.NotNil(t, result)
// Relationship enrichment must never fail `get`: the base issue is still returned.
require.False(t, result.IsError, "enrichment failure should not fail get")
var returnedIssue MinimalIssue
require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &returnedIssue))
assert.Equal(t, 2990, returnedIssue.Number)
assert.Nil(t, returnedIssue.HasParent)
assert.Nil(t, returnedIssue.HasChildren)
assert.Nil(t, returnedIssue.Parent)
assert.Nil(t, returnedIssue.SubIssuesSummary)
}
func Test_SearchIssues(t *testing.T) {
// Verify tool definition once
serverTool := SearchIssues(translations.NullTranslationHelper)
tool := serverTool.Tool
require.NoError(t, toolsnaps.Test(tool.Name, tool))
assert.Equal(t, "search_issues", tool.Name)
assert.NotEmpty(t, tool.Description)
assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "query")
assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "owner")
assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "repo")
assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "sort")
assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "order")
assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "perPage")
assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "page")
assert.ElementsMatch(t, tool.InputSchema.(*jsonschema.Schema).Required, []string{"query"})
// Setup mock search results
mockSearchResult := &github.IssuesSearchResult{
Total: github.Ptr(2),
IncompleteResults: github.Ptr(false),
Issues: []*github.Issue{
{
Number: github.Ptr(42),
Title: github.Ptr("Bug: Something is broken"),
Body: github.Ptr("This is a bug report"),
State: github.Ptr("open"),
HTMLURL: github.Ptr("https://github.com/owner/repo/issues/42"),
Comments: github.Ptr(5),
User: &github.User{
Login: github.Ptr("user1"),
},
},
{
Number: github.Ptr(43),
Title: github.Ptr("Feature: Add new functionality"),
Body: github.Ptr("This is a feature request"),
State: github.Ptr("open"),
HTMLURL: github.Ptr("https://github.com/owner/repo/issues/43"),
Comments: github.Ptr(3),
User: &github.User{
Login: github.Ptr("user2"),
},
},
},
}
tests := []struct {
name string
mockedClient *http.Client
requestArgs map[string]any
expectError bool
expectedResult *github.IssuesSearchResult
expectedErrMsg string
}{
{
name: "successful issues search with all parameters",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetSearchIssues: expectQueryParams(
t,
map[string]string{
"q": "is:issue repo:owner/repo is:open",
"sort": "created",
"order": "desc",
"page": "1",
"per_page": "30",
},
).andThen(
mockResponse(t, http.StatusOK, mockSearchResult),
),
}),
requestArgs: map[string]any{
"query": "repo:owner/repo is:open",
"sort": "created",
"order": "desc",
"page": float64(1),
"perPage": float64(30),
},
expectError: false,
expectedResult: mockSearchResult,
},
{
name: "issues search with owner and repo parameters",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetSearchIssues: expectQueryParams(
t,
map[string]string{
"q": "repo:test-owner/test-repo is:issue is:open",
"sort": "created",
"order": "asc",
"page": "1",
"per_page": "30",
},
).andThen(
mockResponse(t, http.StatusOK, mockSearchResult),
),
}),
requestArgs: map[string]any{
"query": "is:open",
"owner": "test-owner",
"repo": "test-repo",
"sort": "created",
"order": "asc",
},
expectError: false,
expectedResult: mockSearchResult,
},
{
name: "issues search with only owner parameter (should ignore it)",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetSearchIssues: expectQueryParams(
t,
map[string]string{
"q": "is:issue bug",
"page": "1",
"per_page": "30",
},
).andThen(
mockResponse(t, http.StatusOK, mockSearchResult),
),
}),
requestArgs: map[string]any{
"query": "bug",
"owner": "test-owner",
},
expectError: false,
expectedResult: mockSearchResult,
},
{
name: "issues search with only repo parameter (should ignore it)",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetSearchIssues: expectQueryParams(
t,
map[string]string{
"q": "is:issue feature",
"page": "1",
"per_page": "30",
},
).andThen(
mockResponse(t, http.StatusOK, mockSearchResult),
),
}),
requestArgs: map[string]any{
"query": "feature",
"repo": "test-repo",
},
expectError: false,
expectedResult: mockSearchResult,
},
{
name: "issues search with minimal parameters",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetSearchIssues: mockResponse(t, http.StatusOK, mockSearchResult),
}),
requestArgs: map[string]any{
"query": "is:issue repo:owner/repo is:open",
},
expectError: false,
expectedResult: mockSearchResult,
},
{
name: "query with existing is:issue filter - no duplication",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetSearchIssues: expectQueryParams(
t,
map[string]string{
"q": "repo:github/github-mcp-server is:issue is:open (label:critical OR label:urgent)",
"page": "1",
"per_page": "30",
},
).andThen(
mockResponse(t, http.StatusOK, mockSearchResult),
),
}),
requestArgs: map[string]any{
"query": "repo:github/github-mcp-server is:issue is:open (label:critical OR label:urgent)",
},
expectError: false,
expectedResult: mockSearchResult,
},
{
name: "query with existing repo: filter and conflicting owner/repo params - uses query filter",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetSearchIssues: expectQueryParams(
t,
map[string]string{
"q": "is:issue repo:github/github-mcp-server critical",
"page": "1",
"per_page": "30",
},