Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/feature-flags.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
28 changes: 24 additions & 4 deletions pkg/github/__toolsnaps__/update_issue_labels.snap
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -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": [
{
Expand Down Expand Up @@ -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",
Expand All @@ -94,13 +104,23 @@
"id": {
"type": "string"
},
"labels": {
"items": {
"type": "string"
},
"type": [
"null",
"array"
]
},
"url": {
"type": "string"
}
},
"required": [
"id",
"url"
"url",
"labels"
],
"type": [
"null",
Expand Down
59 changes: 57 additions & 2 deletions pkg/github/granular_issue_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
199 changes: 199 additions & 0 deletions pkg/github/granular_tools_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package github
import (
"context"
"encoding/json"
"fmt"
"maps"
"net/http"
"strings"
Expand All @@ -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"
Expand Down Expand Up @@ -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")
}
2 changes: 2 additions & 0 deletions pkg/github/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading