forked from github/github-mcp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprojects_resolver.go
More file actions
424 lines (383 loc) · 14.4 KB
/
Copy pathprojects_resolver.go
File metadata and controls
424 lines (383 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package github
import (
"context"
"fmt"
"strconv"
"strings"
ghErrors "github.com/github/github-mcp-server/pkg/errors"
"github.com/shurcooL/githubv4"
)
// resolverFieldsPageSize is the GraphQL ProjectV2 max page size; covers most
// projects in a single round-trip.
const resolverFieldsPageSize = 100
// ResolvedFieldOption is one option on a SINGLE_SELECT project field.
type ResolvedFieldOption struct {
ID string
Name string
}
// ResolvedField contains a project's numeric database ID, GraphQL node ID, and
// type-specific options.
type ResolvedField struct {
ID string
NodeID string
Name string
DataType string
Options []ResolvedFieldOption
}
// projectFieldsQueryOrg fetches all fields on an org-owned project (paginated).
type projectFieldsQueryOrg struct {
Organization struct {
ProjectV2 struct {
Fields projectFieldsConnection `graphql:"fields(first: $first, after: $after)"`
} `graphql:"projectV2(number: $projectNumber)"`
} `graphql:"organization(login: $owner)"`
}
// projectFieldsQueryUser fetches all fields on a user-owned project (paginated).
type projectFieldsQueryUser struct {
User struct {
ProjectV2 struct {
Fields projectFieldsConnection `graphql:"fields(first: $first, after: $after)"`
} `graphql:"projectV2(number: $projectNumber)"`
} `graphql:"user(login: $owner)"`
}
// projectFieldsConnection is a paginated list of project fields. We select `id`
// to discriminate the union variant and `databaseId` for the numeric ID REST needs.
type projectFieldsConnection struct {
Nodes []struct {
ProjectV2Field struct {
ID githubv4.ID
DatabaseID githubv4.Int `graphql:"databaseId"`
Name githubv4.String
DataType githubv4.String
} `graphql:"... on ProjectV2Field"`
ProjectV2IterationField struct {
ID githubv4.ID
DatabaseID githubv4.Int `graphql:"databaseId"`
Name githubv4.String
DataType githubv4.String
} `graphql:"... on ProjectV2IterationField"`
ProjectV2SingleSelectField struct {
ID githubv4.ID
DatabaseID githubv4.Int `graphql:"databaseId"`
Name githubv4.String
DataType githubv4.String
Options []struct {
ID githubv4.String
Name githubv4.String
}
} `graphql:"... on ProjectV2SingleSelectField"`
}
PageInfo PageInfoFragment
}
// listAllProjectFields fetches every field on a project, paginating as needed.
func listAllProjectFields(ctx context.Context, gqlClient *githubv4.Client, owner, ownerType string, projectNumber int) ([]ResolvedField, error) {
all := []ResolvedField{}
var after *githubv4.String
for {
vars := map[string]any{
"owner": githubv4.String(owner),
"projectNumber": githubv4.Int(int32(projectNumber)), //nolint:gosec // Project numbers are small
"first": githubv4.Int(resolverFieldsPageSize),
"after": (*githubv4.String)(nil),
}
if after != nil {
vars["after"] = after
}
var conn projectFieldsConnection
if ownerType == "org" {
var q projectFieldsQueryOrg
if err := gqlClient.Query(ctx, &q, vars); err != nil {
return nil, fmt.Errorf("failed to list project fields: %w", err)
}
conn = q.Organization.ProjectV2.Fields
} else {
var q projectFieldsQueryUser
if err := gqlClient.Query(ctx, &q, vars); err != nil {
return nil, fmt.Errorf("failed to list project fields: %w", err)
}
conn = q.User.ProjectV2.Fields
}
for _, n := range conn.Nodes {
switch {
case n.ProjectV2SingleSelectField.ID != nil:
opts := make([]ResolvedFieldOption, 0, len(n.ProjectV2SingleSelectField.Options))
for _, o := range n.ProjectV2SingleSelectField.Options {
opts = append(opts, ResolvedFieldOption{ID: string(o.ID), Name: string(o.Name)})
}
all = append(all, ResolvedField{
ID: fmt.Sprintf("%d", n.ProjectV2SingleSelectField.DatabaseID),
NodeID: fmt.Sprintf("%v", n.ProjectV2SingleSelectField.ID),
Name: string(n.ProjectV2SingleSelectField.Name),
DataType: string(n.ProjectV2SingleSelectField.DataType),
Options: opts,
})
case n.ProjectV2IterationField.ID != nil:
all = append(all, ResolvedField{
ID: fmt.Sprintf("%d", n.ProjectV2IterationField.DatabaseID),
NodeID: fmt.Sprintf("%v", n.ProjectV2IterationField.ID),
Name: string(n.ProjectV2IterationField.Name),
DataType: string(n.ProjectV2IterationField.DataType),
})
case n.ProjectV2Field.ID != nil:
all = append(all, ResolvedField{
ID: fmt.Sprintf("%d", n.ProjectV2Field.DatabaseID),
NodeID: fmt.Sprintf("%v", n.ProjectV2Field.ID),
Name: string(n.ProjectV2Field.Name),
DataType: string(n.ProjectV2Field.DataType),
})
}
}
if !bool(conn.PageInfo.HasNextPage) {
break
}
end := conn.PageInfo.EndCursor
after = &end
}
return all, nil
}
// resolveProjectFieldByName resolves a field by display name. Returns a
// structured error on not-found, ambiguous, or wrong-data-type (when
// expectedDataType is set) so the agent can self-correct.
func resolveProjectFieldByName(ctx context.Context, gqlClient *githubv4.Client, owner, ownerType string, projectNumber int, fieldName, expectedDataType string) (*ResolvedField, error) {
if fieldName == "" {
return nil, fmt.Errorf("field name must not be empty")
}
all, err := listAllProjectFields(ctx, gqlClient, owner, ownerType, projectNumber)
if err != nil {
return nil, err
}
var matches []ResolvedField
for _, f := range all {
if strings.EqualFold(f.Name, fieldName) {
matches = append(matches, f)
}
}
if len(matches) == 0 {
candidates := make([]any, 0, len(all))
for _, f := range all {
candidates = append(candidates, map[string]any{
"name": f.Name,
"data_type": f.DataType,
})
}
return nil, ghErrors.NewStructuredResolutionError(
"field_not_found",
fieldName,
fmt.Sprintf("no project field named %q on project %s#%d; see candidates for available names", fieldName, owner, projectNumber),
candidates,
)
}
if len(matches) > 1 {
candidates := make([]any, 0, len(matches))
for _, f := range matches {
candidates = append(candidates, map[string]any{
"id": f.ID,
"data_type": f.DataType,
})
}
return nil, ghErrors.NewStructuredResolutionError(
"field_ambiguous",
fieldName,
"multiple fields share this name; pass updated_field.id to disambiguate",
candidates,
)
}
field := matches[0]
if expectedDataType != "" && field.DataType != expectedDataType {
return nil, ghErrors.NewStructuredResolutionError(
"wrong_field_type",
fieldName,
fmt.Sprintf("field %q has data type %q but %q was expected", fieldName, field.DataType, expectedDataType),
[]any{map[string]any{"id": field.ID, "data_type": field.DataType}},
)
}
return &field, nil
}
// resolveSingleSelectOptionByName resolves an option name to its ID on a
// SINGLE_SELECT field. Returns a structured error if not found or ambiguous.
func resolveSingleSelectOptionByName(field *ResolvedField, optionName string) (string, error) {
if field == nil {
return "", fmt.Errorf("field must not be nil")
}
if field.DataType != "SINGLE_SELECT" {
return "", ghErrors.NewStructuredResolutionError(
"wrong_field_type",
field.Name,
fmt.Sprintf("cannot resolve option name on non-SINGLE_SELECT field %q (data type %q)", field.Name, field.DataType),
nil,
)
}
var matchIDs []string
for _, o := range field.Options {
if strings.EqualFold(o.Name, optionName) {
matchIDs = append(matchIDs, o.ID)
}
}
switch len(matchIDs) {
case 0:
candidates := make([]any, 0, len(field.Options))
for _, o := range field.Options {
candidates = append(candidates, map[string]any{"name": o.Name})
}
return "", ghErrors.NewStructuredResolutionError(
"option_not_found",
optionName,
fmt.Sprintf("no option named %q on field %q; see candidates for available options", optionName, field.Name),
candidates,
)
case 1:
return matchIDs[0], nil
default:
candidates := make([]any, 0, len(matchIDs))
for _, id := range matchIDs {
candidates = append(candidates, map[string]any{"id": id})
}
return "", ghErrors.NewStructuredResolutionError(
"option_ambiguous",
optionName,
fmt.Sprintf("multiple options on field %q share the name %q", field.Name, optionName),
candidates,
)
}
}
// resolveProjectItemIDByIssueNumber resolves a (project, issue) pair to the
// project item's full database ID in one GraphQL hop. Returns a structured
// error if the issue is not an item on the project.
func resolveProjectItemIDByIssueNumber(ctx context.Context, gqlClient *githubv4.Client, owner, ownerType string, projectNumber int, issueOwner, issueRepo string, issueNumber int) (int64, error) {
_, itemID, err := resolveProjectItemByIssueNumber(ctx, gqlClient, owner, ownerType, projectNumber, issueOwner, issueRepo, issueNumber)
return itemID, err
}
func resolveProjectItemByIssueNumber(ctx context.Context, gqlClient *githubv4.Client, owner, ownerType string, projectNumber int, issueOwner, issueRepo string, issueNumber int) (nodeID string, itemID int64, err error) {
projectID, err := resolveProjectNodeID(ctx, gqlClient, owner, ownerType, projectNumber)
if err != nil {
return "", 0, err
}
return resolveProjectItemByIssueNumberWithProjectID(ctx, gqlClient, projectID, issueOwner, issueRepo, issueNumber)
}
func resolveProjectItemByIssueNumberWithProjectID(ctx context.Context, gqlClient *githubv4.Client, projectID githubv4.ID, issueOwner, issueRepo string, issueNumber int) (nodeID string, itemID int64, err error) {
type projectItemsConnection struct {
Nodes []struct {
ID githubv4.ID
FullDatabaseID githubv4.String `graphql:"fullDatabaseId"`
Project struct {
ID githubv4.ID
}
}
PageInfo PageInfoFragment
}
var firstPageQuery struct {
Repository struct {
Issue struct {
ProjectItems projectItemsConnection `graphql:"projectItems(first: 50, includeArchived: true)"`
} `graphql:"issue(number: $issueNumber)"`
} `graphql:"repository(owner: $issueOwner, name: $issueRepo)"`
}
vars := map[string]any{
"issueOwner": githubv4.String(issueOwner),
"issueRepo": githubv4.String(issueRepo),
"issueNumber": githubv4.Int(int32(issueNumber)), //nolint:gosec // Issue numbers are small
}
if err := gqlClient.Query(ctx, &firstPageQuery, vars); err != nil {
return "", 0, fmt.Errorf("failed to resolve project item for %s/%s#%d: %w", issueOwner, issueRepo, issueNumber, err)
}
projectItems := firstPageQuery.Repository.Issue.ProjectItems
for {
for _, item := range projectItems.Nodes {
if item.Project.ID == projectID {
parsedItemID, parseErr := parseInt64(string(item.FullDatabaseID))
if parseErr != nil {
return "", 0, fmt.Errorf("project item ID %q is not an integer: %w", string(item.FullDatabaseID), parseErr)
}
return fmt.Sprintf("%v", item.ID), parsedItemID, nil
}
}
if !projectItems.PageInfo.HasNextPage {
break
}
var nextPageQuery struct {
Repository struct {
Issue struct {
ProjectItems projectItemsConnection `graphql:"projectItems(first: 50, after: $after, includeArchived: true)"`
} `graphql:"issue(number: $issueNumber)"`
} `graphql:"repository(owner: $issueOwner, name: $issueRepo)"`
}
vars["after"] = projectItems.PageInfo.EndCursor
if err := gqlClient.Query(ctx, &nextPageQuery, vars); err != nil {
return "", 0, fmt.Errorf("failed to resolve project item for %s/%s#%d: %w", issueOwner, issueRepo, issueNumber, err)
}
projectItems = nextPageQuery.Repository.Issue.ProjectItems
}
return "", 0, ghErrors.NewStructuredResolutionError(
"item_not_in_project",
fmt.Sprintf("%s/%s#%d", issueOwner, issueRepo, issueNumber),
"the issue exists but is not an item on the named project; add it first via add_project_item",
nil,
)
}
// resolveItemIDFromIssueArgs reads (item_owner, item_repo, issue_number) from args
// and resolves them to a project item ID. Returns a single friendly error if any input is missing.
func resolveItemIDFromIssueArgs(ctx context.Context, gqlClient *githubv4.Client, owner, ownerType string, projectNumber int, args map[string]any) (int64, error) {
issueOwner, ownerErr := RequiredParam[string](args, "item_owner")
issueRepo, repoErr := RequiredParam[string](args, "item_repo")
issueNumber, numErr := RequiredInt(args, "issue_number")
if ownerErr != nil || repoErr != nil || numErr != nil {
return 0, fmt.Errorf("update_project_item requires either item_id, or item_owner + item_repo + issue_number to resolve the item by issue")
}
return resolveProjectItemIDByIssueNumber(ctx, gqlClient, owner, ownerType, projectNumber, issueOwner, issueRepo, issueNumber)
}
func parseInt64(s string) (int64, error) {
return strconv.ParseInt(s, 10, 64)
}
// resolveFieldNamesToIDs resolves field names to numeric IDs in one GraphQL
// hop. Fails fast with a structured error on any unresolved or ambiguous name.
func resolveFieldNamesToIDs(ctx context.Context, gqlClient *githubv4.Client, owner, ownerType string, projectNumber int, names []string) ([]int64, error) {
if len(names) == 0 {
return nil, nil
}
all, err := listAllProjectFields(ctx, gqlClient, owner, ownerType, projectNumber)
if err != nil {
return nil, err
}
// Build a name -> []ResolvedField map so we can detect duplicates per name.
// Matching is case-insensitive to align with the GraphQL API's behaviour.
byName := make(map[string][]ResolvedField, len(all))
for _, f := range all {
key := strings.ToLower(f.Name)
byName[key] = append(byName[key], f)
}
out := make([]int64, 0, len(names))
for _, name := range names {
matches := byName[strings.ToLower(name)]
switch len(matches) {
case 0:
candidates := make([]any, 0, len(all))
for _, f := range all {
candidates = append(candidates, map[string]any{"name": f.Name, "data_type": f.DataType})
}
return nil, ghErrors.NewStructuredResolutionError(
"field_not_found",
name,
fmt.Sprintf("no project field named %q on project %s#%d", name, owner, projectNumber),
candidates,
)
case 1:
id, parseErr := parseInt64(matches[0].ID)
if parseErr != nil {
return nil, fmt.Errorf("resolved field %q has non-numeric ID %q; pass it via 'fields' instead", name, matches[0].ID)
}
out = append(out, id)
default:
candidates := make([]any, 0, len(matches))
for _, f := range matches {
candidates = append(candidates, map[string]any{"id": f.ID, "data_type": f.DataType})
}
return nil, ghErrors.NewStructuredResolutionError(
"field_ambiguous",
name,
"multiple fields share this name; pass numeric IDs via 'fields' to disambiguate",
candidates,
)
}
}
return out, nil
}