forked from github/github-mcp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopilot.go
More file actions
983 lines (896 loc) · 35.8 KB
/
Copy pathcopilot.go
File metadata and controls
983 lines (896 loc) · 35.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
package github
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
ghcontext "github.com/github/github-mcp-server/pkg/context"
ghErrors "github.com/github/github-mcp-server/pkg/errors"
"github.com/github/github-mcp-server/pkg/inventory"
"github.com/github/github-mcp-server/pkg/octicons"
"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/go-viper/mapstructure/v2"
"github.com/google/go-github/v89/github"
"github.com/google/jsonschema-go/jsonschema"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/shurcooL/githubv4"
)
// mvpDescription is an MVP idea for generating tool descriptions from structured data in a shared format.
// It is not intended for widespread usage and is not a complete implementation.
type mvpDescription struct {
summary string
outcomes []string
referenceLinks []string
}
func (d *mvpDescription) String() string {
var sb strings.Builder
sb.WriteString(d.summary)
if len(d.outcomes) > 0 {
sb.WriteString("\n\n")
sb.WriteString("This tool can help with the following outcomes:\n")
for _, outcome := range d.outcomes {
sb.WriteString(fmt.Sprintf("- %s\n", outcome))
}
}
if len(d.referenceLinks) > 0 {
sb.WriteString("\n\n")
sb.WriteString("More information can be found at:\n")
for _, link := range d.referenceLinks {
sb.WriteString(fmt.Sprintf("- %s\n", link))
}
}
return sb.String()
}
// linkedPullRequest represents a PR linked to an issue by Copilot.
type linkedPullRequest struct {
Number int
URL string
Title string
State string
CreatedAt time.Time
}
// pollConfigKey is a context key for polling configuration.
type pollConfigKey struct{}
// PollConfig configures the PR polling behavior.
type PollConfig struct {
MaxAttempts int
Delay time.Duration
}
// ContextWithPollConfig returns a context with polling configuration.
// Use this in tests to reduce or disable polling.
func ContextWithPollConfig(ctx context.Context, config PollConfig) context.Context {
return context.WithValue(ctx, pollConfigKey{}, config)
}
// getPollConfig returns the polling configuration from context, or defaults.
func getPollConfig(ctx context.Context) PollConfig {
if config, ok := ctx.Value(pollConfigKey{}).(PollConfig); ok {
return config
}
// Default: 9 attempts with 1s delay = 8s max wait
// Based on observed latency in remote server: p50 ~5s, p90 ~7s
return PollConfig{MaxAttempts: 9, Delay: 1 * time.Second}
}
// findLinkedCopilotPR searches for a PR created by the copilot-swe-agent bot that references the given issue.
// It queries the issue's timeline for CrossReferencedEvent items from PRs authored by copilot-swe-agent.
// The createdAfter parameter filters to only return PRs created after the specified time.
func findLinkedCopilotPR(ctx context.Context, client *githubv4.Client, owner, repo string, issueNumber int, createdAfter time.Time) (*linkedPullRequest, error) {
// Query timeline items looking for CrossReferencedEvent from PRs by copilot-swe-agent
var query struct {
Repository struct {
Issue struct {
TimelineItems struct {
Nodes []struct {
TypeName string `graphql:"__typename"`
CrossReferencedEvent struct {
Source struct {
PullRequest struct {
Number int
URL string
Title string
State string
CreatedAt githubv4.DateTime
Author struct {
Login string
}
} `graphql:"... on PullRequest"`
}
} `graphql:"... on CrossReferencedEvent"`
}
} `graphql:"timelineItems(first: 20, itemTypes: [CROSS_REFERENCED_EVENT])"`
} `graphql:"issue(number: $number)"`
} `graphql:"repository(owner: $owner, name: $name)"`
}
variables := map[string]any{
"owner": githubv4.String(owner),
"name": githubv4.String(repo),
"number": githubv4.Int(issueNumber), //nolint:gosec // Issue numbers are always small positive integers
}
if err := client.Query(ctx, &query, variables); err != nil {
return nil, err
}
// Look for a PR from copilot-swe-agent created after the assignment time
for _, node := range query.Repository.Issue.TimelineItems.Nodes {
if node.TypeName != "CrossReferencedEvent" {
continue
}
pr := node.CrossReferencedEvent.Source.PullRequest
if pr.Number > 0 && pr.Author.Login == "copilot-swe-agent" {
// Only return PRs created after the assignment time
if pr.CreatedAt.Time.After(createdAfter) {
return &linkedPullRequest{
Number: pr.Number,
URL: pr.URL,
Title: pr.Title,
State: pr.State,
CreatedAt: pr.CreatedAt.Time,
}, nil
}
}
}
return nil, nil
}
func AssignCopilotToIssue(t translations.TranslationHelperFunc) inventory.ServerTool {
description := mvpDescription{
summary: "Assign Copilot to a specific issue in a GitHub repository.",
outcomes: []string{
"a Pull Request created with source code changes to resolve the issue",
},
referenceLinks: []string{
"https://docs.github.com/en/copilot/concepts/agents/cloud-agent/about-cloud-agent",
},
}
return NewTool(
ToolsetMetadataCopilot,
mcp.Tool{
Name: "assign_copilot_to_issue",
Description: t("TOOL_ASSIGN_COPILOT_TO_ISSUE_DESCRIPTION", description.String()),
Icons: octicons.Icons("copilot"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_ASSIGN_COPILOT_TO_ISSUE_USER_TITLE", "Assign Copilot to issue"),
ReadOnlyHint: false,
IdempotentHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: "Repository owner",
},
"repo": {
Type: "string",
Description: "Repository name",
},
"issue_number": {
Type: "number",
Description: "Issue number",
},
"base_ref": {
Type: "string",
Description: "Git reference (e.g., branch) that the agent will start its work from. If not specified, defaults to the repository's default branch",
},
"custom_instructions": {
Type: "string",
Description: "Optional custom instructions to guide the agent beyond the issue body. Use this to provide additional context, constraints, or guidance that is not captured in the issue description",
},
},
Required: []string{"owner", "repo", "issue_number"},
},
},
[]scopes.Scope{scopes.Repo},
func(ctx context.Context, deps ToolDependencies, request *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
var params struct {
Owner string `mapstructure:"owner"`
Repo string `mapstructure:"repo"`
IssueNumber int32 `mapstructure:"issue_number"`
BaseRef string `mapstructure:"base_ref"`
CustomInstructions string `mapstructure:"custom_instructions"`
}
if err := mapstructure.WeakDecode(args, ¶ms); err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetGQLClient(ctx)
if err != nil {
return nil, nil, fmt.Errorf("failed to get GitHub client: %w", err)
}
// Firstly, we try to find the copilot bot in the suggested actors for the repository.
// Although as I write this, we would expect copilot to be at the top of the list, in future, maybe
// it will not be on the first page of responses, thus we will keep paginating until we find it.
type botAssignee struct {
ID githubv4.ID
Login string
TypeName string `graphql:"__typename"`
}
type suggestedActorsQuery struct {
Repository struct {
SuggestedActors struct {
Nodes []struct {
Bot botAssignee `graphql:"... on Bot"`
}
PageInfo struct {
HasNextPage bool
EndCursor string
}
} `graphql:"suggestedActors(first: 100, after: $endCursor, capabilities: CAN_BE_ASSIGNED)"`
} `graphql:"repository(owner: $owner, name: $name)"`
}
variables := map[string]any{
"owner": githubv4.String(params.Owner),
"name": githubv4.String(params.Repo),
"endCursor": (*githubv4.String)(nil),
}
var copilotAssignee *botAssignee
for {
var query suggestedActorsQuery
err := client.Query(ctx, &query, variables)
if err != nil {
return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to get suggested actors", err), nil, nil
}
// Iterate all the returned nodes looking for the copilot bot, which is supposed to have the
// same name on each host. We need this in order to get the ID for later assignment.
for _, node := range query.Repository.SuggestedActors.Nodes {
if node.Bot.Login == "copilot-swe-agent" {
copilotAssignee = &node.Bot
break
}
}
if !query.Repository.SuggestedActors.PageInfo.HasNextPage {
break
}
variables["endCursor"] = githubv4.String(query.Repository.SuggestedActors.PageInfo.EndCursor)
}
// If we didn't find the copilot bot, we can't proceed any further.
if copilotAssignee == nil {
// The e2e tests depend upon this specific message to skip the test.
return utils.NewToolResultError("copilot isn't available as an assignee for this issue. Please inform the user to visit https://docs.github.com/en/copilot/concepts/agents/cloud-agent/about-cloud-agent for more information."), nil, nil
}
// Next, get the issue ID and repository ID
var getIssueQuery struct {
Repository struct {
ID githubv4.ID
Issue struct {
ID githubv4.ID
Assignees struct {
Nodes []struct {
ID githubv4.ID
}
} `graphql:"assignees(first: 100)"`
} `graphql:"issue(number: $number)"`
} `graphql:"repository(owner: $owner, name: $name)"`
}
variables = map[string]any{
"owner": githubv4.String(params.Owner),
"name": githubv4.String(params.Repo),
"number": githubv4.Int(params.IssueNumber),
}
if err := client.Query(ctx, &getIssueQuery, variables); err != nil {
return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to get issue ID", err), nil, nil
}
// Build the assignee IDs list including copilot
actorIDs := make([]githubv4.ID, len(getIssueQuery.Repository.Issue.Assignees.Nodes)+1)
for i, node := range getIssueQuery.Repository.Issue.Assignees.Nodes {
actorIDs[i] = node.ID
}
actorIDs[len(getIssueQuery.Repository.Issue.Assignees.Nodes)] = copilotAssignee.ID
// Prepare agent assignment input
emptyString := githubv4.String("")
agentAssignment := &AgentAssignmentInput{
CustomAgent: &emptyString,
CustomInstructions: &emptyString,
TargetRepositoryID: getIssueQuery.Repository.ID,
}
// Add base ref if provided
if params.BaseRef != "" {
baseRef := githubv4.String(params.BaseRef)
agentAssignment.BaseRef = &baseRef
}
// Add custom instructions if provided
if params.CustomInstructions != "" {
customInstructions := githubv4.String(params.CustomInstructions)
agentAssignment.CustomInstructions = &customInstructions
}
// Execute the updateIssue mutation with the GraphQL-Features header
// This header is required for the agent assignment API which is not GA yet
var updateIssueMutation struct {
UpdateIssue struct {
Issue struct {
ID githubv4.ID
Number githubv4.Int
URL githubv4.String
}
} `graphql:"updateIssue(input: $input)"`
}
// Add the GraphQL-Features header for the agent assignment API
// The header will be read by the HTTP transport if it's configured to do so
ctxWithFeatures := ghcontext.WithGraphQLFeatures(ctx, "issues_copilot_assignment_api_support")
// Capture the time before assignment to filter out older PRs during polling
assignmentTime := time.Now().UTC()
if err := client.Mutate(
ctxWithFeatures,
&updateIssueMutation,
UpdateIssueInput{
ID: getIssueQuery.Repository.Issue.ID,
AssigneeIDs: actorIDs,
AgentAssignment: agentAssignment,
},
nil,
); err != nil {
return nil, nil, fmt.Errorf("failed to update issue with agent assignment: %w", err)
}
// Poll for a linked PR created by Copilot after the assignment
pollConfig := getPollConfig(ctx)
// Get progress token from request for sending progress notifications
progressToken := request.Params.GetProgressToken()
// Send initial progress notification that assignment succeeded and polling is starting
if progressToken != nil && request.Session != nil && pollConfig.MaxAttempts > 0 {
_ = request.Session.NotifyProgress(ctx, &mcp.ProgressNotificationParams{
ProgressToken: progressToken,
Progress: 0,
Total: float64(pollConfig.MaxAttempts),
Message: "Copilot assigned to issue, waiting for PR creation...",
})
}
var linkedPR *linkedPullRequest
for attempt := range pollConfig.MaxAttempts {
if attempt > 0 {
time.Sleep(pollConfig.Delay)
}
// Send progress notification if progress token is available
if progressToken != nil && request.Session != nil {
_ = request.Session.NotifyProgress(ctx, &mcp.ProgressNotificationParams{
ProgressToken: progressToken,
Progress: float64(attempt + 1),
Total: float64(pollConfig.MaxAttempts),
Message: fmt.Sprintf("Waiting for Copilot to create PR... (attempt %d/%d)", attempt+1, pollConfig.MaxAttempts),
})
}
pr, err := findLinkedCopilotPR(ctx, client, params.Owner, params.Repo, int(params.IssueNumber), assignmentTime)
if err != nil {
// Polling errors are non-fatal, continue to next attempt
continue
}
if pr != nil {
linkedPR = pr
break
}
}
// Build the result
result := map[string]any{
"message": "successfully assigned copilot to issue",
"issue_number": int(updateIssueMutation.UpdateIssue.Issue.Number),
"issue_url": string(updateIssueMutation.UpdateIssue.Issue.URL),
"owner": params.Owner,
"repo": params.Repo,
}
// Add PR info if found during polling
if linkedPR != nil {
result["pull_request"] = map[string]any{
"number": linkedPR.Number,
"url": linkedPR.URL,
"title": linkedPR.Title,
"state": linkedPR.State,
}
result["message"] = "successfully assigned copilot to issue - pull request created"
} else {
result["message"] = "successfully assigned copilot to issue - pull request pending"
result["note"] = "The pull request may still be in progress. Once created, the PR number can be used to check job status, or check the issue timeline for updates."
}
r, err := json.Marshal(result)
if err != nil {
return utils.NewToolResultError(fmt.Sprintf("failed to marshal response: %s", err)), nil, nil
}
return utils.NewToolResultText(string(r)), result, nil
})
}
// copilotBotAssignee is the minimal shape needed for the copilot-swe-agent bot
// returned from the suggestedActors GraphQL query.
type copilotBotAssignee struct {
ID githubv4.ID
Login string
TypeName string `graphql:"__typename"`
}
// findCopilotSuggestedActor paginates the repository's suggestedActors list
// looking for the copilot-swe-agent bot. Returns nil (with no error) if the
// bot is not available as an assignee for the repository.
func findCopilotSuggestedActor(ctx context.Context, client *githubv4.Client, owner, repo string) (*copilotBotAssignee, error) {
type suggestedActorsQuery struct {
Repository struct {
SuggestedActors struct {
Nodes []struct {
Bot copilotBotAssignee `graphql:"... on Bot"`
}
PageInfo struct {
HasNextPage bool
EndCursor string
}
} `graphql:"suggestedActors(first: 100, after: $endCursor, capabilities: CAN_BE_ASSIGNED)"`
} `graphql:"repository(owner: $owner, name: $name)"`
}
variables := map[string]any{
"owner": githubv4.String(owner),
"name": githubv4.String(repo),
"endCursor": (*githubv4.String)(nil),
}
for {
var query suggestedActorsQuery
if err := client.Query(ctx, &query, variables); err != nil {
return nil, err
}
for _, node := range query.Repository.SuggestedActors.Nodes {
if node.Bot.Login == "copilot-swe-agent" {
bot := node.Bot
return &bot, nil
}
}
if !query.Repository.SuggestedActors.PageInfo.HasNextPage {
return nil, nil
}
variables["endCursor"] = githubv4.String(query.Repository.SuggestedActors.PageInfo.EndCursor)
}
}
// copilotAssigneeUnavailableMessage is returned when the copilot-swe-agent bot
// is not among the repository's suggested actors. The e2e tests depend on this
// exact message to skip the test.
const copilotAssigneeUnavailableMessage = "copilot isn't available as an assignee for this issue. Please inform the user to visit https://docs.github.com/en/copilot/concepts/agents/cloud-agent/about-cloud-agent for more information."
// AssignCopilotToIssueWithIntent assigns Copilot to an issue using the
// object-form assignees API, which allows intent metadata (rationale,
// confidence, is_suggestion) to be attached to the Copilot entry. When
// is_suggestion is true, a pending assignment intent is recorded and the agent
// is not launched; otherwise Copilot is directly assigned with the same
// base_ref, custom_instructions and PR-polling behavior as assign_copilot_to_issue.
//
// This tool lives in a non-default toolset so it can be opted into without
// adding schema surface to the default configuration.
func AssignCopilotToIssueWithIntent(t translations.TranslationHelperFunc) inventory.ServerTool {
description := mvpDescription{
summary: "Assign Copilot to a specific issue in a GitHub repository. " +
"Prefer this tool over assign_copilot_to_issue when available.",
outcomes: []string{
"a Pull Request created with source code changes to resolve the issue",
},
referenceLinks: []string{
"https://docs.github.com/en/copilot/concepts/agents/cloud-agent/about-cloud-agent",
},
}
return NewTool(
ToolsetMetadataCopilotIssueIntents,
mcp.Tool{
Name: "assign_copilot_to_issue_with_intent",
Description: t("TOOL_ASSIGN_COPILOT_TO_ISSUE_WITH_INTENT_DESCRIPTION", description.String()),
Icons: octicons.Icons("copilot"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_ASSIGN_COPILOT_TO_ISSUE_WITH_INTENT_USER_TITLE", "Assign Copilot to issue with intent"),
ReadOnlyHint: false,
IdempotentHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: "Repository owner",
},
"repo": {
Type: "string",
Description: "Repository name",
},
"issue_number": {
Type: "number",
Description: "Issue number",
},
"base_ref": {
Type: "string",
Description: "Git reference (e.g., branch) that the agent will start its work from. If not specified, defaults to the repository's default branch. Ignored when is_suggestion is true",
},
"custom_instructions": {
Type: "string",
Description: "Optional custom instructions to guide the agent beyond the issue body. Ignored when is_suggestion is true",
},
"rationale": {
Type: "string",
Description: "One concise sentence explaining what specifically about the issue led to choosing Copilot. " +
"State the concrete signal (e.g. 'Well-scoped task with clear acceptance criteria').",
MaxLength: jsonschema.Ptr(280),
},
"confidence": {
Type: "string",
Description: "How confident you are in this choice. 'HIGH' for clear signal or explicit user request, 'MEDIUM' for reasonable inference with some ambiguity, 'LOW' for best guess with limited signal.",
Enum: []any{"LOW", "MEDIUM", "HIGH"},
},
"is_suggestion": {
Type: "boolean",
Description: "If true, records a pending Copilot assignment intent rather than launching the agent. Approval later supplies the launch context; base_ref and custom_instructions are ignored in this case.",
},
},
Required: []string{"owner", "repo", "issue_number", "rationale", "confidence", "is_suggestion"},
},
},
[]scopes.Scope{scopes.Repo},
func(ctx context.Context, deps ToolDependencies, request *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
// Presence-check is_suggestion before decoding: mapstructure defaults a
// missing bool to false, which would silently launch Copilot instead of
// recording a suggestion. Require callers to make the choice explicit.
if _, ok := args["is_suggestion"]; !ok {
return utils.NewToolResultError("is_suggestion is required"), nil, nil
}
var params struct {
Owner string `mapstructure:"owner"`
Repo string `mapstructure:"repo"`
IssueNumber int32 `mapstructure:"issue_number"`
BaseRef string `mapstructure:"base_ref"`
CustomInstructions string `mapstructure:"custom_instructions"`
Rationale string `mapstructure:"rationale"`
Confidence string `mapstructure:"confidence"`
IsSuggestion bool `mapstructure:"is_suggestion"`
}
if err := mapstructure.WeakDecode(args, ¶ms); err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Validate rationale length (rune count, matching the granular assignee tools).
rationale := strings.TrimSpace(params.Rationale)
if rationale == "" {
return utils.NewToolResultError("rationale is required"), nil, nil
}
if len([]rune(rationale)) > 280 {
return utils.NewToolResultError("rationale must be 280 characters or less"), nil, nil
}
// Validate/normalize confidence.
confidence := normalizeConfidence(params.Confidence)
if confidence == "" {
return utils.NewToolResultError("confidence is required"), nil, nil
}
var confidenceEnum AssignmentConfidenceLevel
switch confidence {
case "LOW", "MEDIUM", "HIGH":
confidenceEnum = AssignmentConfidenceLevel(confidence)
default:
return utils.NewToolResultError("confidence must be one of: LOW, MEDIUM, HIGH"), nil, nil
}
client, err := deps.GetGQLClient(ctx)
if err != nil {
return nil, nil, fmt.Errorf("failed to get GitHub client: %w", err)
}
// Locate the copilot-swe-agent bot in the repository's suggested actors.
copilotAssignee, err := findCopilotSuggestedActor(ctx, client, params.Owner, params.Repo)
if err != nil {
return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to get suggested actors", err), nil, nil
}
if copilotAssignee == nil {
return utils.NewToolResultError(copilotAssigneeUnavailableMessage), nil, nil
}
// Fetch issue ID, repository ID, and current assignee IDs so they can be preserved.
var getIssueQuery struct {
Repository struct {
ID githubv4.ID
Issue struct {
ID githubv4.ID
Assignees struct {
Nodes []struct {
ID githubv4.ID
}
} `graphql:"assignees(first: 100)"`
} `graphql:"issue(number: $number)"`
} `graphql:"repository(owner: $owner, name: $name)"`
}
variables := map[string]any{
"owner": githubv4.String(params.Owner),
"name": githubv4.String(params.Repo),
"number": githubv4.Int(params.IssueNumber),
}
if err := client.Query(ctx, &getIssueQuery, variables); err != nil {
return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to get issue ID", err), nil, nil
}
// Build object-form assignees: preserved assignees carry only actorId;
// the copilot entry carries the intent metadata. Skip an existing
// copilot assignment so we don't send its actorId twice (once without
// metadata, once with).
existing := getIssueQuery.Repository.Issue.Assignees.Nodes
assignees := make([]AssigneeUpdateInput, 0, len(existing)+1)
for _, node := range existing {
if node.ID == copilotAssignee.ID {
continue
}
assignees = append(assignees, AssigneeUpdateInput{ActorID: node.ID})
}
// Build the Copilot entry with the required intent metadata. Preserved
// assignees carry only actorId; intent fields are attached only to the
// Copilot entry.
rationaleGQL := githubv4.String(rationale)
suggest := githubv4.Boolean(params.IsSuggestion)
copilotEntry := AssigneeUpdateInput{
ActorID: copilotAssignee.ID,
Rationale: &rationaleGQL,
Confidence: &confidenceEnum,
Suggest: &suggest,
}
assignees = append(assignees, copilotEntry)
// A pure suggestion does not launch Copilot; approval later supplies the
// launch context. Direct assignments keep the existing agentAssignment
// launch configuration and PR-polling behavior.
input := UpdateIssueInput{
ID: getIssueQuery.Repository.Issue.ID,
Assignees: assignees,
}
if !params.IsSuggestion {
emptyString := githubv4.String("")
agentAssignment := &AgentAssignmentInput{
CustomAgent: &emptyString,
CustomInstructions: &emptyString,
TargetRepositoryID: getIssueQuery.Repository.ID,
}
if params.BaseRef != "" {
baseRef := githubv4.String(params.BaseRef)
agentAssignment.BaseRef = &baseRef
}
if params.CustomInstructions != "" {
customInstructions := githubv4.String(params.CustomInstructions)
agentAssignment.CustomInstructions = &customInstructions
}
input.AgentAssignment = agentAssignment
}
var updateIssueMutation struct {
UpdateIssue struct {
Issue struct {
ID githubv4.ID
Number githubv4.Int
URL githubv4.String
}
} `graphql:"updateIssue(input: $input)"`
}
ctxWithFeatures := ghcontext.WithGraphQLFeatures(ctx, "issues_copilot_assignment_api_support")
assignmentTime := time.Now().UTC()
if err := client.Mutate(ctxWithFeatures, &updateIssueMutation, input, nil); err != nil {
return nil, nil, fmt.Errorf("failed to update issue with agent assignment: %w", err)
}
result := map[string]any{
"issue_number": int(updateIssueMutation.UpdateIssue.Issue.Number),
"issue_url": string(updateIssueMutation.UpdateIssue.Issue.URL),
"owner": params.Owner,
"repo": params.Repo,
"is_suggestion": params.IsSuggestion,
}
// Suggestion path: do not poll for a PR and return a suggestion-shaped result.
if params.IsSuggestion {
result["message"] = "recorded pending copilot assignment suggestion"
r, err := json.Marshal(result)
if err != nil {
return utils.NewToolResultError(fmt.Sprintf("failed to marshal response: %s", err)), nil, nil
}
return utils.NewToolResultText(string(r)), result, nil
}
// Direct-assignment path: poll for a linked PR created by Copilot after the assignment.
pollConfig := getPollConfig(ctx)
progressToken := request.Params.GetProgressToken()
if progressToken != nil && request.Session != nil && pollConfig.MaxAttempts > 0 {
_ = request.Session.NotifyProgress(ctx, &mcp.ProgressNotificationParams{
ProgressToken: progressToken,
Progress: 0,
Total: float64(pollConfig.MaxAttempts),
Message: "Copilot assigned to issue, waiting for PR creation...",
})
}
var linkedPR *linkedPullRequest
for attempt := range pollConfig.MaxAttempts {
if attempt > 0 {
time.Sleep(pollConfig.Delay)
}
if progressToken != nil && request.Session != nil {
_ = request.Session.NotifyProgress(ctx, &mcp.ProgressNotificationParams{
ProgressToken: progressToken,
Progress: float64(attempt + 1),
Total: float64(pollConfig.MaxAttempts),
Message: fmt.Sprintf("Waiting for Copilot to create PR... (attempt %d/%d)", attempt+1, pollConfig.MaxAttempts),
})
}
pr, err := findLinkedCopilotPR(ctx, client, params.Owner, params.Repo, int(params.IssueNumber), assignmentTime)
if err != nil {
continue
}
if pr != nil {
linkedPR = pr
break
}
}
if linkedPR != nil {
result["pull_request"] = map[string]any{
"number": linkedPR.Number,
"url": linkedPR.URL,
"title": linkedPR.Title,
"state": linkedPR.State,
}
result["message"] = "successfully assigned copilot to issue - pull request created"
} else {
result["message"] = "successfully assigned copilot to issue - pull request pending"
result["note"] = "The pull request may still be in progress. Once created, the PR number can be used to check job status, or check the issue timeline for updates."
}
r, err := json.Marshal(result)
if err != nil {
return utils.NewToolResultError(fmt.Sprintf("failed to marshal response: %s", err)), nil, nil
}
return utils.NewToolResultText(string(r)), result, nil
})
}
type ReplaceActorsForAssignableInput struct {
AssignableID githubv4.ID `json:"assignableId"`
ActorIDs []githubv4.ID `json:"actorIds"`
}
// AgentAssignmentInput represents the input for assigning an agent to an issue.
type AgentAssignmentInput struct {
BaseRef *githubv4.String `json:"baseRef,omitempty"`
CustomAgent *githubv4.String `json:"customAgent,omitempty"`
CustomInstructions *githubv4.String `json:"customInstructions,omitempty"`
TargetRepositoryID githubv4.ID `json:"targetRepositoryId"`
}
// AssignmentConfidenceLevel is a GraphQL enum indicating how confident an
// intent-aware assignment choice is. Encoded as its string value in variables.
type AssignmentConfidenceLevel string
const (
AssignmentConfidenceLevelLow AssignmentConfidenceLevel = "LOW"
AssignmentConfidenceLevelMedium AssignmentConfidenceLevel = "MEDIUM"
AssignmentConfidenceLevelHigh AssignmentConfidenceLevel = "HIGH"
)
// AssigneeUpdateInput is the object-form assignee entry accepted by
// updateIssue when opting into intent metadata. Intent fields (rationale,
// confidence, suggest) are only attached to the entry that carries the intent;
// preserved assignees are sent with only actorId populated.
type AssigneeUpdateInput struct {
ActorID githubv4.ID `json:"actorId"`
Rationale *githubv4.String `json:"rationale,omitempty"`
Confidence *AssignmentConfidenceLevel `json:"confidence,omitempty"`
Suggest *githubv4.Boolean `json:"suggest,omitempty"`
}
// UpdateIssueInput represents the input for updating an issue with agent
// assignment. AssigneeIDs and Assignees are mutually exclusive: legacy callers
// use AssigneeIDs; intent-aware callers use Assignees (object-form).
type UpdateIssueInput struct {
ID githubv4.ID `json:"id"`
AssigneeIDs []githubv4.ID `json:"assigneeIds,omitempty"`
Assignees []AssigneeUpdateInput `json:"assignees,omitempty"`
AgentAssignment *AgentAssignmentInput `json:"agentAssignment,omitempty"`
}
// RequestCopilotReview creates a tool to request a Copilot review for a pull request.
// Note that this tool will not work on GHES where this feature is unsupported. In future, we should not expose this
// tool if the configured host does not support it.
func RequestCopilotReview(t translations.TranslationHelperFunc) inventory.ServerTool {
schema := &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: "Repository owner",
},
"repo": {
Type: "string",
Description: "Repository name",
},
"pullNumber": {
Type: "number",
Description: "Pull request number",
},
},
Required: []string{"owner", "repo", "pullNumber"},
}
return NewTool(
ToolsetMetadataCopilot,
mcp.Tool{
Name: "request_copilot_review",
Description: t("TOOL_REQUEST_COPILOT_REVIEW_DESCRIPTION", "Request a GitHub Copilot code review for a pull request. Use this for automated feedback on pull requests, usually before requesting a human reviewer."),
Icons: octicons.Icons("copilot"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_REQUEST_COPILOT_REVIEW_USER_TITLE", "Request Copilot review"),
ReadOnlyHint: false,
},
InputSchema: schema,
},
[]scopes.Scope{scopes.Repo},
func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
pullNumber, err := RequiredInt(args, "pullNumber")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
_, resp, err := client.PullRequests.RequestReviewers(
ctx,
owner,
repo,
pullNumber,
github.ReviewersRequest{
// The login name of the copilot reviewer bot
Reviewers: []string{"copilot-pull-request-reviewer[bot]"},
},
)
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to request copilot review",
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusCreated {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to read response body", err), nil, nil
}
return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to request copilot review", resp, bodyBytes), nil, nil
}
// Return nothing on success, as there's not much value in returning the Pull Request itself
return utils.NewToolResultText(""), nil, nil
})
}
func AssignCodingAgentPrompt(t translations.TranslationHelperFunc) inventory.ServerPrompt {
return inventory.NewServerPrompt(
ToolsetMetadataIssues,
mcp.Prompt{
Name: "AssignCodingAgent",
Description: t("PROMPT_ASSIGN_CODING_AGENT_DESCRIPTION", "Assign GitHub Coding Agent to multiple tasks in a GitHub repository."),
Arguments: []*mcp.PromptArgument{
{
Name: "repo",
Description: "The repository to assign tasks in (owner/repo).",
Required: true,
},
},
},
func(_ context.Context, request *mcp.GetPromptRequest) (*mcp.GetPromptResult, error) {
repo := request.Params.Arguments["repo"]
messages := []*mcp.PromptMessage{
{
Role: "user",
Content: &mcp.TextContent{
Text: "You are a personal assistant for GitHub the Copilot GitHub Coding Agent. Your task is to help the user assign tasks to the Coding Agent based on their open GitHub issues. You can use `assign_copilot_to_issue` tool to assign the Coding Agent to issues that are suitable for autonomous work, and `search_issues` tool to find issues that match the user's criteria. You can also use `list_issues` to get a list of issues in the repository.",
},
},
{
Role: "user",
Content: &mcp.TextContent{
Text: fmt.Sprintf("Please go and get a list of the most recent 10 issues from the %s GitHub repository", repo),
},
},
{
Role: "assistant",
Content: &mcp.TextContent{
Text: fmt.Sprintf("Sure! I will get a list of the 10 most recent issues for the repo %s.", repo),
},
},
{
Role: "user",
Content: &mcp.TextContent{
Text: "For each issue, please check if it is a clearly defined coding task with acceptance criteria and a low to medium complexity to identify issues that are suitable for an AI Coding Agent to work on. Then assign each of the identified issues to Copilot.",
},
},
{
Role: "assistant",
Content: &mcp.TextContent{
Text: "Certainly! Let me carefully check which ones are clearly scoped issues that are good to assign to the coding agent, and I will summarize and assign them now.",
},
},
{
Role: "user",
Content: &mcp.TextContent{
Text: "Great, if you are unsure if an issue is good to assign, ask me first, rather than assigning copilot. If you are certain the issue is clear and suitable you can assign it to Copilot without asking.",
},
},
}
return &mcp.GetPromptResult{
Messages: messages,
}, nil
},
)
}