diff --git a/docs/feature-flags.md b/docs/feature-flags.md index f19886f1be..50f340c4c5 100644 --- a/docs/feature-flags.md +++ b/docs/feature-flags.md @@ -286,7 +286,8 @@ as output formatting) won't appear here. - **update_issue_labels** - Update Issue Labels - **OAuth Challenge Scopes**: `repo` - `issue_number`: The issue number to update (number, required) - - `labels`: Labels to apply to this issue. ([], required) + - `labels`: Labels to apply to this issue. For 'add' and 'remove', only each label's name is used; 'rationale', 'confidence', and 'is_suggestion' are only honored when method is 'replace'. ([], required) + - `method`: How to apply the labels: 'replace' (default) sets the issue's labels to exactly the provided list, 'add' adds them while keeping the existing labels, and 'remove' removes the named labels without affecting the others. (string, optional) - `owner`: Repository owner (username or organization) (string, required) - `repo`: Repository name (string, required) diff --git a/pkg/github/__toolsnaps__/update_issue_labels.snap b/pkg/github/__toolsnaps__/update_issue_labels.snap index c0cfa73ad8..e5ba30f3e6 100644 --- a/pkg/github/__toolsnaps__/update_issue_labels.snap +++ b/pkg/github/__toolsnaps__/update_issue_labels.snap @@ -1,12 +1,12 @@ { "annotations": { - "destructiveHint": false, + "destructiveHint": true, "idempotentHint": false, "openWorldHint": true, "readOnlyHint": false, "title": "Update Issue Labels" }, - "description": "Update the labels of an existing issue. This replaces the current labels with the provided list. When setting values, include a confidence level (LOW, MEDIUM, or HIGH) reflecting how certain you are about the choice.", + "description": "Update the labels of an existing issue. With method 'replace' (default) this replaces the current labels with the provided list; use 'add' to add labels while keeping the existing ones, or 'remove' to remove specific labels without touching the rest. Returns the issue's labels after the update. When setting values, include a confidence level (LOW, MEDIUM, or HIGH) reflecting how certain you are about the choice.", "icons": [ { "mimeType": "image/png", @@ -27,7 +27,7 @@ "type": "number" }, "labels": { - "description": "Labels to apply to this issue.", + "description": "Labels to apply to this issue. For 'add' and 'remove', only each label's name is used; 'rationale', 'confidence', and 'is_suggestion' are only honored when method is 'replace'.", "items": { "oneOf": [ { @@ -68,6 +68,16 @@ }, "type": "array" }, + "method": { + "default": "replace", + "description": "How to apply the labels: 'replace' (default) sets the issue's labels to exactly the provided list, 'add' adds them while keeping the existing labels, and 'remove' removes the named labels without affecting the others.", + "enum": [ + "replace", + "add", + "remove" + ], + "type": "string" + }, "owner": { "description": "Repository owner (username or organization)", "type": "string", @@ -94,13 +104,23 @@ "id": { "type": "string" }, + "labels": { + "items": { + "type": "string" + }, + "type": [ + "null", + "array" + ] + }, "url": { "type": "string" } }, "required": [ "id", - "url" + "url", + "labels" ], "type": [ "null", diff --git a/pkg/github/granular_issue_types.go b/pkg/github/granular_issue_types.go index c0b9f2e16d..5b72dcc9f3 100644 --- a/pkg/github/granular_issue_types.go +++ b/pkg/github/granular_issue_types.go @@ -106,11 +106,24 @@ type GranularIssueAssigneesInput struct { Assignees []GranularIssueAssignee `json:"assignees"` } +const ( + issueLabelsMethodReplace = "replace" + issueLabelsMethodAdd = "add" + issueLabelsMethodRemove = "remove" +) + type GranularIssueLabelsInput struct { GranularIssueCoordinate + Method string `json:"method,omitempty"` Labels []GranularIssueLabel `json:"labels"` } +type GranularIssueLabelsResponse struct { + ID string `json:"id"` + URL string `json:"url"` + Labels []string `json:"labels"` +} + type GranularIssueTypeInput struct { GranularIssueCoordinate IssueType *string `json:"issue_type"` @@ -574,16 +587,36 @@ func normalizeGranularUpdateIssueLabelsArguments(raw json.RawMessage) (json.RawM } } + method, err := OptionalParam[string](args, "method") + if err != nil { + return nil, err + } + method = strings.ToLower(strings.TrimSpace(method)) + if method == "" { + method = issueLabelsMethodReplace + } + if method != issueLabelsMethodReplace && method != issueLabelsMethodAdd && method != issueLabelsMethodRemove { + return nil, fmt.Errorf("method must be one of: replace, add, remove") + } + payload := make([]GranularIssueLabel, 0, len(labelsSlice)) for _, item := range labelsSlice { switch v := item.(type) { case string: - payload = append(payload, GranularIssueLabel{Name: v, StringForm: true}) + name := strings.TrimSpace(v) + if name == "" { + return nil, fmt.Errorf("label name cannot be empty") + } + payload = append(payload, GranularIssueLabel{Name: name, StringForm: true}) case map[string]any: name, err := RequiredParam[string](v, "name") if err != nil { return nil, fmt.Errorf("each label object must have a 'name' string") } + name = strings.TrimSpace(name) + if name == "" { + return nil, fmt.Errorf("label name cannot be empty") + } rationale, err := OptionalParam[string](v, "rationale") if err != nil { return nil, err @@ -615,7 +648,29 @@ func normalizeGranularUpdateIssueLabelsArguments(raw json.RawMessage) (json.RawM } } - return marshalGranularIssueArguments(args, GranularIssueLabelsInput{Owner: owner, Repo: repo, IssueNumber: issueNumber, Labels: payload}) + if method != issueLabelsMethodReplace { + payload = uniqueLabelNames(payload) + if len(payload) == 0 { + return nil, fmt.Errorf("at least one label is required") + } + } + + return marshalGranularIssueArguments(args, GranularIssueLabelsInput{Owner: owner, Repo: repo, IssueNumber: issueNumber, Method: method, Labels: payload}) +} + +// uniqueLabelNames drops intent fields and duplicate names, since the add and +// remove endpoints accept only names. +func uniqueLabelNames(labels []GranularIssueLabel) []GranularIssueLabel { + seen := make(map[string]struct{}, len(labels)) + unique := make([]GranularIssueLabel, 0, len(labels)) + for _, label := range labels { + if _, ok := seen[label.Name]; ok { + continue + } + seen[label.Name] = struct{}{} + unique = append(unique, GranularIssueLabel{Name: label.Name, StringForm: true}) + } + return unique } func normalizeGranularUpdateIssueTypeArguments(raw json.RawMessage) (json.RawMessage, error) { diff --git a/pkg/github/granular_tools_test.go b/pkg/github/granular_tools_test.go index 460a192766..97988cab5b 100644 --- a/pkg/github/granular_tools_test.go +++ b/pkg/github/granular_tools_test.go @@ -3,6 +3,7 @@ package github import ( "context" "encoding/json" + "fmt" "maps" "net/http" "strings" @@ -15,6 +16,7 @@ import ( "github.com/github/github-mcp-server/v2/pkg/inventory" "github.com/github/github-mcp-server/v2/pkg/translations" gogithub "github.com/google/go-github/v92/github" + "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -2764,3 +2766,200 @@ func TestGranularRemovePullRequestReviewCommentReaction(t *testing.T) { }) } } + +func labelsIssue(names ...string) *gogithub.Issue { + labels := make([]*gogithub.Label, len(names)) + for i, name := range names { + labels[i] = &gogithub.Label{Name: name} + } + return &gogithub.Issue{ + ID: new(int64(42)), + Number: new(1), + HTMLURL: new("https://github.com/owner/repo/issues/1"), + Labels: labels, + } +} + +func callUpdateIssueLabels(t *testing.T, httpClient *http.Client, args map[string]any) *mcp.CallToolResult { + t.Helper() + deps := BaseDeps{Client: mustNewGHClient(t, httpClient)} + serverTool := GranularUpdateIssueLabels(translations.NullTranslationHelper) + handler := serverTool.Handler(deps) + request := createMCPRequest(args) + result, err := handler(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + return result +} + +func labelsArgs(method string, labels ...any) map[string]any { + if labels == nil { + labels = []any{} + } + args := map[string]any{ + "owner": "owner", + "repo": "repo", + "issue_number": float64(1), + "labels": labels, + } + if method != "" { + args["method"] = method + } + return args +} + +func decodeLabelsResponse(t *testing.T, result *mcp.CallToolResult) GranularIssueLabelsResponse { + t.Helper() + require.False(t, result.IsError, "unexpected error: %v", result.Content) + var out GranularIssueLabelsResponse + require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &out)) + return out +} + +func TestGranularUpdateIssueLabelsReplace(t *testing.T) { + t.Run("omitted method defaults to replace and returns id, url and labels", func(t *testing.T) { + result := callUpdateIssueLabels(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + PatchReposIssuesByOwnerByRepoByIssueNumber: expectRequestBody(t, map[string]any{"labels": []any{"bug", "enhancement"}}). + andThen(mockResponse(t, http.StatusOK, labelsIssue("bug", "enhancement"))), + }), labelsArgs("", "bug", "enhancement")) + + out := decodeLabelsResponse(t, result) + assert.Equal(t, "42", out.ID) + assert.Equal(t, "https://github.com/owner/repo/issues/1", out.URL) + assert.Equal(t, []string{"bug", "enhancement"}, out.Labels) + }) + + t.Run("label names are trimmed", func(t *testing.T) { + result := callUpdateIssueLabels(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + PatchReposIssuesByOwnerByRepoByIssueNumber: expectRequestBody(t, map[string]any{"labels": []any{"bug", "enhancement"}}). + andThen(mockResponse(t, http.StatusOK, labelsIssue("bug", "enhancement"))), + }), labelsArgs("replace", " bug ", map[string]any{"name": " enhancement "})) + assert.False(t, result.IsError) + }) + + t.Run("empty list clears all labels", func(t *testing.T) { + result := callUpdateIssueLabels(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + PatchReposIssuesByOwnerByRepoByIssueNumber: expectRequestBody(t, map[string]any{"labels": []any{}}). + andThen(mockResponse(t, http.StatusOK, labelsIssue())), + }), labelsArgs("replace")) + assert.Equal(t, []string{}, decodeLabelsResponse(t, result).Labels) + }) + + for _, labels := range [][]any{{" "}, {map[string]any{"name": " "}}} { + t.Run(fmt.Sprintf("whitespace-only name rejected: %v", labels), func(t *testing.T) { + result := callUpdateIssueLabels(t, MockHTTPClientWithHandlers(nil), labelsArgs("replace", labels...)) + assert.Contains(t, getErrorResult(t, result).Text, "label name cannot be empty") + }) + } +} + +func TestGranularUpdateIssueLabelsAdd(t *testing.T) { + t.Run("adds labels without replacing existing ones", func(t *testing.T) { + result := callUpdateIssueLabels(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + PostReposIssuesLabelsByOwnerByRepoByIssueNumber: expectRequestBody(t, []any{"enhancement"}). + andThen(mockResponse(t, http.StatusOK, []*gogithub.Label{{Name: "bug"}, {Name: "enhancement"}})), + GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, labelsIssue("bug", "enhancement")), + }), labelsArgs("add", "enhancement")) + + out := decodeLabelsResponse(t, result) + assert.Equal(t, "42", out.ID) + assert.Equal(t, []string{"bug", "enhancement"}, out.Labels) + }) + + t.Run("uses only the name of label objects and de-duplicates", func(t *testing.T) { + result := callUpdateIssueLabels(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + PostReposIssuesLabelsByOwnerByRepoByIssueNumber: expectRequestBody(t, []any{"enhancement"}). + andThen(mockResponse(t, http.StatusOK, []*gogithub.Label{{Name: "enhancement"}})), + GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, labelsIssue("enhancement")), + }), labelsArgs("add", + map[string]any{"name": "enhancement", "rationale": "ignored for add"}, + "enhancement", " enhancement ")) + assert.False(t, result.IsError) + }) + + t.Run("method is trimmed and case-folded", func(t *testing.T) { + result := callUpdateIssueLabels(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + PostReposIssuesLabelsByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, []*gogithub.Label{{Name: "bug"}}), + GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, labelsIssue("bug")), + }), labelsArgs(" ADD ", "bug")) + assert.False(t, result.IsError) + }) + + t.Run("requires at least one label", func(t *testing.T) { + result := callUpdateIssueLabels(t, MockHTTPClientWithHandlers(nil), labelsArgs("add")) + assert.Contains(t, getErrorResult(t, result).Text, "at least one label is required") + }) +} + +func TestGranularUpdateIssueLabelsRemove(t *testing.T) { + t.Run("removes a label and returns the remaining labels", func(t *testing.T) { + result := callUpdateIssueLabels(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + DeleteReposIssuesLabelsByOwnerByRepoByIssueNumberByName: mockResponse(t, http.StatusOK, []*gogithub.Label{{Name: "enhancement"}}), + GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, labelsIssue("enhancement")), + }), labelsArgs("remove", "bug")) + assert.Equal(t, []string{"enhancement"}, decodeLabelsResponse(t, result).Labels) + }) + + t.Run("de-duplicates labels before issuing deletes", func(t *testing.T) { + var deleteCount int + result := callUpdateIssueLabels(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + DeleteReposIssuesLabelsByOwnerByRepoByIssueNumberByName: func(w http.ResponseWriter, r *http.Request) { + deleteCount++ + mockResponse(t, http.StatusOK, []*gogithub.Label{})(w, r) + }, + GetReposIssuesByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, labelsIssue()), + }), labelsArgs("remove", "bug", "bug", " bug ")) + require.False(t, result.IsError) + assert.Equal(t, 1, deleteCount, "duplicate labels should collapse to a single DELETE") + }) + + for _, tc := range []struct{ label, wantPath string }{ + {"good first issue", "labels/good%20first%20issue"}, + {"status/blocked", "labels/status%2Fblocked"}, + } { + t.Run("escapes label name in path: "+tc.label, func(t *testing.T) { + // Catch-all handler: the keyed router matches decoded paths, where %2F becomes a separator. + var deletePath string + result := callUpdateIssueLabels(t, MockHTTPClientWithHandler(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodDelete { + deletePath = r.URL.EscapedPath() + mockResponse(t, http.StatusOK, []*gogithub.Label{})(w, r) + return + } + mockResponse(t, http.StatusOK, labelsIssue())(w, r) + }), labelsArgs("remove", tc.label)) + require.False(t, result.IsError) + assert.True(t, strings.HasSuffix(deletePath, tc.wantPath), "got path %q", deletePath) + }) + } + + t.Run("surfaces API error and reports labels already removed", func(t *testing.T) { + result := callUpdateIssueLabels(t, MockHTTPClientWithHandler(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/labels/missing") { + mockResponse(t, http.StatusNotFound, map[string]any{"message": "Label does not exist"})(w, r) + return + } + mockResponse(t, http.StatusOK, []*gogithub.Label{})(w, r) + }), labelsArgs("remove", "bug", "missing")) + text := getErrorResult(t, result).Text + assert.Contains(t, text, `failed to remove label "missing" from issue`) + assert.Contains(t, text, "already removed: bug") + }) + + t.Run("rejects whitespace-only label names", func(t *testing.T) { + result := callUpdateIssueLabels(t, MockHTTPClientWithHandlers(nil), labelsArgs("remove", " ")) + assert.Contains(t, getErrorResult(t, result).Text, "label name cannot be empty") + }) +} + +func TestGranularUpdateIssueLabelsInvalidMethod(t *testing.T) { + result := callUpdateIssueLabels(t, MockHTTPClientWithHandlers(nil), labelsArgs("toggle", "bug")) + assert.Contains(t, getErrorResult(t, result).Text, "method must be one of: replace, add, remove") +} + +func TestGranularUpdateIssueLabelsIsDestructive(t *testing.T) { + tool := GranularUpdateIssueLabels(translations.NullTranslationHelper).Tool + require.NotNil(t, tool.Annotations) + require.NotNil(t, tool.Annotations.DestructiveHint) + assert.True(t, *tool.Annotations.DestructiveHint) + assert.Contains(t, tool.Description, "replaces") +} diff --git a/pkg/github/helper_test.go b/pkg/github/helper_test.go index 80a2e523f2..cdc06f9383 100644 --- a/pkg/github/helper_test.go +++ b/pkg/github/helper_test.go @@ -68,6 +68,8 @@ const ( PostReposIssuesReactionsByOwnerByRepoByIssueNumber = "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" DeleteReposIssuesReactionsByOwnerByRepoByIssueNumber = "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" PatchReposIssuesByOwnerByRepoByIssueNumber = "PATCH /repos/{owner}/{repo}/issues/{issue_number}" + PostReposIssuesLabelsByOwnerByRepoByIssueNumber = "POST /repos/{owner}/{repo}/issues/{issue_number}/labels" + DeleteReposIssuesLabelsByOwnerByRepoByIssueNumberByName = "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" GetReposIssuesSubIssuesByOwnerByRepoByIssueNumber = "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" PostReposIssuesSubIssuesByOwnerByRepoByIssueNumber = "POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" DeleteReposIssuesSubIssueByOwnerByRepoByIssueNumber = "DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue" diff --git a/pkg/github/issues_granular.go b/pkg/github/issues_granular.go index eab4a204cd..2235b10b64 100644 --- a/pkg/github/issues_granular.go +++ b/pkg/github/issues_granular.go @@ -2,12 +2,15 @@ package github import ( "context" + "encoding/json" "fmt" "maps" + "net/url" "strings" ghcontext "github.com/github/github-mcp-server/v2/pkg/context" ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/ifc" "github.com/github/github-mcp-server/v2/pkg/inventory" "github.com/github/github-mcp-server/v2/pkg/scopes" "github.com/github/github-mcp-server/v2/pkg/translations" @@ -362,15 +365,15 @@ type assigneesUpdateRequest struct { // GranularUpdateIssueLabels creates a tool to update an issue's labels. func GranularUpdateIssueLabels(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool[GranularIssueLabelsInput, *MinimalResponse]( + st := NewTool[GranularIssueLabelsInput, *GranularIssueLabelsResponse]( ToolsetMetadataIssues, mcp.Tool{ Name: "update_issue_labels", - Description: t("TOOL_UPDATE_ISSUE_LABELS_DESCRIPTION", "Update the labels of an existing issue. This replaces the current labels with the provided list. When setting values, include a confidence level (LOW, MEDIUM, or HIGH) reflecting how certain you are about the choice."), + Description: t("TOOL_UPDATE_ISSUE_LABELS_DESCRIPTION", "Update the labels of an existing issue. With method 'replace' (default) this replaces the current labels with the provided list; use 'add' to add labels while keeping the existing ones, or 'remove' to remove specific labels without touching the rest. Returns the issue's labels after the update. When setting values, include a confidence level (LOW, MEDIUM, or HIGH) reflecting how certain you are about the choice."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_UPDATE_ISSUE_LABELS_USER_TITLE", "Update Issue Labels"), ReadOnlyHint: false, - DestructiveHint: new(false), + DestructiveHint: new(true), OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ @@ -389,9 +392,15 @@ func GranularUpdateIssueLabels(t translations.TranslationHelperFunc) inventory.S Description: "The issue number to update", Minimum: new(1.0), }, + "method": { + Type: "string", + Description: "How to apply the labels: 'replace' (default) sets the issue's labels to exactly the provided list, 'add' adds them while keeping the existing labels, and 'remove' removes the named labels without affecting the others.", + Enum: []any{issueLabelsMethodReplace, issueLabelsMethodAdd, issueLabelsMethodRemove}, + Default: json.RawMessage(`"replace"`), + }, "labels": { Type: "array", - Description: "Labels to apply to this issue.", + Description: "Labels to apply to this issue. For 'add' and 'remove', only each label's name is used; 'rationale', 'confidence', and 'is_suggestion' are only honored when method is 'replace'.", Items: &jsonschema.Schema{ OneOf: []*jsonschema.Schema{ {Type: "string", Description: "Label name"}, @@ -429,33 +438,42 @@ func GranularUpdateIssueLabels(t translations.TranslationHelperFunc) inventory.S }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularIssueLabelsInput) (*mcp.CallToolResult, *MinimalResponse, error) { - owner, repo, issueNumber := args.Owner, args.Repo, args.IssueNumber - + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularIssueLabelsInput) (*mcp.CallToolResult, *GranularIssueLabelsResponse, error) { client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil } - body := granularIssueLabelsPayload(args.Labels) - - apiURL := fmt.Sprintf("repos/%s/%s/issues/%d", owner, repo, issueNumber) - req, err := client.NewRequest(ctx, "PATCH", apiURL, body) - if err != nil { - return utils.NewToolResultErrorFromErr("failed to create request", err), nil, nil + var issue *github.Issue + var errResult *mcp.CallToolResult + switch args.Method { + case issueLabelsMethodAdd: + issue, errResult = addIssueLabels(ctx, client, args) + case issueLabelsMethodRemove: + issue, errResult = removeIssueLabels(ctx, client, args) + default: + issue, errResult = replaceIssueLabels(ctx, client, args) + } + if errResult != nil { + return errResult, nil, nil } - issue := &github.Issue{} - resp, err := client.Do(req, issue) + names := make([]string, 0, len(issue.Labels)) + for _, label := range issue.Labels { + names = append(names, label.GetName()) + } + output := &GranularIssueLabelsResponse{ + ID: fmt.Sprintf("%d", issue.GetID()), + URL: issue.GetHTMLURL(), + Labels: names, + } + raw, err := json.Marshal(output) if err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to update issue", resp, err), nil, nil + return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - defer func() { _ = resp.Body.Close() }() - - return granularIssueMinimalResult(&MinimalResponse{ - ID: fmt.Sprintf("%d", issue.GetID()), - URL: issue.GetHTMLURL(), - }) + result := utils.NewToolResultText(string(raw)) + result = attachRepoVisibilityIFCLabelLazy(ctx, deps, args.Owner, args.Repo, result, ifc.LabelRepoMetadata) + return result, output, nil }, granularIssueInputNormalizer(normalizeGranularUpdateIssueLabelsArguments), ) @@ -463,6 +481,66 @@ func GranularUpdateIssueLabels(t translations.TranslationHelperFunc) inventory.S return st } +func replaceIssueLabels(ctx context.Context, client *github.Client, args GranularIssueLabelsInput) (*github.Issue, *mcp.CallToolResult) { + apiURL := fmt.Sprintf("repos/%s/%s/issues/%d", args.Owner, args.Repo, args.IssueNumber) + req, err := client.NewRequest(ctx, "PATCH", apiURL, granularIssueLabelsPayload(args.Labels)) + if err != nil { + return nil, utils.NewToolResultErrorFromErr("failed to create request", err) + } + issue := &github.Issue{} + resp, err := client.Do(req, issue) + if err != nil { + return nil, ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to update issue", resp, err) + } + _ = resp.Body.Close() + return issue, nil +} + +func addIssueLabels(ctx context.Context, client *github.Client, args GranularIssueLabelsInput) (*github.Issue, *mcp.CallToolResult) { + names := make([]string, len(args.Labels)) + for i, label := range args.Labels { + names[i] = label.Name + } + _, resp, err := client.Issues.AddLabelsToIssue(ctx, args.Owner, args.Repo, args.IssueNumber, names) + if err != nil { + return nil, ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to add labels to issue", resp, err) + } + _ = resp.Body.Close() + return getIssueAfterLabelChange(ctx, client, args) +} + +func removeIssueLabels(ctx context.Context, client *github.Client, args GranularIssueLabelsInput) (*github.Issue, *mcp.CallToolResult) { + removed := make([]string, 0, len(args.Labels)) + for _, label := range args.Labels { + // Not using Issues.RemoveLabelForIssue: it does not escape names like "status/blocked". + apiURL := fmt.Sprintf("repos/%s/%s/issues/%d/labels/%s", args.Owner, args.Repo, args.IssueNumber, url.PathEscape(label.Name)) + req, err := client.NewRequest(ctx, "DELETE", apiURL, nil) + if err != nil { + return nil, utils.NewToolResultErrorFromErr("failed to create request", err) + } + resp, err := client.Do(req, nil) + if err != nil { + msg := fmt.Sprintf("failed to remove label %q from issue", label.Name) + if len(removed) > 0 { + msg += fmt.Sprintf(" (already removed: %s)", strings.Join(removed, ", ")) + } + return nil, ghErrors.NewGitHubAPIErrorResponse(ctx, msg, resp, err) + } + _ = resp.Body.Close() + removed = append(removed, label.Name) + } + return getIssueAfterLabelChange(ctx, client, args) +} + +func getIssueAfterLabelChange(ctx context.Context, client *github.Client, args GranularIssueLabelsInput) (*github.Issue, *mcp.CallToolResult) { + issue, resp, err := client.Issues.Get(ctx, args.Owner, args.Repo, args.IssueNumber) + if err != nil { + return nil, ghErrors.NewGitHubAPIErrorResponse(ctx, "labels were updated but failed to read the issue back", resp, err) + } + _ = resp.Body.Close() + return issue, nil +} + // GranularUpdateIssueMilestone creates a tool to update an issue's milestone. func GranularUpdateIssueMilestone(t translations.TranslationHelperFunc) inventory.ServerTool { return issueUpdateTool(t, diff --git a/pkg/github/typed_granular_issue_outputs_test.go b/pkg/github/typed_granular_issue_outputs_test.go index d2b833d650..2d9086233b 100644 --- a/pkg/github/typed_granular_issue_outputs_test.go +++ b/pkg/github/typed_granular_issue_outputs_test.go @@ -86,6 +86,8 @@ type granularIssueWireCase struct { } const granularMutationText = `{"id":"123","url":"https://github.com/owner/repo/issues/1"}` + +const granularLabelsMutationText = `{"id":"123","url":"https://github.com/owner/repo/issues/1","labels":[]}` const granularSubIssueAPIResponse = `{"id":7,"number":7,"title":"Child\u202e","body":"body\u202e","url":"https://api.github.com/repos/owner/repo/issues/7","html_url":"https://github.com/owner/repo/issues/7","comments_url":"https://api.github.com/repos/owner/repo/issues/7/comments","node_id":"I_7","issue_field_values":[{"issue_field_id":11,"node_id":"IF_11","data_type":"number","value":0},{"issue_field_id":12,"node_id":"IF_12","data_type":"text","value":""},{"issue_field_id":13,"node_id":"IF_13","data_type":"text","value":false},{"issue_field_id":14,"node_id":"IF_14","data_type":"text","value":null}]}` const granularSubIssueText = `{"id":7,"number":7,"title":"Child","body":"body","url":"https://api.github.com/repos/owner/repo/issues/7","html_url":"https://github.com/owner/repo/issues/7","comments_url":"https://api.github.com/repos/owner/repo/issues/7/comments","node_id":"I_7","issue_field_values":[{"issue_field_id":11,"node_id":"IF_11","data_type":"number","value":0},{"issue_field_id":12,"node_id":"IF_12","data_type":"text","value":""},{"issue_field_id":13,"node_id":"IF_13","data_type":"text","value":false},{"issue_field_id":14,"node_id":"IF_14","data_type":"text","value":null}]}` @@ -103,9 +105,9 @@ func granularIssueWireCases() []granularIssueWireCase { {"update_issue_assignees", map[string]any{"assignees": []string{}}, granularMutationText, "", `{"assignees":[]}`, "/repos/owner/repo/issues/1", "PATCH"}, {"update_issue_assignees", map[string]any{"assignees": []any{"octocat", map[string]any{"login": "hubot"}}}, granularMutationText, "", `{"assignees":["octocat","hubot"]}`, "/repos/owner/repo/issues/1", "PATCH"}, {"update_issue_assignees", map[string]any{"assignees": []any{"hubot", map[string]any{"login": "octocat", "rationale": " Authored file ", "confidence": " high\t", "is_suggestion": true}}}, granularMutationText, "", `{"assignees":["hubot",{"login":"octocat","rationale":"Authored file","confidence":"HIGH","suggest":true}]}`, "/repos/owner/repo/issues/1", "PATCH"}, - {"update_issue_labels", map[string]any{"labels": []string{}}, granularMutationText, "", `{"labels":[]}`, "/repos/owner/repo/issues/1", "PATCH"}, - {"update_issue_labels", map[string]any{"labels": []any{"bug", map[string]any{"name": "triage"}}}, granularMutationText, "", `{"labels":["bug","triage"]}`, "/repos/owner/repo/issues/1", "PATCH"}, - {"update_issue_labels", map[string]any{"labels": []any{"triage", map[string]any{"name": "bug", "rationale": " Crash ", "confidence": " medium ", "is_suggestion": true}}}, granularMutationText, "", `{"labels":["triage",{"name":"bug","rationale":"Crash","confidence":"MEDIUM","suggest":true}]}`, "/repos/owner/repo/issues/1", "PATCH"}, + {"update_issue_labels", map[string]any{"labels": []string{}}, granularLabelsMutationText, "", `{"labels":[]}`, "/repos/owner/repo/issues/1", "PATCH"}, + {"update_issue_labels", map[string]any{"labels": []any{"bug", map[string]any{"name": "triage"}}}, granularLabelsMutationText, "", `{"labels":["bug","triage"]}`, "/repos/owner/repo/issues/1", "PATCH"}, + {"update_issue_labels", map[string]any{"labels": []any{"triage", map[string]any{"name": "bug", "rationale": " Crash ", "confidence": " medium ", "is_suggestion": true}}}, granularLabelsMutationText, "", `{"labels":["triage",{"name":"bug","rationale":"Crash","confidence":"MEDIUM","suggest":true}]}`, "/repos/owner/repo/issues/1", "PATCH"}, {"update_issue_milestone", map[string]any{"milestone": "3e0"}, granularMutationText, "", `{"milestone":3}`, "/repos/owner/repo/issues/1", "PATCH"}, {"update_issue_type", map[string]any{"issue_type": nil}, granularMutationText, "", `{"type":null}`, "/repos/owner/repo/issues/1", "PATCH"}, {"update_issue_type", map[string]any{"issue_type": "Bug"}, granularMutationText, "", `{"type":"Bug"}`, "/repos/owner/repo/issues/1", "PATCH"}, @@ -395,7 +397,7 @@ func TestTypedGranularIssueWireErrors(t *testing.T) { {"update_issue_title", map[string]any{"title": "Subject"}, `{"id":"0","url":""}`}, {"update_issue_body", map[string]any{"body": "Body"}, `{"id":"0","url":""}`}, {"update_issue_assignees", map[string]any{"assignees": []string{}}, `{"id":"0","url":""}`}, - {"update_issue_labels", map[string]any{"labels": []string{}}, `{"id":"0","url":""}`}, + {"update_issue_labels", map[string]any{"labels": []string{}}, `{"id":"0","url":"","labels":[]}`}, {"update_issue_milestone", map[string]any{"milestone": 3}, `{"id":"0","url":""}`}, {"update_issue_type", map[string]any{"issue_type": nil}, `{"id":"0","url":""}`}, {"update_issue_state", map[string]any{"state": "open"}, `{"id":"0","url":""}`},