{{ message }}
Repository navigation
Expand file tree
/
Copy pathfind_duplicate_test.go
More file actions
387 lines (341 loc) · 13.4 KB
/
Copy pathfind_duplicate_test.go
File metadata and controls
387 lines (341 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package github
import (
"context"
"encoding/json"
"net/http"
"net/url"
"testing"
"github.com/github/github-mcp-server/internal/toolsnaps"
"github.com/github/github-mcp-server/pkg/inventory"
"github.com/github/github-mcp-server/pkg/translations"
"github.com/google/jsonschema-go/jsonschema"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const endpointSemanticallySimilar = EndpointPattern("GET /repos/{owner}/{repo}/issues/{issue_number}/semantically_similar")
func Test_FindDuplicate(t *testing.T) {
// Verify tool definition once (flag-gated variant snap).
serverTool := FindDuplicate(translations.NullTranslationHelper)
tool := serverTool.Tool
require.NoError(t, toolsnaps.Test(tool.Name+"_ff_"+string(FeatureFlagDuplicateDetection), tool))
require.Equal(t, []inventory.FeatureFlag{FeatureFlagDuplicateDetection}, serverTool.FeatureRule.Features())
assert.Equal(t, "find_duplicate", tool.Name)
assert.NotEmpty(t, tool.Description)
assert.True(t, tool.Annotations.ReadOnlyHint)
assert.Equal(t, []string{"repo"}, serverTool.ScopeAccess.Scopes)
assert.NotNil(t, serverTool.ScopeAccess.Visible)
assert.NotNil(t, serverTool.ScopeAccess.Challenge)
schema := tool.InputSchema.(*jsonschema.Schema)
assert.Contains(t, schema.Properties, "owner")
assert.Contains(t, schema.Properties, "repo")
assert.Contains(t, schema.Properties, "issue_number")
assert.Contains(t, schema.Properties, "confidence_threshold")
assert.Contains(t, schema.Properties, "page")
assert.Contains(t, schema.Properties, "perPage")
assert.ElementsMatch(t, schema.Required, []string{"owner", "repo", "issue_number"})
}
func Test_FindDuplicate_RankedResults(t *testing.T) {
serverTool := FindDuplicate(translations.NullTranslationHelper)
rankedResults := []map[string]any{
{
"issue": map[string]any{
"number": 456,
"title": "Example failure when saving",
"state": "open",
"html_url": "https://github.com/owner/repo/issues/456",
},
"score": 0.95,
"confidence": "high",
"likely_duplicate": true,
},
{
"issue": map[string]any{
"number": 789,
"title": "Possibly related",
"state": "closed",
"html_url": "https://github.com/owner/repo/issues/789",
},
"score": nil, // score is nullable
"confidence": "low",
"likely_duplicate": false,
},
}
var capturedURL *url.URL
var capturedMethod string
handler := func(w http.ResponseWriter, r *http.Request) {
capturedURL = r.URL
capturedMethod = r.Method
w.WriteHeader(http.StatusOK)
_, _ = w.Write(MustMarshal(rankedResults))
}
client := mustNewGHClient(t, NewMockedHTTPClient(WithRequestMatchHandler(endpointSemanticallySimilar, http.HandlerFunc(handler))))
deps := BaseDeps{Client: client}
toolHandler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"owner": "owner",
"repo": "repo",
"issue_number": float64(123),
"confidence_threshold": float64(0.8),
"perPage": float64(10),
"page": float64(1),
})
result, err := toolHandler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.False(t, result.IsError, "expected result to not be an error")
// The tool must be read-only: only a GET is issued.
assert.Equal(t, http.MethodGet, capturedMethod)
// confidence_threshold maps to threshold; perPage maps to per_page; page is forwarded.
require.NotNil(t, capturedURL)
assert.Equal(t, "0.8", capturedURL.Query().Get("threshold"))
assert.Equal(t, "10", capturedURL.Query().Get("per_page"))
assert.Equal(t, "1", capturedURL.Query().Get("page"))
text := getTextResult(t, result)
var candidates []duplicateCandidate
require.NoError(t, json.Unmarshal([]byte(text.Text), &candidates))
require.Len(t, candidates, 2)
assert.Equal(t, "high", candidates[0].Confidence)
assert.True(t, candidates[0].LikelyDuplicate)
require.NotNil(t, candidates[0].Score)
assert.InDelta(t, 0.95, *candidates[0].Score, 0.0001)
assert.Equal(t, 456, candidates[0].Issue.Number)
assert.Equal(t, "Example failure when saving", candidates[0].Issue.Title)
assert.Equal(t, "open", candidates[0].Issue.State)
assert.Equal(t, "https://github.com/owner/repo/issues/456", candidates[0].Issue.URL)
// A null score must decode successfully.
assert.Nil(t, candidates[1].Score)
assert.Equal(t, "low", candidates[1].Confidence)
assert.False(t, candidates[1].LikelyDuplicate)
}
// Test_FindDuplicate_SanitizesIssueTitle asserts that candidate issue titles, which are
// user-authored content from an arbitrary repository, are sanitized before being returned.
// Without this the tool would forward hidden-instruction payloads straight to the model.
func Test_FindDuplicate_SanitizesIssueTitle(t *testing.T) {
serverTool := FindDuplicate(translations.NullTranslationHelper)
rankedResults := []map[string]any{
{
"issue": map[string]any{
"number": 456,
"title": maliciousText,
"state": "open",
"html_url": "https://github.com/owner/repo/issues/456",
},
"score": 0.95,
"confidence": "high",
"likely_duplicate": true,
},
}
handler := func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write(MustMarshal(rankedResults))
}
client := mustNewGHClient(t, NewMockedHTTPClient(WithRequestMatchHandler(endpointSemanticallySimilar, http.HandlerFunc(handler))))
deps := BaseDeps{Client: client}
toolHandler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"owner": "owner",
"repo": "repo",
"issue_number": float64(123),
})
result, err := toolHandler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.False(t, result.IsError, "expected result to not be an error")
text := getTextResult(t, result)
var candidates []duplicateCandidate
require.NoError(t, json.Unmarshal([]byte(text.Text), &candidates))
require.Len(t, candidates, 1)
assert.Equal(t, sanitizedText, candidates[0].Issue.Title)
}
func Test_FindDuplicate_OmitsUnsetParams(t *testing.T) {
serverTool := FindDuplicate(translations.NullTranslationHelper)
var capturedURL *url.URL
handler := func(w http.ResponseWriter, r *http.Request) {
capturedURL = r.URL
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`[]`))
}
client := mustNewGHClient(t, NewMockedHTTPClient(WithRequestMatchHandler(endpointSemanticallySimilar, http.HandlerFunc(handler))))
deps := BaseDeps{Client: client}
toolHandler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"owner": "owner",
"repo": "repo",
"issue_number": float64(123),
})
result, err := toolHandler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.False(t, result.IsError)
require.NotNil(t, capturedURL)
q := capturedURL.Query()
_, hasThreshold := q["threshold"]
_, hasPerPage := q["per_page"]
_, hasPage := q["page"]
assert.False(t, hasThreshold, "threshold should be omitted when unset")
assert.False(t, hasPerPage, "per_page should be omitted when unset")
assert.False(t, hasPage, "page should be omitted when unset")
}
func Test_FindDuplicate_EmptyResults(t *testing.T) {
serverTool := FindDuplicate(translations.NullTranslationHelper)
client := mustNewGHClient(t, NewMockedHTTPClient(WithRequestMatch(endpointSemanticallySimilar, []map[string]any{})))
deps := BaseDeps{Client: client}
toolHandler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"owner": "owner",
"repo": "repo",
"issue_number": float64(123),
})
result, err := toolHandler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.False(t, result.IsError, "empty results is a successful search")
text := getTextResult(t, result)
var candidates []duplicateCandidate
require.NoError(t, json.Unmarshal([]byte(text.Text), &candidates))
assert.Empty(t, candidates)
}
func Test_FindDuplicate_LegacyBareIssueResponse(t *testing.T) {
serverTool := FindDuplicate(translations.NullTranslationHelper)
// When ranked duplicate detection is disabled the endpoint returns bare
// issue resources (no ranking metadata), which must fail clearly.
bareIssues := []map[string]any{
{
"number": 456,
"title": "Example",
"state": "open",
"html_url": "https://github.com/owner/repo/issues/456",
},
}
client := mustNewGHClient(t, NewMockedHTTPClient(WithRequestMatch(endpointSemanticallySimilar, bareIssues)))
deps := BaseDeps{Client: client}
toolHandler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"owner": "owner",
"repo": "repo",
"issue_number": float64(123),
})
result, err := toolHandler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
getErrorResult(t, result)
}
func Test_FindDuplicate_Errors(t *testing.T) {
serverTool := FindDuplicate(translations.NullTranslationHelper)
t.Run("missing required param", func(t *testing.T) {
client := mustNewGHClient(t, NewMockedHTTPClient())
deps := BaseDeps{Client: client}
toolHandler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"owner": "owner",
"repo": "repo",
})
result, err := toolHandler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
getErrorResult(t, result)
})
t.Run("API error is surfaced", func(t *testing.T) {
client := mustNewGHClient(t, NewMockedHTTPClient(
WithRequestMatchHandler(endpointSemanticallySimilar, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"message": "Not Found"}`))
})),
))
deps := BaseDeps{Client: client}
toolHandler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"owner": "owner",
"repo": "repo",
"issue_number": float64(123),
})
result, err := toolHandler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
getErrorResult(t, result)
})
}
func Test_FindDuplicate_IFCLabels(t *testing.T) {
serverTool := FindDuplicate(translations.NullTranslationHelper)
rankedResults := []map[string]any{
{
"issue": map[string]any{
"number": 585,
"title": "Improve the onboarding flow for new users",
"state": "open",
"html_url": "https://github.com/owner/repo/issues/585",
},
"score": 1.93,
"confidence": "high",
"likely_duplicate": true,
},
}
// makeClient serves the semantic-similarity endpoint plus the repo lookup
// that the IFC labeler uses to resolve visibility.
makeClient := func(isPrivate bool, repoStatus int) *http.Client {
handlers := map[string]http.HandlerFunc{
string(endpointSemanticallySimilar): mockResponse(t, http.StatusOK, rankedResults),
}
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)
}
req := map[string]any{
"owner": "owner",
"repo": "repo",
"issue_number": float64(769),
}
t.Run("flag disabled omits ifc label", func(t *testing.T) {
deps := BaseDeps{Client: mustNewGHClient(t, makeClient(false, 0))}
handler := serverTool.Handler(deps)
request := createMCPRequest(req)
result, err := handler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.False(t, result.IsError)
assert.Nil(t, result.Meta)
})
t.Run("flag enabled on public repo emits public untrusted", func(t *testing.T) {
deps := BaseDeps{
Client: mustNewGHClient(t, makeClient(false, 0)),
featureChecker: featureCheckerFor(FeatureFlagIFCLabels),
}
handler := serverTool.Handler(deps)
request := createMCPRequest(req)
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("flag enabled on private repo emits private trusted", func(t *testing.T) {
deps := BaseDeps{
Client: mustNewGHClient(t, makeClient(true, 0)),
featureChecker: featureCheckerFor(FeatureFlagIFCLabels),
}
handler := serverTool.Handler(deps)
request := createMCPRequest(req)
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("visibility lookup failure omits label but still succeeds", func(t *testing.T) {
deps := BaseDeps{
Client: mustNewGHClient(t, makeClient(false, http.StatusInternalServerError)),
featureChecker: featureCheckerFor(FeatureFlagIFCLabels),
}
handler := serverTool.Handler(deps)
request := createMCPRequest(req)
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, "label must be omitted on visibility lookup failure")
}
})
}
You can’t perform that action at this time.
