diff --git a/README.md b/README.md index ab7377f127..defd3fd4d0 100644 --- a/README.md +++ b/README.md @@ -619,6 +619,15 @@ The following sets of tools are available: | people | `users` | GitHub User related tools | +The `issues` toolset supports planning statuses. `issue_read` returns the +current status, `search_issues` documents the `status:` qualifier, and issue +creation accepts Backlog, Todo, In progress, or In review. The +`update_issue_status` tool also accepts Done, Not planned, and Duplicate; +these closing statuses require `confirm_close: true` after the user confirms. +Duplicate requires the canonical issue number in `duplicate_of`. The +`issue_write` MCP App creation form can set an initial status or use the +default, Backlog. + ### Additional Toolsets in Remote GitHub MCP Server | Toolset | Description | @@ -1099,6 +1108,7 @@ For negotiated supported protocol versions `2026-07-28` or newer, the consolidat - `repo`: Repository name (string, required) - `state`: New state (string, optional) - `state_reason`: Reason for the state change. Ignored unless state is changed. (string, optional) + - `status`: Initial planning status (create only). Only open statuses are supported. Backlog is backlog; Todo is planned; In progress and In review are started. Omit to use the default status, Backlog. (string, optional) - `title`: Issue title (string, optional) - `type`: Type of this issue. For updates, pass null to remove the current type. Only use if issue types are enabled for this repository. Use list_issue_types to get valid type values for this repository or its owner organization. If the repository doesn't support issue types, omit this parameter. (string | null, optional) @@ -1161,6 +1171,15 @@ For negotiated supported protocol versions `2026-07-28` or newer, the consolidat - `owner`: Repository owner (string, required) - `repo`: Repository name (string, required) +- **update_issue_status** - Update Issue Status + - **OAuth Challenge Scopes**: `repo` + - `confirm_close`: Must be true for Done, Not planned or Duplicate. Set only after the user confirms closing the issue. (boolean, optional) + - `duplicate_of`: The canonical issue number. Required only for Duplicate. (number, optional) + - `issue_number`: The issue number to update (number, required) + - `owner`: Repository owner (username or organization) (string, required) + - `repo`: Repository name (string, required) + - `status`: The planning status to assign. (string, required) +
diff --git a/docs/feature-flags.md b/docs/feature-flags.md index bbfadbfb7f..1cef71ef28 100644 --- a/docs/feature-flags.md +++ b/docs/feature-flags.md @@ -285,6 +285,7 @@ as output formatting) won't appear here. - `parent_owner`: Repository owner of the parent issue. Must be provided with parent_repo. Omit both to use owner and repo. Only used when parent_issue_number is provided. (string, optional) - `parent_repo`: Repository name of the parent issue. Must be provided with parent_owner. Omit both to use owner and repo. Only used when parent_issue_number is provided. (string, optional) - `repo`: Repository name (string, required) + - `status`: Initial planning status (create only). Only open statuses are supported. Backlog is backlog; Todo is planned; In progress and In review are started. Omit to use the default status, Backlog. (string, optional) - `title`: Issue title (string, required) - **hide_issue_comment** - Hide Issue Comment diff --git a/pkg/github/__toolsnaps__/create_issue.snap b/pkg/github/__toolsnaps__/create_issue.snap index b616605c21..d5c783cb26 100644 --- a/pkg/github/__toolsnaps__/create_issue.snap +++ b/pkg/github/__toolsnaps__/create_issue.snap @@ -48,6 +48,16 @@ "type": "string", "x-mcp-header": "repo" }, + "status": { + "description": "Initial planning status (create only). Only open statuses are supported. Backlog is backlog; Todo is planned; In progress and In review are started. Omit to use the default status, Backlog.", + "enum": [ + "Backlog", + "Todo", + "In progress", + "In review" + ], + "type": "string" + }, "title": { "description": "Issue title", "type": "string" diff --git a/pkg/github/__toolsnaps__/issue_read.snap b/pkg/github/__toolsnaps__/issue_read.snap index 4a4356bfe5..c52b73a9a7 100644 --- a/pkg/github/__toolsnaps__/issue_read.snap +++ b/pkg/github/__toolsnaps__/issue_read.snap @@ -586,6 +586,48 @@ ], "type": "string" }, + "status": { + "additionalProperties": false, + "description": "The issue's planning status, or null when it has none or it is not recognized. Backlog is backlog; Todo is planned; In progress and In review are started; Done is completed; Not planned is not_planned; Duplicate is duplicate.", + "properties": { + "category": { + "enum": [ + "backlog", + "planned", + "started", + "completed", + "not_planned", + "duplicate" + ], + "type": "string" + }, + "id": { + "description": "The status ID.", + "type": "integer" + }, + "name": { + "enum": [ + "Backlog", + "Todo", + "In progress", + "In review", + "Done", + "Not planned", + "Duplicate" + ], + "type": "string" + } + }, + "required": [ + "id", + "name", + "category" + ], + "type": [ + "object", + "null" + ] + }, "sub_issues_summary": { "additionalProperties": false, "properties": { @@ -642,7 +684,8 @@ "number", "title", "state", - "assignees" + "assignees", + "status" ], "type": [ "null", diff --git a/pkg/github/__toolsnaps__/issue_write.snap b/pkg/github/__toolsnaps__/issue_write.snap index dde73657f6..ef3b446e28 100644 --- a/pkg/github/__toolsnaps__/issue_write.snap +++ b/pkg/github/__toolsnaps__/issue_write.snap @@ -125,6 +125,16 @@ ], "type": "string" }, + "status": { + "description": "Initial planning status (create only). Only open statuses are supported. Backlog is backlog; Todo is planned; In progress and In review are started. Omit to use the default status, Backlog.", + "enum": [ + "Backlog", + "Todo", + "In progress", + "In review" + ], + "type": "string" + }, "title": { "description": "Issue title", "type": "string" diff --git a/pkg/github/__toolsnaps__/search_issues.snap b/pkg/github/__toolsnaps__/search_issues.snap index bbba9b0b95..292998b3d6 100644 --- a/pkg/github/__toolsnaps__/search_issues.snap +++ b/pkg/github/__toolsnaps__/search_issues.snap @@ -4,7 +4,7 @@ "readOnlyHint": true, "title": "Search issues" }, - "description": "Search issues using natural-language semantic matching. Best for conceptual or paraphrased queries (e.g. \"login fails after password reset\"). Already scoped to is:issue.", + "description": "Search issues using natural-language semantic matching. Best for conceptual or paraphrased queries (e.g. \"login fails after password reset\"). Already scoped to is:issue. Filter by planning status with the status: qualifier, for example status:\"In progress\". Statuses: Backlog, Todo, In progress, In review, Done, Not planned, Duplicate.", "inputSchema": { "properties": { "fields": { diff --git a/pkg/github/__toolsnaps__/update_issue_status.snap b/pkg/github/__toolsnaps__/update_issue_status.snap new file mode 100644 index 0000000000..af13cd10c7 --- /dev/null +++ b/pkg/github/__toolsnaps__/update_issue_status.snap @@ -0,0 +1,130 @@ +{ + "annotations": { + "destructiveHint": true, + "idempotentHint": false, + "openWorldHint": true, + "readOnlyHint": false, + "title": "Update Issue Status" + }, + "description": "Update an issue's planning status. Done, Not planned and Duplicate close the issue; the other statuses keep it open or reopen it. Closing statuses require confirm_close: true, set only after the user confirms closing the issue. Duplicate requires duplicate_of, the canonical issue number in the same repository. A status cannot be removed.", + "icons": [ + { + "mimeType": "image/png", + "src": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAAC2UlEQVRIicWVMUyTaRjHf/+vVUpOJOdilOYoUvVreq2CDmLOwdlAS5xMbrrhBifjYG7QjYuJw108nZx1huLgYlw0QshxChUK2koxHHcuCmgsFfieG0or3kGPSoz/8X3f5/97nvfN8z7wmaVqm9FodFfR/EnMugy5giCAwYwgI9Ff9Hl9L9Lp1zUBgsGO+rqGwnlhF4CdwBSyAUwvS1G220zHBSFgHtmVxYWvfp2ZGSj8LyAcjgfZphTQZtAr7OdsZvSP9RIJR+LtQhcNusF+d1aUfPp05M8NAavmg8AOk3cmN56+s1Hpa7U/cviUYbcw3jgex9ZCKoBgsKM+0PDuAdBq2He5zOiTzZiXtc+NxRw598GeLRcWTuTz+UUAp3ygrqFwHmgzeWdqNQd4PpFOy/gedNQfaDz3UQXRaHRX0fNPGdzNZUZO12q+VuHIoV7g5Hu/1/IinX7tABTNnwR2SvRsxRzAzOsBGuuWfAkoX5FZFzCVHR95tFVAbiI9DEwj6wLwl5YVMTRYLTDsxjuRrgGYYz/kxkbvbXRWMOBB24cKYI9ks1X8hXQDaAaa5XG9WjImZgV71wI+m8qAv8y0t1pSmP0ITANTmHO2qqvRZDALlTdgHKyjWkx2YvQ2cHtTacMxYBhWK5DoF4TCkXj7Jg02VKsbOwI0Y+qvALZrOQXMC13cKkDSJWBuJUCqAhgbG3uF7IpBcn/k8KlPNQ+78U5QQuhy/vHjuQoAYPndwi9gw4bd2ufGYrWatxz8No50ExhaKsz9Vl6vAPL5/KKzoiTGG0fOg1oqCbvxTp/juw/M+zynu/yTwjoD58CBQ02ez/pAR4E+M69ntf3/o1Y3dqR050oAQz7P6Z6cfPRRw647MkOhUMAfaDyH+AloBKYNPRT292rQHoMOSp09J3TZlt5ezWazxX97VR3638RiX9ct+RImSyBcrDT0ETMyMp4ptRIgVX7QL6J/ALSUEwJ5rdg2AAAAAElFTkSuQmCC", + "theme": "light" + }, + { + "mimeType": "image/png", + "src": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAABxElEQVRIibWVvW4TURCFv0vlNEDcIHAkKAERJOIKSjoUArwBPwUFFaKIIngAJARCPIgdh4cgRBYt6ZIAEYEqdhpEw0fhCbkKa68dxyNtsfNzzpnZu3NhwpYGBdUqcA+4A1wEZiK0DawD74FWSml3JAJ1CngGLAIngU1gFfgZKWeAG8AFoAu8At6mlH6VtqTOqJ/UP2pDnRuQO6c27VlbrQ0Dvq121Fulag7q5qPmW18SdSqUd9Qrw4Jn9bNR21YrRQkvYixDKy/AuB3jWjocqKpdtXFU8AxrOTqZzp2PgvnaMRDUA+tB7mypG+OCZ3hbahPgRPguAR9LihaicEu9WcKxClzOi/fU1wPAk7rjgX0uEfNG3cs7mJjtE+wA5/olpZQEHgNf6K2NJyW4NeD7v7c4WptjSc0svlMjdzyM2fbdOyOA7x/T+7mzGj9H8xgIWuquevpw4HmsivkxwBdC/WJRsBKLqqPOHgH8aqybtcJlF0m1WLndUToJ5V31q9r3NOYk7Wh1Wa0PyK3HzA3l/4H3uzIrwFNgCThF7/x/AH5EylngOnAe6AAvgXcppd9DEWRE08DdeIou/RVgJaXUGYQzUfsL+zmwV7BtIq0AAAAASUVORK5CYII=", + "theme": "dark" + } + ], + "inputSchema": { + "properties": { + "confirm_close": { + "description": "Must be true for Done, Not planned or Duplicate. Set only after the user confirms closing the issue.", + "type": "boolean" + }, + "duplicate_of": { + "description": "The canonical issue number. Required only for Duplicate.", + "minimum": 1, + "type": "number" + }, + "issue_number": { + "description": "The issue number to update", + "minimum": 1, + "type": "number" + }, + "owner": { + "description": "Repository owner (username or organization)", + "type": "string", + "x-mcp-header": "owner" + }, + "repo": { + "description": "Repository name", + "type": "string", + "x-mcp-header": "repo" + }, + "status": { + "description": "The planning status to assign.", + "enum": [ + "Backlog", + "Todo", + "In progress", + "In review", + "Done", + "Not planned", + "Duplicate" + ], + "type": "string" + } + }, + "required": [ + "owner", + "repo", + "issue_number", + "status" + ], + "type": "object" + }, + "name": "update_issue_status", + "outputSchema": { + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "status": { + "additionalProperties": false, + "description": "The issue's planning status, or null when it has none or it is not recognized. Backlog is backlog; Todo is planned; In progress and In review are started; Done is completed; Not planned is not_planned; Duplicate is duplicate.", + "properties": { + "category": { + "enum": [ + "backlog", + "planned", + "started", + "completed", + "not_planned", + "duplicate" + ], + "type": "string" + }, + "id": { + "description": "The status ID.", + "type": "integer" + }, + "name": { + "enum": [ + "Backlog", + "Todo", + "In progress", + "In review", + "Done", + "Not planned", + "Duplicate" + ], + "type": "string" + } + }, + "required": [ + "id", + "name", + "category" + ], + "type": [ + "object", + "null" + ] + }, + "url": { + "type": "string" + } + }, + "required": [ + "id", + "url", + "status" + ], + "type": "object" + } +} \ No newline at end of file diff --git a/pkg/github/consolidated_issue_types.go b/pkg/github/consolidated_issue_types.go index ccd84e0173..2f81836b0b 100644 --- a/pkg/github/consolidated_issue_types.go +++ b/pkg/github/consolidated_issue_types.go @@ -27,6 +27,7 @@ type IssueWriteInput struct { State *string `json:"state,omitempty"` StateReason *string `json:"state_reason,omitempty"` DuplicateOf *int `json:"duplicate_of,omitempty"` + Status *string `json:"status,omitempty"` IssueFields []IssueWriteFieldInput `json:"issue_fields,omitempty"` TypeProvided bool `json:"-"` } @@ -160,6 +161,7 @@ type IssueDetailsOutput struct { Parent *MinimalIssueRef `json:"parent,omitempty"` SubIssuesSummary *MinimalSubIssuesSummary `json:"sub_issues_summary,omitempty"` ClosedByPullRequests *MinimalClosingPullRequests `json:"closed_by_pull_requests,omitempty"` + Status *IssuePlanningStatus `json:"status"` } func issueDetailsOutput(issue MinimalIssue) *IssueDetailsOutput { @@ -381,6 +383,7 @@ func subIssueOutput(issue *github.SubIssue) (*SubIssueOutput, error) { var issueReadOutputSchema = sync.OnceValue(func() *jsonschema.Schema { schema := issueDTOschema[IssueReadOutput]() issue := schema.Properties["issue"] + issue.Properties["status"] = issuePlanningStatusSchema() issue.Properties["state"].Enum = []any{"", "open", "closed"} issue.Properties["state_reason"].Enum = []any{"completed", "not_planned", "reopened", "duplicate"} describeIssueSummarySchema(issue.Properties["sub_issues_summary"]) diff --git a/pkg/github/granular_issue_types.go b/pkg/github/granular_issue_types.go index c0b9f2e16d..765cb56af8 100644 --- a/pkg/github/granular_issue_types.go +++ b/pkg/github/granular_issue_types.go @@ -30,6 +30,7 @@ type GranularCreateIssueInput struct { ParentIssueNumber *int `json:"parent_issue_number,omitempty"` ParentOwner string `json:"parent_owner,omitempty"` ParentRepo string `json:"parent_repo,omitempty"` + Status string `json:"status,omitempty"` } type GranularIssueTitleInput struct { @@ -455,7 +456,11 @@ func normalizeGranularCreateIssueArguments(raw json.RawMessage) (json.RawMessage parentNumber = &parentIssueNumber } - return marshalGranularIssueArguments(args, GranularCreateIssueInput{Owner: owner, Repo: repo, Title: title, Body: body, ParentIssueNumber: parentNumber, ParentOwner: parentOwner, ParentRepo: parentRepo}) + status, err := OptionalParam[string](args, "status") + if err != nil { + return nil, err + } + return marshalGranularIssueArguments(args, GranularCreateIssueInput{Owner: owner, Repo: repo, Title: title, Body: body, ParentIssueNumber: parentNumber, ParentOwner: parentOwner, ParentRepo: parentRepo, Status: status}) } func normalizeGranularUpdateIssueAssigneesArguments(raw json.RawMessage) (json.RawMessage, error) { diff --git a/pkg/github/granular_tools_test.go b/pkg/github/granular_tools_test.go index b63485fe9d..a014d8ae40 100644 --- a/pkg/github/granular_tools_test.go +++ b/pkg/github/granular_tools_test.go @@ -3,8 +3,10 @@ package github import ( "context" "encoding/json" + "fmt" "maps" "net/http" + "slices" "strings" "testing" @@ -16,6 +18,7 @@ import ( "github.com/github/github-mcp-server/v2/pkg/translations" "github.com/github/github-mcp-server/v2/pkg/utils" 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" @@ -114,7 +117,7 @@ func TestIssuesGranularToolset(t *testing.T) { t.Run("all granular tools have correct feature flag", func(t *testing.T) { for _, tool := range granularToolsForToolset(ToolsetMetadataIssues.ID, FeatureFlagIssuesGranular) { - assert.Equal(t, []inventory.FeatureFlag{inventory.FeatureFlag(FeatureFlagIssuesGranular)}, tool.FeatureRule.Features(), "tool %s", tool.Tool.Name) + assert.Contains(t, tool.FeatureRule.Features(), inventory.FeatureFlag(FeatureFlagIssuesGranular), "tool %s", tool.Tool.Name) } }) } @@ -1175,6 +1178,179 @@ func TestGranularUpdateIssueState(t *testing.T) { } } +func TestUpdateIssueStatus(t *testing.T) { + cases := []struct { + status string + category string + duplicateCode int + updateCode int + wantError string + unconfirmed bool + }{ + {"Backlog", "backlog", 0, http.StatusOK, "", false}, + {"Todo", "planned", 0, http.StatusOK, "", false}, + {"In progress", "started", 0, http.StatusOK, "", false}, + {"In review", "started", 0, http.StatusOK, "", false}, + {"Done", "completed", 0, http.StatusOK, "", false}, + {"Not planned", "not_planned", 0, http.StatusOK, "", false}, + {"Duplicate", "duplicate", http.StatusOK, http.StatusOK, "", false}, + {"Duplicate", "duplicate", http.StatusNotFound, 0, "failed to get duplicate issue", false}, + {"Todo", "planned", 0, http.StatusForbidden, "failed to update issue", false}, + {"Done", "completed", 0, 0, "confirm_close must be true", true}, + {"Not planned", "not_planned", 0, 0, "confirm_close must be true", true}, + {"Duplicate", "duplicate", 0, 0, "confirm_close must be true", true}, + } + for _, tc := range cases { + t.Run(fmt.Sprintf("%s/%d/%d/unconfirmed=%t", tc.status, tc.duplicateCode, tc.updateCode, tc.unconfirmed), func(t *testing.T) { + gets, patches := 0, 0 + rest := &http.Client{Transport: recorderTransport{handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method == http.MethodGet { + gets++ + assert.Equal(t, "/repos/owner/repo/issues/7", r.URL.Path) + w.WriteHeader(tc.duplicateCode) + _, _ = w.Write([]byte(`{"id":987,"message":"Not Found"}`)) + return + } + patches++ + assert.Equal(t, http.MethodPatch, r.Method) + assert.Equal(t, "/repos/owner/repo/issues/42", r.URL.Path) + var body map[string]any + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + expected := map[string]any{"status": tc.status} + if tc.status == "Duplicate" { + expected["duplicate_issue_id"] = float64(987) + } + assert.Equal(t, expected, body, "only the status and resolved duplicate ID should be sent") + w.WriteHeader(tc.updateCode) + _, _ = fmt.Fprintf(w, `{"id":123,"html_url":"https://github.com/owner/repo/issues/42","status":{"id":4,"name":%q,"category":%q},"message":"Forbidden"}`, tc.status, tc.category) + })}} + session, _ := issueStatusSession(t, BaseDeps{Client: mustNewGHClient(t, rest)}, inventory.ProtocolVersionMultiRoundTrip) + args := map[string]any{"owner": "owner", "repo": "repo", "issue_number": "42", "status": strings.ToLower(tc.status)} + if tc.status == "Duplicate" { + args["duplicate_of"] = "7" + } + if slices.Contains(issueClosingStatusNames, tc.status) && !tc.unconfirmed { + args["confirm_close"] = true + } + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: "update_issue_status", Arguments: args}) + require.NoError(t, err) + if tc.wantError != "" { + require.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, tc.wantError) + } else { + require.False(t, result.IsError, "%s", getTextResult(t, result).Text) + assert.JSONEq(t, fmt.Sprintf(`{"id":"123","url":"https://github.com/owner/repo/issues/42","status":{"id":4,"name":%q,"category":%q}}`, tc.status, tc.category), getTextResult(t, result).Text) + assert.JSONEq(t, mustMarshalJSON(t, result.StructuredContent), getTextResult(t, result).Text) + } + if tc.status == "Duplicate" && !tc.unconfirmed { + assert.Equal(t, 1, gets) + } else { + assert.Zero(t, gets) + } + if tc.updateCode == 0 { + assert.Zero(t, patches, "failed duplicate lookup or missing confirmation must prevent the mutation") + } else { + assert.Equal(t, 1, patches) + } + }) + } +} + +func TestIssuePlanningStatusInvalidInput(t *testing.T) { + translate := translations.NullTranslationHelper + cases := []struct { + tool inventory.ServerTool + args map[string]any + want string + }{ + {UpdateIssueStatus(translate), map[string]any{"status": "Duplicate"}, "duplicate_of is required"}, + {UpdateIssueStatus(translate), map[string]any{"status": "Duplicate", "duplicate_of": 0}, "duplicate_of must be positive"}, + {UpdateIssueStatus(translate), map[string]any{"status": "Todo", "duplicate_of": 7}, "duplicate_of can only be used"}, + {UpdateIssueStatus(translate), map[string]any{"status": "unknown"}, "status must be one of"}, + {UpdateIssueStatus(translate), map[string]any{"status": nil}, "status"}, + {UpdateIssueStatus(translate), map[string]any{"status": "Todo", "issue_number": -1}, "issue_number must be positive"}, + {UpdateIssueStatus(translate), map[string]any{"status": "Done"}, "confirm_close must be true"}, + {UpdateIssueStatus(translate), map[string]any{"status": "Not planned", "confirm_close": false}, "confirm_close must be true"}, + {UpdateIssueStatus(translate), map[string]any{"status": "Done", "confirm_close": "true"}, "confirm_close"}, + {UpdateIssueStatus(translate), map[string]any{"status": "Todo", "repo": "repo/../../user"}, "repository path segments"}, + {UpdateIssueStatus(translate), map[string]any{"status": "Todo", "owner": ".."}, "repository path segments"}, + {GranularCreateIssue(translate), map[string]any{"status": "Todo", "owner": `owner\x`}, "repository path segments"}, + {IssueWrite(translate), map[string]any{"status": "Todo", "repo": "."}, "repository path segments"}, + {GranularCreateIssue(translate), map[string]any{"status": "Done"}, "status must be one of: Backlog, Todo, In progress, In review"}, + {IssueWrite(translate), map[string]any{"method": "update", "status": "Todo"}, "status is only supported with the create method"}, + {IssueWrite(translate), map[string]any{"status": "Todo", "state": "closed"}, "status cannot be combined with state"}, + } + for i, tc := range cases { + t.Run(fmt.Sprintf("%s/%d", tc.tool.Tool.Name, i), func(t *testing.T) { + args := map[string]any{"owner": "owner", "repo": "repo", "issue_number": 42, "title": "Subject", "method": "create"} + maps.Copy(args, tc.args) + req := createMCPRequest(args) + result, err := tc.tool.Handler(BaseDeps{})(ContextWithDeps(context.Background(), BaseDeps{}), &req) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, tc.want) + }) + } +} + +func TestIssuePlanningStatusCreationNotApplied(t *testing.T) { + for _, tool := range []inventory.ServerTool{ + IssueWrite(translations.NullTranslationHelper), GranularCreateIssue(translations.NullTranslationHelper), + } { + t.Run(tool.Tool.Name, func(t *testing.T) { + client := MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + PostReposIssuesByOwnerByRepo: mockResponse(t, http.StatusCreated, map[string]any{ + "id": 123, "number": 42, "html_url": "https://github.com/owner/repo/issues/42", + "status": map[string]any{"id": 1, "name": "Backlog", "category": "backlog"}, + }), + }) + deps := BaseDeps{Client: mustNewGHClient(t, client), GQLClient: defaultGQLClient} + req := createMCPRequest(map[string]any{"owner": "owner", "repo": "repo", "title": "Subject", "method": "create", "status": "Todo"}) + result, err := tool.Handler(deps)(ContextWithDeps(context.Background(), deps), &req) + require.NoError(t, err) + require.True(t, result.IsError) + text := getTextResult(t, result).Text + assert.Contains(t, text, "issue created but requested status was not applied") + assert.Contains(t, text, `requested="Todo", applied="Backlog", issue_id=123, issue_url="https://github.com/owner/repo/issues/42"`) + }) + } +} + +func TestUpdateIssueStatusNotApplied(t *testing.T) { + for _, protocol := range []string{inventory.ProtocolVersionMultiRoundTrip, "2025-11-25"} { + for _, status := range []string{ + `{"id":9,"name":"Blocked","category":"started"}`, + `{"id":9,"name":"Todo","category":"custom"}`, + `{"id":1,"name":"Backlog","category":"backlog"}`, + `"Todo"`, `null`, "", + } { + t.Run(protocol+"/"+status, func(t *testing.T) { + patches := 0 + rest := &http.Client{Transport: recorderTransport{handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + patches++ + assert.Equal(t, http.MethodPatch, r.Method) + payload := `{"id":123,"html_url":"https://github.com/owner/repo/issues/42"}` + if status != "" { + payload = strings.TrimSuffix(payload, "}") + `,"status":` + status + "}" + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(payload)) + })}} + session, _ := issueStatusSession(t, BaseDeps{Client: mustNewGHClient(t, rest)}, protocol) + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: "update_issue_status", Arguments: map[string]any{ + "owner": "owner", "repo": "repo", "issue_number": 42, "status": "Todo", + }}) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, `requested status "Todo" was not applied`) + assert.Nil(t, result.StructuredContent) + assert.Equal(t, 1, patches, "unapplied status updates must not be retried") + }) + } + } +} + func TestGranularUpdateIssueStateSuggest(t *testing.T) { tests := []struct { name string diff --git a/pkg/github/issue_status.go b/pkg/github/issue_status.go new file mode 100644 index 0000000000..ecb8157eb2 --- /dev/null +++ b/pkg/github/issue_status.go @@ -0,0 +1,364 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "slices" + "strings" + + 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/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/google/go-github/v92/github" + "github.com/google/jsonschema-go/jsonschema" + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/shurcooL/githubv4" +) + +var ( + issueStatusNames = []string{"Backlog", "Todo", "In progress", "In review", "Done", "Not planned", "Duplicate"} + // Issues can only be created with an open status. + issueCreationStatusNames = issueStatusNames[:4:4] + issueStatusCategories = []string{"backlog", "planned", "started", "completed", "not_planned", "duplicate"} + issueClosingStatusNames = issueStatusNames[4:] +) + +type IssuePlanningStatus struct { + ID int64 `json:"id"` + Name string `json:"name"` + Category string `json:"category"` +} + +// issueWithStatus decodes the REST status field, which go-github does not yet expose. +// The status stays raw so an unexpected shape cannot fail decoding the issue. +type issueWithStatus struct { + github.Issue + RawStatus json.RawMessage `json:"status"` +} + +// planningStatus returns nil when the issue has no status or an unrecognized one, +// so unexpected API values never fail output schema validation. +func (issue *issueWithStatus) planningStatus() *IssuePlanningStatus { + var status *IssuePlanningStatus + if json.Unmarshal(issue.RawStatus, &status) != nil || status == nil { + return nil + } + if !slices.Contains(issueStatusNames, status.Name) || !slices.Contains(issueStatusCategories, status.Category) { + return nil + } + return status +} + +func enumValues(values []string) []any { + enum := make([]any, len(values)) + for i, value := range values { + enum[i] = value + } + return enum +} + +type IssueStatusUpdateOutput struct { + ID string `json:"id"` + URL string `json:"url"` + Status *IssuePlanningStatus `json:"status"` +} + +type IssueStatusInput struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + IssueNumber int `json:"issue_number"` + Status string `json:"status"` + DuplicateOf int `json:"duplicate_of,omitempty"` + ConfirmClose bool `json:"confirm_close,omitempty"` +} + +func issuePlanningStatusSchema() *jsonschema.Schema { + return &jsonschema.Schema{ + Types: []string{"object", "null"}, + Description: "The issue's planning status, or null when it has none or it is not recognized. " + + "Backlog is backlog; Todo is planned; In progress and In review are started; " + + "Done is completed; Not planned is not_planned; Duplicate is duplicate.", + Properties: map[string]*jsonschema.Schema{ + "id": {Type: "integer", Description: "The status ID."}, + "name": {Type: "string", Enum: enumValues(issueStatusNames)}, + "category": {Type: "string", Enum: enumValues(issueStatusCategories)}, + }, + Required: []string{"id", "name", "category"}, + AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}}, + } +} + +func canonicalIssueStatus(status string, allowed []string) (string, error) { + for _, name := range allowed { + if strings.EqualFold(status, name) { + return name, nil + } + } + return "", fmt.Errorf("status must be one of: %s", strings.Join(allowed, ", ")) +} + +func normalizeIssueCreationStatus(next inventory.InputNormalizer, consolidated bool) inventory.InputNormalizer { + return func(raw json.RawMessage) (json.RawMessage, error) { + var args map[string]any + if err := json.Unmarshal(raw, &args); err != nil { + return nil, err + } + if _, provided := args["status"]; provided { + if consolidated && args["method"] != "create" { + return nil, fmt.Errorf("status is only supported with the create method; use update_issue_status to update it") + } + status, err := RequiredParam[string](args, "status") + if err != nil { + return nil, err + } + status, err = canonicalIssueStatus(status, issueCreationStatusNames) + if err != nil { + return nil, err + } + for _, field := range []string{"state", "state_reason", "duplicate_of"} { + if _, provided := args[field]; provided { + return nil, fmt.Errorf("status cannot be combined with %s when creating an issue", field) + } + } + args["status"] = status + raw, err = json.Marshal(args) + if err != nil { + return nil, err + } + } + return next(raw) + } +} + +func normalizeIssueStatusArguments(raw json.RawMessage) (json.RawMessage, error) { + var args map[string]any + if err := json.Unmarshal(raw, &args); err != nil { + return nil, err + } + for _, field := range []string{"owner", "repo", "status"} { + if _, err := RequiredParam[string](args, field); err != nil { + return nil, err + } + } + number, err := RequiredInt(args, "issue_number") + if err != nil { + return nil, err + } + if number < 1 { + return nil, fmt.Errorf("issue_number must be positive") + } + status, err := canonicalIssueStatus(args["status"].(string), issueStatusNames) + if err != nil { + return nil, err + } + duplicate := 0 + if _, provided := args["duplicate_of"]; provided { + duplicate, err = OptionalIntParam(args, "duplicate_of") + if err != nil { + return nil, err + } + if duplicate < 1 { + return nil, fmt.Errorf("duplicate_of must be positive") + } + if status != "Duplicate" { + return nil, fmt.Errorf("duplicate_of can only be used when status is 'Duplicate'") + } + args["duplicate_of"] = duplicate + } + if status == "Duplicate" && duplicate == 0 { + return nil, fmt.Errorf("duplicate_of is required when status is 'Duplicate'") + } + if _, err := OptionalParam[bool](args, "confirm_close"); err != nil { + return nil, err + } + args["issue_number"], args["status"] = number, status + return json.Marshal(args) +} + +// UpdateIssueStatus changes an issue's planning status. +func UpdateIssueStatus(t translations.TranslationHelperFunc) inventory.ServerTool { + return NewTool[IssueStatusInput, *IssueStatusUpdateOutput]( + ToolsetMetadataIssues, + mcp.Tool{ + Name: "update_issue_status", + Description: t("TOOL_UPDATE_ISSUE_STATUS_DESCRIPTION", "Update an issue's planning status. "+ + "Done, Not planned and Duplicate close the issue; the other statuses keep it open or reopen it. "+ + "Closing statuses require confirm_close: true, set only after the user confirms closing the issue. "+ + "Duplicate requires duplicate_of, the canonical issue number in the same repository. A status cannot be removed."), + InputSchema: &jsonschema.Schema{ + Type: "object", + Properties: map[string]*jsonschema.Schema{ + "owner": {Type: "string", Description: "Repository owner (username or organization)"}, + "repo": {Type: "string", Description: "Repository name"}, + "issue_number": {Type: "number", Minimum: new(1.0), Description: "The issue number to update"}, + "status": {Type: "string", Enum: enumValues(issueStatusNames), Description: "The planning status to assign."}, + "duplicate_of": {Type: "number", Minimum: new(1.0), Description: "The canonical issue number. Required only for Duplicate."}, + "confirm_close": { + Type: "boolean", + Description: "Must be true for Done, Not planned or Duplicate. Set only after the user confirms closing the issue.", + }, + }, + Required: []string{"owner", "repo", "issue_number", "status"}, + }, + OutputSchema: issueStatusUpdateOutputSchema(), + Annotations: &mcp.ToolAnnotations{ + Title: t("TOOL_UPDATE_ISSUE_STATUS_USER_TITLE", "Update Issue Status"), + ReadOnlyHint: false, + DestructiveHint: new(true), + OpenWorldHint: new(true), + }, + }, + publicRepositoryWriteScopeAccess(), + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args IssueStatusInput) (*mcp.CallToolResult, *IssueStatusUpdateOutput, error) { + // This is a caller-supplied confirmation policy, not proof that a trusted UI prompted the user. + if slices.Contains(issueClosingStatusNames, args.Status) && !args.ConfirmClose { + return utils.NewToolResultError("confirm_close must be true to use a status that closes the issue"), nil, nil + } + repoPath, err := repositoryAPIPath(args.Owner, args.Repo) + 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 + } + body := struct { + Status string `json:"status"` + DuplicateIssueID *int64 `json:"duplicate_issue_id,omitempty"` + }{Status: args.Status} + if args.DuplicateOf != 0 { + duplicate, resp, err := client.Issues.Get(ctx, args.Owner, args.Repo, args.DuplicateOf) + if resp != nil { + defer func() { _ = resp.Body.Close() }() + } + if err != nil { + return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to get duplicate issue", resp, err), nil, nil + } + body.DuplicateIssueID = duplicate.ID + if body.DuplicateIssueID == nil || *body.DuplicateIssueID < 1 { + return utils.NewToolResultError("failed to get duplicate issue: response did not include a valid issue ID"), nil, nil + } + } + req, err := client.NewRequest(ctx, http.MethodPatch, fmt.Sprintf("%s/issues/%d", repoPath, args.IssueNumber), body) + if err != nil { + return utils.NewToolResultErrorFromErr("failed to create status update request", err), nil, nil + } + var issue issueWithStatus + resp, err := client.Do(req, &issue) + if resp != nil { + defer func() { _ = resp.Body.Close() }() + } + if err != nil { + return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to update issue", resp, err), nil, nil + } + status := issue.planningStatus() + if status == nil || status.Name != args.Status { + return utils.NewToolResultError(fmt.Sprintf("requested status %q was not applied; issue statuses may be unavailable in this repository", args.Status)), nil, nil + } + output := &IssueStatusUpdateOutput{ID: fmt.Sprintf("%d", issue.GetID()), URL: issue.GetHTMLURL(), Status: status} + result := attachRepoVisibilityIFCLabel(ctx, deps, client, args.Owner, args.Repo, MarshalledTextResult(output), ifc.LabelRepoMetadata) + return result, output, nil + }, + granularIssueInputNormalizer(normalizeIssueStatusArguments), + ) +} + +func issueCreationStatusProperty() *jsonschema.Schema { + return &jsonschema.Schema{ + Type: "string", Enum: enumValues(issueCreationStatusNames), + Description: "Initial planning status (create only). Only open statuses are supported. " + + "Backlog is backlog; Todo is planned; In progress and In review are started. " + + "Omit to use the default status, Backlog.", + } +} + +// repositoryAPIPath rejects coordinates that are not single path segments and +// escapes them, so hand-built REST URLs cannot target a different API path. +func repositoryAPIPath(owner, repo string) (string, error) { + for _, segment := range []string{owner, repo} { + if strings.TrimSpace(segment) == "" || segment == "." || segment == ".." || strings.ContainsAny(segment, "/\\") { + return "", fmt.Errorf("owner and repo must be nonempty repository path segments") + } + } + return fmt.Sprintf("repos/%s/%s", url.PathEscape(owner), url.PathEscape(repo)), nil +} + +// createRESTIssue preserves the standard request fields while adding the API's +// status field, which go-github does not yet expose. +func createRESTIssue(ctx context.Context, client *github.Client, owner, repo string, body github.CreateIssueRequest, status string) (*issueWithStatus, *github.Response, error) { + if status == "" { + issue, resp, err := client.Issues.Create(ctx, owner, repo, body) + if err != nil { + return nil, resp, err + } + if issue == nil { + issue = &github.Issue{} + } + return &issueWithStatus{Issue: *issue}, resp, nil + } + repoPath, err := repositoryAPIPath(owner, repo) + if err != nil { + return nil, nil, err + } + requestBody := struct { + github.CreateIssueRequest + Status string `json:"status"` + }{body, status} + req, err := client.NewRequest(ctx, http.MethodPost, repoPath+"/issues", requestBody) + if err != nil { + return nil, nil, err + } + var issue issueWithStatus + resp, err := client.Do(req, &issue) + return &issue, resp, err +} + +// unappliedIssueStatusError reports a created issue whose status differs from +// the requested one, so callers can fix that issue instead of creating another. +func unappliedIssueStatusError(requested string, issue *issueWithStatus) error { + if requested == "" { + return nil + } + applied := "" + if status := issue.planningStatus(); status != nil { + applied = status.Name + } + if applied == requested { + return nil + } + return fmt.Errorf("requested=%q, applied=%q, issue_id=%d, issue_url=%q; issue statuses may be unavailable in this repository; use update_issue_status to correct the issue instead of creating it again", + requested, applied, issue.GetID(), issue.GetHTMLURL()) +} + +func resolveIssueStatusID(ctx context.Context, client *githubv4.Client, owner, repo, status string) (githubv4.ID, error) { + var query struct { + Repository struct { + PlanningStatuses struct { + Nodes []struct { + ID githubv4.ID + Name string + } + } `graphql:"planningStatuses(first: 10)"` + } `graphql:"repository(owner: $owner, name: $repo)"` + } + if err := client.Query(ctx, &query, map[string]any{"owner": githubv4.String(owner), "repo": githubv4.String(repo)}); err != nil { + return nil, err + } + for _, node := range query.Repository.PlanningStatuses.Nodes { + if node.Name == status && node.ID != nil { + return node.ID, nil + } + } + return nil, fmt.Errorf("planning status %q is unavailable in %s/%s", status, owner, repo) +} + +func issueStatusUpdateOutputSchema() *jsonschema.Schema { + schema := issueDTOschema[IssueStatusUpdateOutput]() + schema.Properties["status"] = issuePlanningStatusSchema() + return schema +} diff --git a/pkg/github/issues.go b/pkg/github/issues.go index 30005854aa..f1972b01ee 100644 --- a/pkg/github/issues.go +++ b/pkg/github/issues.go @@ -912,11 +912,19 @@ func getIssue(ctx context.Context, client *github.Client, deps ToolDependencies, } flags := deps.GetFlags(ctx) - issue, resp, err := client.Issues.Get(ctx, owner, repo, issueNumber) + req, err := client.NewRequest(ctx, http.MethodGet, fmt.Sprintf("repos/%s/%s/issues/%d", owner, repo, issueNumber), nil) + if err != nil { + return nil, nil, fmt.Errorf("failed to create issue request: %w", err) + } + var response issueWithStatus + resp, err := client.Do(req, &response) + if resp != nil { + defer func() { _ = resp.Body.Close() }() + } if err != nil { return nil, nil, fmt.Errorf("failed to get issue: %w", err) } - defer func() { _ = resp.Body.Close() }() + issue := &response.Issue if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) @@ -947,7 +955,13 @@ func getIssue(ctx context.Context, client *github.Client, deps ToolDependencies, } } - return MarshalledTextResult(minimalIssue), &IssueReadOutput{Method: "get", Issue: issueDetailsOutput(minimalIssue)}, nil + output := &IssueReadOutput{Method: "get", Issue: issueDetailsOutput(minimalIssue)} + status := response.planningStatus() + output.Issue.Status = status + return MarshalledTextResult(struct { + MinimalIssue + Status *IssuePlanningStatus `json:"status"` + }{minimalIssue, status}), output, nil } // applyIssueReadEnrichment populates the hierarchy relationship signals (has_parent/has_children, @@ -1958,6 +1972,11 @@ const ( searchIssuesLexicalQueryDescription = "Search query using GitHub issues search syntax" ) +func searchIssuesStatusDescription() string { + return `Filter by planning status with the status: qualifier, for example status:"In progress". Statuses: ` + + strings.Join(issueStatusNames, ", ") + "." +} + // SearchIssues creates a tool to search for issues. func SearchIssues(t translations.TranslationHelperFunc, opts ...ToolOption) inventory.ServerTool { cfg := newToolConfig(opts) @@ -1975,6 +1994,7 @@ func SearchIssues(t translations.TranslationHelperFunc, opts ...ToolOption) inve toolDescription = searchIssuesLexicalDescription queryDescription = searchIssuesLexicalQueryDescription } + toolDescription += " " + searchIssuesStatusDescription() schema := &jsonschema.Schema{ Type: "object", @@ -2648,6 +2668,7 @@ var issueWriteFormParams = map[string]struct{}{ "assignees": {}, "milestone": {}, "type": {}, + "status": {}, "state": {}, "state_reason": {}, "duplicate_of": {}, @@ -2684,12 +2705,7 @@ func issueWriteAwaitingFormResult(method, owner, repo string, issueNumber int) * return utils.NewToolResultAwaitingFormSubmission(msg) } -// IssueWrite is the FeatureFlagIssueFields-enabled variant of issue_write -// (with the issue_fields parameter). LegacyIssueWrite is served when the flag -// is off. Both register under the tool name "issue_write"; exactly one is -// active at a time via mutually exclusive feature-flag annotations. When the -// flag is removed, delete LegacyIssueWrite outright and drop the feature-flag -// fields on IssueWrite. +// IssueWrite creates a tool to create or update an issue. func IssueWrite(t translations.TranslationHelperFunc) inventory.ServerTool { st := NewTool[IssueWriteInput, *IssueWriteOutput]( ToolsetMetadataIssues, @@ -3003,11 +3019,15 @@ Options are: switch method { case "create": + status := "" + if input.Status != nil { + status = *input.Status + } if parentProvided { - return issueWriteResult(method)(createIssueWithParent(ctx, client, gqlClient, owner, repo, title, body, assignees, labels, milestoneNum, issueType, parentIssueNumber, parentOwner, parentRepo)) + return issueWriteResult(method)(createIssueWithParent(ctx, client, gqlClient, owner, repo, title, body, assignees, labels, milestoneNum, issueType, parentIssueNumber, parentOwner, parentRepo, status)) } - return issueWriteResult(method)(createIssue(ctx, client, owner, repo, title, body, assignees, labels, milestoneNum, issueType, issueFieldValues)) + return issueWriteResult(method)(createIssue(ctx, client, owner, repo, title, body, assignees, labels, milestoneNum, issueType, issueFieldValues, status)) case "update": issueNumber, err := RequiredInt(args, "issue_number") if err != nil { @@ -3021,7 +3041,10 @@ Options are: default: return utils.NewToolResultError("invalid method, must be either 'create' or 'update'"), nil, nil } - }, normalizeConsolidatedIssueArguments("write")) + }, normalizeIssueCreationStatus(normalizeConsolidatedIssueArguments("write"), true)) + schema := inventory.CloneSchema(st.Tool.InputSchema.(*jsonschema.Schema)) + schema.Properties["status"] = issueCreationStatusProperty() + st.Tool.InputSchema = schema st.FeatureRule = issuesConsolidatedFeatureRule return st } @@ -3036,6 +3059,7 @@ type CreateIssueInput struct { LabelIDs *[]githubv4.ID `json:"labelIds,omitempty"` IssueTypeID *githubv4.ID `json:"issueTypeId,omitempty"` ParentIssueID *githubv4.ID `json:"parentIssueId,omitempty"` + StatusID *githubv4.ID `json:"statusId,omitempty"` } type createIssueMutation struct { @@ -3077,11 +3101,12 @@ func CreateIssueWithParent( parentOwner string, parentRepo string, ) (*mcp.CallToolResult, error) { - result, _, err := createIssueWithParent(ctx, client, gqlClient, owner, repo, title, body, assignees, labels, milestoneNumber, issueType, parentIssueNumber, parentOwner, parentRepo) + result, _, err := createIssueWithParent(ctx, client, gqlClient, owner, repo, title, body, assignees, labels, milestoneNumber, issueType, parentIssueNumber, parentOwner, parentRepo, "") return result, err } -func createIssueWithParent(ctx context.Context, client *github.Client, gqlClient *githubv4.Client, owner, repo, title, body string, assignees, labels []string, milestoneNumber int, issueType string, parentIssueNumber int, parentOwner, parentRepo string) (*mcp.CallToolResult, *MinimalResponse, error) { +// createIssueWithParent sets the initial planning status unless status is empty. +func createIssueWithParent(ctx context.Context, client *github.Client, gqlClient *githubv4.Client, owner, repo, title, body string, assignees, labels []string, milestoneNumber int, issueType string, parentIssueNumber int, parentOwner, parentRepo, status string) (*mcp.CallToolResult, *MinimalResponse, error) { if title == "" { return utils.NewToolResultError("missing required parameter: title"), nil, nil } @@ -3144,6 +3169,14 @@ func createIssueWithParent(ctx context.Context, client *github.Client, gqlClient input.IssueTypeID = &issueTypeID } + if status != "" { + statusID, err := resolveIssueStatusID(ctx, gqlClient, owner, repo, status) + if err != nil { + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to resolve planning status", err), nil, nil + } + input.StatusID = &statusID + } + var mutation createIssueMutation if err := gqlClient.Mutate(ctx, &mutation, input, nil); err != nil { return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to create issue", err), nil, nil @@ -3313,11 +3346,12 @@ func containsIssueLabel(labels []string, target string) bool { } func CreateIssue(ctx context.Context, client *github.Client, owner string, repo string, title string, body string, assignees []string, labels []string, milestoneNum int, issueType string, issueFieldValues []*github.IssueRequestFieldValue) (*mcp.CallToolResult, error) { - result, _, err := createIssue(ctx, client, owner, repo, title, body, assignees, labels, milestoneNum, issueType, issueFieldValues) + result, _, err := createIssue(ctx, client, owner, repo, title, body, assignees, labels, milestoneNum, issueType, issueFieldValues, "") return result, err } -func createIssue(ctx context.Context, client *github.Client, owner string, repo string, title string, body string, assignees []string, labels []string, milestoneNum int, issueType string, issueFieldValues []*github.IssueRequestFieldValue) (*mcp.CallToolResult, *MinimalResponse, error) { +// createIssue sets the initial planning status unless status is empty. +func createIssue(ctx context.Context, client *github.Client, owner string, repo string, title string, body string, assignees []string, labels []string, milestoneNum int, issueType string, issueFieldValues []*github.IssueRequestFieldValue, status string) (*mcp.CallToolResult, *MinimalResponse, error) { if title == "" { return utils.NewToolResultError("missing required parameter: title"), nil, nil } @@ -3339,15 +3373,13 @@ func createIssue(ctx context.Context, client *github.Client, owner string, repo issueRequest.Type = new(issueType) } - issue, resp, err := client.Issues.Create(ctx, owner, repo, issueRequest) + issue, resp, err := createRESTIssue(ctx, client, owner, repo, issueRequest, status) + if resp != nil { + defer func() { _ = resp.Body.Close() }() + } if err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, - "failed to create issue", - resp, - err, - ), nil, nil + return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to create issue", resp, err), nil, nil } - defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusCreated { body, err := io.ReadAll(resp.Body) @@ -3358,11 +3390,15 @@ func createIssue(ctx context.Context, client *github.Client, owner string, repo } if len(labels) > 0 { - if err := unappliedIssueLabelsError(labels, issue); err != nil { + if err := unappliedIssueLabelsError(labels, &issue.Issue); err != nil { return ghErrors.NewGitHubAPIErrorResponse(ctx, "issue created but requested labels were not fully applied", resp, err), nil, nil } } + if err := unappliedIssueStatusError(status, issue); err != nil { + return ghErrors.NewGitHubAPIErrorResponse(ctx, "issue created but requested status was not applied", resp, err), nil, nil + } + // Return minimal response with just essential information minimalResponse := MinimalResponse{ ID: fmt.Sprintf("%d", issue.GetID()), diff --git a/pkg/github/issues_granular.go b/pkg/github/issues_granular.go index eab4a204cd..c51aad10d8 100644 --- a/pkg/github/issues_granular.go +++ b/pkg/github/issues_granular.go @@ -170,23 +170,30 @@ func GranularCreateIssue(t translations.TranslationHelperFunc) inventory.ServerT if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub GraphQL client", err), nil, nil } - result, output, err := createIssueWithParent(ctx, client, gqlClient, owner, repo, title, body, nil, nil, 0, "", parentIssueNumber, parentOwner, parentRepo) - return result, output, err + return createIssueWithParent(ctx, client, gqlClient, owner, repo, title, body, nil, nil, 0, "", parentIssueNumber, parentOwner, parentRepo, args.Status) } - issue, resp, err := client.Issues.Create(ctx, owner, repo, issueReq) + issue, resp, err := createRESTIssue(ctx, client, owner, repo, issueReq, args.Status) + if resp != nil { + defer func() { _ = resp.Body.Close() }() + } if err != nil { return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to create issue", resp, err), nil, nil } - defer func() { _ = resp.Body.Close() }() + if err := unappliedIssueStatusError(args.Status, issue); err != nil { + return ghErrors.NewGitHubAPIErrorResponse(ctx, "issue created but requested status was not applied", resp, err), nil, nil + } return granularIssueMinimalResult(&MinimalResponse{ ID: fmt.Sprintf("%d", issue.GetID()), URL: issue.GetHTMLURL(), }) }, - granularIssueInputNormalizer(normalizeGranularCreateIssueArguments), + granularIssueInputNormalizer(normalizeIssueCreationStatus(normalizeGranularCreateIssueArguments, false)), ) + schema := inventory.CloneSchema(st.Tool.InputSchema.(*jsonschema.Schema)) + schema.Properties["status"] = issueCreationStatusProperty() + st.Tool.InputSchema = schema st.FeatureRule = issuesGranularFeatureRule return st } diff --git a/pkg/github/issues_test.go b/pkg/github/issues_test.go index 79eeb22100..308dbe81d2 100644 --- a/pkg/github/issues_test.go +++ b/pkg/github/issues_test.go @@ -1847,6 +1847,7 @@ func Test_CreateIssue(t *testing.T) { assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "milestone") assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "type") assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "issue_fields") + assert.Contains(t, tool.InputSchema.(*jsonschema.Schema).Properties, "status") assert.ElementsMatch(t, tool.InputSchema.(*jsonschema.Schema).Required, []string{"method", "owner", "repo"}) // Setup mock issue for success case @@ -2266,6 +2267,67 @@ func Test_IssueWrite_MCPAppsFeature_UIGate(t *testing.T) { "non-UI client should execute directly") }) + t.Run("UI client with initial status routes through UI form", func(t *testing.T) { + for _, status := range []string{"Backlog", "Todo", "In progress", "In review", "in progress"} { + t.Run(status, func(t *testing.T) { + request := createMCPRequestWithSession(t, ClientNameVSCodeInsiders, true, map[string]any{ + "method": "create", + "owner": "owner", + "repo": "repo", + "title": "Test", + "status": status, + }) + result, err := handler(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + assert.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, "interactive form has been shown to the user for creating a new issue") + }) + } + }) + + t.Run("UI client submits selected status", func(t *testing.T) { + calls := 0 + statusClient := mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + PostReposIssuesByOwnerByRepo: func(w http.ResponseWriter, r *http.Request) { + calls++ + var body map[string]any + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + assert.Equal(t, "In review", body["status"]) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + _, _ = io.WriteString(w, `{"number":1,"title":"Test","html_url":"https://github.com/owner/repo/issues/1","status":{"id":1,"name":"In review","category":"started"}}`) + }, + })) + statusDeps := BaseDeps{Client: statusClient, GQLClient: githubv4.NewClient(nil), featureChecker: featureCheckerFor()} + request := createMCPRequestWithSession(t, ClientNameVSCodeInsiders, true, map[string]any{ + "method": "create", + "owner": "owner", + "repo": "repo", + "title": "Test", + "status": "in review", + "_ui_submitted": true, + }) + result, err := serverTool.Handler(statusDeps)(ContextWithDeps(context.Background(), statusDeps), &request) + require.NoError(t, err) + require.False(t, result.IsError, getTextResult(t, result).Text) + assert.Equal(t, 1, calls) + assert.Contains(t, getTextResult(t, result).Text, "https://github.com/owner/repo/issues/1") + }) + + t.Run("UI client cannot set initial status on update", func(t *testing.T) { + request := createMCPRequestWithSession(t, ClientNameVSCodeInsiders, true, map[string]any{ + "method": "update", + "owner": "owner", + "repo": "repo", + "issue_number": float64(1), + "status": "Todo", + }) + result, err := handler(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, "status is only supported with the create method") + }) + t.Run("UI client with state change routes through UI form", func(t *testing.T) { // state/state_reason/duplicate_of are form params (the issue-write view // renders close/reopen controls), so a call carrying them must go to @@ -3072,6 +3134,7 @@ func Test_issueWriteHasNonFormParams(t *testing.T) { {name: "state present", args: map[string]any{"state": "closed"}, want: false}, {name: "state_reason present", args: map[string]any{"state_reason": "completed"}, want: false}, {name: "duplicate_of present", args: map[string]any{"duplicate_of": float64(7)}, want: false}, + {name: "status present", args: map[string]any{"status": "Todo"}, want: false}, {name: "parent issue present", args: map[string]any{"parent_issue_number": float64(7)}, want: true}, {name: "parent owner present", args: map[string]any{"parent_owner": "octo-org"}, want: true}, {name: "parent repo present", args: map[string]any{"parent_repo": "parent-repo"}, want: true}, @@ -3183,31 +3246,19 @@ func Test_issueWriteSchemaClassification(t *testing.T) { "parent_repo": {}, } - cases := []struct { - name string - tool inventory.ServerTool - }{ - {name: "IssueWrite", tool: IssueWrite(translations.NullTranslationHelper)}, - } + schema, ok := IssueWrite(translations.NullTranslationHelper).Tool.InputSchema.(*jsonschema.Schema) + require.True(t, ok, "InputSchema should be *jsonschema.Schema") - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - schema, ok := tc.tool.Tool.InputSchema.(*jsonschema.Schema) - require.True(t, ok, "InputSchema should be *jsonschema.Schema") - - for prop := range schema.Properties { - _, isForm := issueWriteFormParams[prop] - _, isNonForm := knownNonForm[prop] - - assert.Falsef(t, isForm && isNonForm, - "property %q is classified as both form-resendable and non-form — pick one", prop) - assert.Truef(t, isForm || isNonForm, - "property %q in %s schema is unclassified — add it to issueWriteFormParams (pkg/github/issues.go) "+ - "if the MCP App form can carry it on submit, otherwise add it to the knownNonForm allowlist in this test", - prop, tc.name) - } - }) + for prop := range schema.Properties { + _, isForm := issueWriteFormParams[prop] + _, isNonForm := knownNonForm[prop] + + assert.Falsef(t, isForm && isNonForm, + "property %q is classified as both form-resendable and non-form — pick one", prop) + assert.Truef(t, isForm || isNonForm, + "property %q in IssueWrite schema is unclassified — add it to issueWriteFormParams (pkg/github/issues.go) "+ + "if the MCP App form can carry it on submit, otherwise add it to the knownNonForm allowlist in this test", + prop) } } diff --git a/pkg/github/search_semantic_test.go b/pkg/github/search_semantic_test.go index 102664d08c..86092d347c 100644 --- a/pkg/github/search_semantic_test.go +++ b/pkg/github/search_semantic_test.go @@ -74,8 +74,8 @@ func Test_searchIssuesTool_descriptionMatchesEngine(t *testing.T) { require.Equal(t, "search_issues", semantic.Tool.Name) require.Equal(t, "search_issues", lexical.Tool.Name) - assert.Equal(t, searchIssuesSemanticDescription, semantic.Tool.Description) - assert.Equal(t, searchIssuesLexicalDescription, lexical.Tool.Description) + assert.Equal(t, searchIssuesSemanticDescription+" "+searchIssuesStatusDescription(), semantic.Tool.Description) + assert.Equal(t, searchIssuesLexicalDescription+" "+searchIssuesStatusDescription(), lexical.Tool.Description) semanticSchema, ok := semantic.Tool.InputSchema.(*jsonschema.Schema) require.True(t, ok) diff --git a/pkg/github/tools.go b/pkg/github/tools.go index 32f706b9a9..fd34ae73e6 100644 --- a/pkg/github/tools.go +++ b/pkg/github/tools.go @@ -264,6 +264,7 @@ func AllTools(t translations.TranslationHelperFunc, opts ...ToolOption) []invent ListIssueTypes(t), ListIssueFields(t), IssueWrite(t), + UpdateIssueStatus(t), AddIssueComment(t), UpdateIssueComment(t), SubIssueWrite(t), diff --git a/pkg/github/typed_consolidated_issue_enrichment_test.go b/pkg/github/typed_consolidated_issue_enrichment_test.go index 2e02dcf09c..f703ae91cc 100644 --- a/pkg/github/typed_consolidated_issue_enrichment_test.go +++ b/pkg/github/typed_consolidated_issue_enrichment_test.go @@ -87,7 +87,7 @@ func TestTypedIssueReadEnrichmentAndLockdown(t *testing.T) { if !lockdown { text += `{"number":8,"title":"Closing","state":"OPEN","url":"closing","repository":"owner/repo"}` } - text += `]}}` + text += `]},"status":null}` result := assertConsolidatedResult(t, session, schemas, "issue_read", map[string]any{ "method": "get", "owner": "owner", "repo": "repo", "issue_number": 1, }, text) diff --git a/pkg/github/typed_consolidated_issue_outputs_test.go b/pkg/github/typed_consolidated_issue_outputs_test.go index 60374e10cb..2e4186f7ed 100644 --- a/pkg/github/typed_consolidated_issue_outputs_test.go +++ b/pkg/github/typed_consolidated_issue_outputs_test.go @@ -10,7 +10,10 @@ import ( "testing" "time" + "github.com/github/github-mcp-server/v2/internal/githubv4mock" + "github.com/github/github-mcp-server/v2/internal/toolsnaps" ghcontext "github.com/github/github-mcp-server/v2/pkg/context" + "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/sanitize" "github.com/github/github-mcp-server/v2/pkg/translations" @@ -22,6 +25,272 @@ import ( "github.com/stretchr/testify/require" ) +func issueStatusSession(t *testing.T, deps BaseDeps, protocol string, flags ...inventory.FeatureFlag) (*mcp.ClientSession, []*mcp.Tool) { + t.Helper() + translate := translations.NullTranslationHelper + tools := []inventory.ServerTool{ + IssueRead(translate), IssueWrite(translate), GranularCreateIssue(translate), + SearchIssues(translate), UpdateIssueStatus(translate), + } + checker := featureCheckerFor(flags...) + inv, err := inventory.NewBuilder().SetTools(tools).WithToolsets([]string{"all"}).WithFeatureChecker(checker).Build() + require.NoError(t, err) + server := mcp.NewServer(&mcp.Implementation{Name: "issue-statuses", Version: "v1"}, nil) + server.AddReceivingMiddleware(InjectDepsMiddleware(deps)) + inv.RegisterTools(context.Background(), server, deps) + session := connectCommentVisibilityClient(t, server, protocol) + list, err := session.ListTools(context.Background(), nil) + require.NoError(t, err) + return session, list.Tools +} + +func TestIssuePlanningStatusToolAvailability(t *testing.T) { + for _, granular := range []bool{false, true} { + t.Run(fmt.Sprintf("granular=%t", granular), func(t *testing.T) { + var flags []inventory.FeatureFlag + if granular { + flags = append(flags, inventory.FeatureFlag(FeatureFlagIssuesGranular)) + } + _, tools := issueStatusSession(t, BaseDeps{}, inventory.ProtocolVersionMultiRoundTrip, flags...) + names := make(map[string]bool) + for _, tool := range tools { + require.False(t, names[tool.Name], "duplicate registration: %s", tool.Name) + names[tool.Name] = true + var input, output jsonschema.Schema + require.NoError(t, json.Unmarshal([]byte(mustMarshalJSON(t, tool.InputSchema)), &input)) + require.NoError(t, json.Unmarshal([]byte(mustMarshalJSON(t, tool.OutputSchema)), &output)) + if tool.Name == "issue_write" || tool.Name == "create_issue" { + assert.Contains(t, input.Properties, "status") + } + if tool.Name == "issue_read" { + assert.Contains(t, output.Properties["issue"].Properties, "status") + } + if tool.Name == "search_issues" { + assert.Contains(t, tool.Description, "status:") + } + } + assert.Equal(t, granular, names["create_issue"]) + assert.Equal(t, !granular, names["issue_write"]) + assert.True(t, names["update_issue_status"]) + }) + } +} + +func TestUpdateIssueStatusWireContract(t *testing.T) { + const expected = `{"id":"123","url":"https://github.com/owner/repo/issues/42","status":{"id":4,"name":"Todo","category":"planned"}}` + for _, protocol := range []string{inventory.ProtocolVersionMultiRoundTrip, "2025-11-25"} { + t.Run(protocol, func(t *testing.T) { + rest := &http.Client{Transport: recorderTransport{handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodPatch, r.Method) + assert.Equal(t, "/repos/owner/repo/issues/42", r.URL.Path) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":123,"html_url":"https://github.com/owner/repo/issues/42","status":{"id":4,"name":"Todo","category":"planned"}}`)) + })}} + session, tools := issueStatusSession(t, BaseDeps{Client: mustNewGHClient(t, rest)}, protocol) + + var outputSchema *jsonschema.Resolved + found := false + for _, tool := range tools { + if tool.Name != "update_issue_status" { + continue + } + found = true + if protocol == inventory.ProtocolVersionMultiRoundTrip { + require.NoError(t, toolsnaps.Test(tool.Name, *tool)) + var schema jsonschema.Schema + require.NoError(t, json.Unmarshal([]byte(mustMarshalJSON(t, tool.OutputSchema)), &schema)) + var err error + outputSchema, err = schema.Resolve(nil) + require.NoError(t, err) + } else { + assert.Nil(t, tool.OutputSchema) + } + } + require.True(t, found) + + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: "update_issue_status", Arguments: map[string]any{ + "owner": "owner", "repo": "repo", "issue_number": 42, "status": "Todo", + }}) + require.NoError(t, err) + require.False(t, result.IsError, "%s", getTextResult(t, result).Text) + assert.JSONEq(t, expected, getTextResult(t, result).Text) + if protocol == inventory.ProtocolVersionMultiRoundTrip { + require.NotNil(t, outputSchema) + assert.JSONEq(t, expected, mustMarshalJSON(t, result.StructuredContent)) + var output any + require.NoError(t, json.Unmarshal([]byte(mustMarshalJSON(t, result.StructuredContent)), &output)) + require.NoError(t, outputSchema.Validate(output)) + } else { + assert.Nil(t, result.StructuredContent) + } + }) + } +} + +func TestUpdateIssueStatusIFCLabel(t *testing.T) { + for _, protocol := range []string{inventory.ProtocolVersionMultiRoundTrip, "2025-11-25"} { + for _, private := range []bool{false, true} { + for _, enabled := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/private=%t/enabled=%t", protocol, private, enabled), func(t *testing.T) { + lookups := 0 + rest := &http.Client{Transport: recorderTransport{handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method == http.MethodGet { + lookups++ + assert.Equal(t, "/repos/owner/repo", r.URL.Path) + _, _ = fmt.Fprintf(w, `{"private":%t}`, private) + return + } + assert.Equal(t, http.MethodPatch, r.Method) + _, _ = w.Write([]byte(`{"id":123,"html_url":"https://github.com/owner/repo/issues/42","status":{"id":4,"name":"Todo","category":"planned"}}`)) + })}} + deps := BaseDeps{Client: mustNewGHClient(t, rest)} + if enabled { + deps.featureChecker = featureCheckerFor(FeatureFlagIFCLabels) + } + session, _ := issueStatusSession(t, deps, protocol) + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: "update_issue_status", Arguments: map[string]any{ + "owner": "owner", "repo": "repo", "issue_number": 42, "status": "Todo", + }}) + require.NoError(t, err) + require.False(t, result.IsError) + if enabled { + assert.JSONEq(t, mustMarshalJSON(t, ifc.LabelRepoMetadata(private)), mustMarshalJSON(t, result.Meta["ifc"])) + assert.Equal(t, 1, lookups) + } else { + assert.NotContains(t, result.Meta, "ifc") + assert.Zero(t, lookups) + } + }) + } + } + } +} + +func TestIssuePlanningStatusRead(t *testing.T) { + const inProgress = `{"id":4,"name":"In progress","category":"started"}` + unrecognized := []string{`{"id":9,"name":"Blocked","category":"started"}`, `{"id":9,"name":"Todo","category":"custom"}`, `"Todo"`} + for _, protocol := range []string{inventory.ProtocolVersionMultiRoundTrip, "2025-11-25"} { + for _, status := range append([]string{inProgress, "null", ""}, unrecognized...) { + t.Run(fmt.Sprintf("%s/status=%s", protocol, status), func(t *testing.T) { + calls := 0 + rest := &http.Client{Transport: recorderTransport{handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.Equal(t, http.MethodGet, r.Method) + assert.Equal(t, "/repos/owner/repo/issues/42", r.URL.Path) + payload := `{"id":123,"number":42,"title":"Subject","state":"open"}` + if status != "" { + payload = strings.TrimSuffix(payload, "}") + `,"status":` + status + "}" + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(payload)) + })}} + deps := BaseDeps{Client: mustNewGHClient(t, rest), GQLClient: defaultGQLClient, RepoAccessCache: stubRepoAccessCache(nil, time.Minute)} + session, tools := issueStatusSession(t, deps, protocol) + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: "issue_read", Arguments: map[string]any{ + "method": "get", "owner": "owner", "repo": "repo", "issue_number": 42, + }}) + require.NoError(t, err) + require.False(t, result.IsError, "%s", getTextResult(t, result).Text) + assert.Equal(t, 1, calls, "status must use the original issue GET") + var output map[string]any + require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &output)) + if protocol == inventory.ProtocolVersionMultiRoundTrip { + assert.JSONEq(t, mustMarshalJSON(t, result.StructuredContent), getTextResult(t, result).Text) + for _, tool := range tools { + if tool.Name == "issue_read" { + var schema jsonschema.Schema + require.NoError(t, json.Unmarshal([]byte(mustMarshalJSON(t, tool.OutputSchema)), &schema)) + resolved, err := schema.Resolve(nil) + require.NoError(t, err) + require.NoError(t, resolved.Validate(output)) + } + } + output = output["issue"].(map[string]any) + } + value, present := output["status"] + assert.True(t, present) + if status == inProgress { + assert.JSONEq(t, status, mustMarshalJSON(t, value)) + } else { + assert.Nil(t, value, "missing and unrecognized statuses must be null") + } + }) + } + } +} + +func TestIssuePlanningStatusCreation(t *testing.T) { + for _, protocol := range []string{inventory.ProtocolVersionMultiRoundTrip, "2025-11-25"} { + for _, tc := range []struct{ granular, parent bool }{ + {false, false}, {false, true}, {true, false}, {true, true}, + } { + granular, parent := tc.granular, tc.parent + t.Run(fmt.Sprintf("%s/granular=%t/parent=%t", protocol, granular, parent), func(t *testing.T) { + calls := 0 + rest := &http.Client{Transport: recorderTransport{handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.Equal(t, http.MethodPost, r.Method) + assert.Equal(t, "/repos/owner/repo/issues", r.URL.Path) + var body map[string]any + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + assert.Equal(t, "In review", body["status"]) + assert.Equal(t, "Subject", body["title"]) + assert.Equal(t, "Body", body["body"]) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"id":123,"number":42,"html_url":"https://github.com/owner/repo/issues/42","status":{"id":5,"name":"In review","category":"started"}}`)) + })}} + gql := defaultGQLClient + if parent { + parentID, statusID := githubv4.ID("I_parent"), githubv4.ID("IS_review") + gql = githubv4.NewClient(githubv4mock.NewMockedHTTPClient( + createIssueParentMatcher(3, "owner", "repo", "R_repo", "I_parent"), + githubv4mock.NewQueryMatcher( + "query($owner:String!$repo:String!){repository(owner: $owner, name: $repo){planningStatuses(first: 10){nodes{id,name}}}}", + map[string]any{"owner": "owner", "repo": "repo"}, + githubv4mock.DataResponse(map[string]any{"repository": map[string]any{"planningStatuses": map[string]any{"nodes": []any{map[string]any{"id": "IS_review", "name": "In review"}}}}}), + ), + githubv4mock.NewMutationMatcher(createIssueMutation{}, CreateIssueInput{ + RepositoryID: githubv4.ID("R_repo"), Title: githubv4.String("Subject"), Body: githubv4.NewString("Body"), + ParentIssueID: &parentID, StatusID: &statusID, + }, nil, githubv4mock.DataResponse(map[string]any{"createIssue": map[string]any{"issue": map[string]any{ + "fullDatabaseId": "123", "url": "https://github.com/owner/repo/issues/42", + }}})), + )) + } + deps := BaseDeps{Client: mustNewGHClient(t, rest), GQLClient: gql} + var flags []inventory.FeatureFlag + name := "issue_write" + args := map[string]any{"owner": "owner", "repo": "repo", "title": "Subject", "body": "Body", "status": "in review"} + if granular { + flags = append(flags, inventory.FeatureFlag(FeatureFlagIssuesGranular)) + name = "create_issue" + } else { + args["method"] = "create" + } + if parent { + args["parent_issue_number"] = 3 + } + session, _ := issueStatusSession(t, deps, protocol, flags...) + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: name, Arguments: args}) + require.NoError(t, err) + require.False(t, result.IsError, "%s", getTextResult(t, result).Text) + if protocol == inventory.ProtocolVersionMultiRoundTrip && !granular { + assert.JSONEq(t, `{"method":"create","issue":{"id":"123","url":"https://github.com/owner/repo/issues/42"}}`, getTextResult(t, result).Text) + } else { + assert.JSONEq(t, `{"id":"123","url":"https://github.com/owner/repo/issues/42"}`, getTextResult(t, result).Text) + } + if parent { + assert.Zero(t, calls, "parent and status must be created atomically, without a REST write") + } else { + assert.Equal(t, 1, calls) + } + }) + } + } +} + func consolidatedIssueSession(t *testing.T, deps BaseDeps, protocol string, ui bool) (*mcp.ClientSession, map[string]*jsonschema.Resolved) { t.Helper() tools := []inventory.ServerTool{ @@ -251,7 +520,7 @@ func TestTypedConsolidatedIssueOutputs(t *testing.T) { args map[string]any text string }{ - {"issue_read", map[string]any{"method": "get", "issue_number": "1.0"}, `{"number":1,"title":"Subject","state":"open","html_url":"https://github.com/owner/repo/issues/1","assignees":[]}`}, + {"issue_read", map[string]any{"method": "get", "issue_number": "1.0"}, `{"number":1,"title":"Subject","state":"open","html_url":"https://github.com/owner/repo/issues/1","assignees":[],"status":null}`}, {"issue_read", map[string]any{"method": "get_comments", "issue_number": "1", "page": "0", "perPage": "0"}, `[{"id":42,"body":"hello","html_url":"https://github.com/owner/repo/issues/1#issuecomment-42"}]`}, {"issue_read", map[string]any{"method": "get_comments", "issue_number": 2}, `[]`}, {"issue_read", map[string]any{"method": "get_comments", "issue_number": 3}, `[]`}, @@ -444,7 +713,7 @@ func TestConsolidatedIssueStrictSchemasAndScalars(t *testing.T) { }{ { issueReadOutputSchema(), - []string{`{"method":"get","issue":null}`, `{"method":"get_comments","comments":[]}`, `{"method":"get_sub_issues","sub_issues":[null]}`, `{"method":"get_parent","parent":null}`, `{"method":"get","issue":{"number":0,"title":"","state":"","assignees":[]}}`, `{"method":"get_labels","labels":[],"totalCount":0}`}, + []string{`{"method":"get","issue":null}`, `{"method":"get_comments","comments":[]}`, `{"method":"get_sub_issues","sub_issues":[null]}`, `{"method":"get_parent","parent":null}`, `{"method":"get","issue":{"number":0,"title":"","state":"","assignees":[],"status":null}}`, `{"method":"get_labels","labels":[],"totalCount":0}`}, []string{`null`, `[]`, `{}`, `{"method":"get"}`, `{"method":"get","comments":[]}`, `{"method":"get","issue":{"number":1}}`, `{"method":"get_parent","parent":{"number":1}}`, `{"method":"get_labels","labels":[]}`, `{"method":"get","issue":null,"comments":[]}`}, }, { diff --git a/pkg/github/typed_issue_outputs_test.go b/pkg/github/typed_issue_outputs_test.go index 698abdf01a..f6c139cff5 100644 --- a/pkg/github/typed_issue_outputs_test.go +++ b/pkg/github/typed_issue_outputs_test.go @@ -94,7 +94,7 @@ func TestTypedIssueOutputs(t *testing.T) { // These tools remain feature-gated in production. Enable their existing // feature rules in the contract harness rather than clearing the rules. inv, err := inventory.NewBuilder().SetTools(tools).WithToolsets([]string{"all"}). - WithFeatureChecker(func(context.Context, string) (bool, error) { return true, nil }).Build() + WithFeatureChecker(featureCheckerFor(FeatureFlagIssueDependencies, FeatureFlagDuplicateDetection)).Build() require.NoError(t, err) const commentText = `{"id":"42","url":"https://github.com/owner/repo/issues/123#issuecomment-42"}` @@ -107,7 +107,7 @@ func TestTypedIssueOutputs(t *testing.T) { text string structured string }{ - {name: "issue_read", args: map[string]any{"method": "get", "owner": "owner", "repo": "repo", "issue_number": "7.0", "page": "0", "perPage": "0"}, text: `{"number":7,"title":"Blocker","state":"open","html_url":"https://github.com/owner/repo/issues/7","assignees":[]}`, structured: `{"method":"get","issue":{"number":7,"title":"Blocker","state":"open","html_url":"https://github.com/owner/repo/issues/7","assignees":[]}}`}, + {name: "issue_read", args: map[string]any{"method": "get", "owner": "owner", "repo": "repo", "issue_number": "7.0", "page": "0", "perPage": "0"}, text: `{"number":7,"title":"Blocker","state":"open","html_url":"https://github.com/owner/repo/issues/7","assignees":[],"status":null}`, structured: `{"method":"get","issue":{"number":7,"title":"Blocker","state":"open","html_url":"https://github.com/owner/repo/issues/7","assignees":[],"status":null}}`}, {name: "list_issue_types", args: map[string]any{"owner": "owner"}, text: `[{"id":1,"name":"Bug","is_enabled":false}]`, structured: `[{"id":1,"name":"Bug","is_enabled":false}]`}, {name: "list_issue_types", args: map[string]any{"owner": "owner", "repo": "repo"}, text: `[{"id":1,"name":"Bug","is_enabled":false}]`, structured: `[{"id":1,"name":"Bug","is_enabled":false}]`}, {name: "list_issue_fields", args: map[string]any{"owner": "owner"}, text: `[{"id":"IF_1","full_database_id":99,"name":"Priority","description":"Importance","data_type":"SINGLE_SELECT","visibility":"ALL","options":[{"id":"OPT_1","name":"High","color":"red","priority":0}]}]`, structured: `[{"id":"IF_1","full_database_id":99,"name":"Priority","description":"Importance","data_type":"SINGLE_SELECT","visibility":"ALL","options":[{"id":"OPT_1","name":"High","color":"red","priority":0}]}]`}, diff --git a/pkg/http/server_test.go b/pkg/http/server_test.go index 2b69f77a00..1b2e66a4d1 100644 --- a/pkg/http/server_test.go +++ b/pkg/http/server_test.go @@ -347,7 +347,8 @@ func TestInitGlobalToolScopeMapUsesHost(t *testing.T) { require.NoError(t, initGlobalToolScopeMap(translator, tt.hostType)) tool := github.SearchIssues(translator, github.WithHost(tt.hostType)) - assert.Equal(t, tt.want, tool.Tool.Description) + assert.True(t, strings.HasPrefix(tool.Tool.Description, tt.want)) + assert.Contains(t, tool.Tool.Description, "status:") }) } } diff --git a/pkg/skills/catalog/skills/issue-authoring/SKILL.md b/pkg/skills/catalog/skills/issue-authoring/SKILL.md index 8e7d77f4cc..b008d377f7 100644 --- a/pkg/skills/catalog/skills/issue-authoring/SKILL.md +++ b/pkg/skills/catalog/skills/issue-authoring/SKILL.md @@ -62,6 +62,9 @@ do it. - `labels` — must already exist on the repository. This tool applies labels; it does not create them. - `assignees` — assigning someone is a claim on their time. Only from an instruction. +- `status` — on `issue_write` or `create_issue`, creation accepts Backlog, Todo, + In progress or In review. The parent and initial status can be set atomically. + Closed statuses cannot be assigned at creation. - `sub_issue_id` on `sub_issue_write` — the internal identifier, which is not the issue number. Read it from the issue rather than assuming the number will work. @@ -92,6 +95,8 @@ do it. labels is a separate decision that affects the whole repository. - **The account cannot write** — the issue cannot be filed from here. Give the complete text so it can be filed by hand rather than losing it. +- **A write only partially succeeds** — report what was saved and what failed. + Make any corrections on the existing issue rather than repeating creation. - **The report is not reproducible and not specific** — say what is missing rather than filing something that will be closed for lack of detail. An unfiled question is recoverable; a vague issue occupies someone's attention and then dies. diff --git a/pkg/skills/catalog/skills/issue-backlog-triage/SKILL.md b/pkg/skills/catalog/skills/issue-backlog-triage/SKILL.md index 0b9c717e8a..18f7e10e7d 100644 --- a/pkg/skills/catalog/skills/issue-backlog-triage/SKILL.md +++ b/pkg/skills/catalog/skills/issue-backlog-triage/SKILL.md @@ -62,6 +62,13 @@ important one in the backlog; judge on content, not on dates alone. - `state_reason` — `completed`, `not_planned`, or `duplicate`. Closing without one loses the only durable signal about why. - `duplicate_of` — required when `state_reason` is `duplicate`. +- `issue_read` with `method: get` returns `status` as an ID, name and category, + or null. Filter `search_issues` with `status:"In progress"` or another fixed status. + Use `update_issue_status` for Backlog, Todo, In progress, In review, Done, + Not planned or Duplicate. Done, Not planned and Duplicate close the issue + and require `confirm_close: true`, set only after the user confirms closing; + the others keep it open or reopen it. Duplicate requires `duplicate_of`, + the canonical issue number in the same repository. Status cannot be removed. - `type` — only valid if `list_issue_types` returned it. Guessing a type fails the whole call. - `updated_at` against `created_at` — age of the report and age of the last activity diff --git a/pkg/skills/catalog/tools.go b/pkg/skills/catalog/tools.go index 71240e924e..44cb772708 100644 --- a/pkg/skills/catalog/tools.go +++ b/pkg/skills/catalog/tools.go @@ -30,7 +30,7 @@ var requirements = map[string]toolRequirements{ }, "issue-backlog-triage": { required: [][]string{{"list_issues"}, {"issue_write", "update_issue_state"}}, - optional: []string{"search_issues", "issue_read", "sub_issue_write", "add_issue_comment", "list_label", "list_issue_types", "find_duplicate", "add_sub_issue", "remove_sub_issue", "reprioritize_sub_issue", "set_issue_fields", "update_issue_assignees", "update_issue_body", "update_issue_labels", "update_issue_milestone", "update_issue_title", "update_issue_type"}, + optional: []string{"search_issues", "issue_read", "sub_issue_write", "add_issue_comment", "list_label", "list_issue_types", "find_duplicate", "add_sub_issue", "remove_sub_issue", "reprioritize_sub_issue", "set_issue_fields", "update_issue_assignees", "update_issue_body", "update_issue_labels", "update_issue_milestone", "update_issue_title", "update_issue_type", "update_issue_status"}, }, "label-scheme-management": { required: [][]string{{"list_label"}, {"label_write"}}, diff --git a/ui/src/apps/issue-write/App.tsx b/ui/src/apps/issue-write/App.tsx index 5cfb5d83a4..567e824d04 100644 --- a/ui/src/apps/issue-write/App.tsx +++ b/ui/src/apps/issue-write/App.tsx @@ -116,6 +116,8 @@ const stateReasonOptions: Array<{ value: StateReason; label: string; description { value: "duplicate", label: "Duplicate", description: "Another issue tracks this" }, ]; +const issueCreationStatuses = ["Backlog", "Todo", "In progress", "In review"]; + function normalizeSwatchColor(color: string): string { const trimmed = color.trim(); if (!trimmed) return "var(--borderColor-default, var(--color-border-default))"; @@ -454,6 +456,8 @@ function CreateIssueApp() { const [issueTypeCleared, setIssueTypeCleared] = useState(false); const [issueTypesLoading, setIssueTypesLoading] = useState(false); + const [selectedStatus, setSelectedStatus] = useState(""); + // State transition state const [currentState, setCurrentState] = useState("open"); const [stateReason, setStateReason] = useState("completed"); @@ -758,6 +762,12 @@ function CreateIssueApp() { typeof inputIssueType === "string" ? { id: inputIssueType, text: inputIssueType } : null ); setIssueTypeCleared(inputIssueType === null); + const inputStatus = toolInput?.status; + setSelectedStatus( + typeof inputStatus === "string" + ? issueCreationStatuses.find((status) => status.toLowerCase() === inputStatus.toLowerCase()) ?? inputStatus + : "" + ); setCurrentState("open"); setStateReason("completed"); setDuplicateOf(""); @@ -1053,11 +1063,15 @@ function CreateIssueApp() { delete params.duplicate_of; delete params.issue_fields; delete params.type; + delete params.status; if (isUpdateMode && issueNumber) { params.issue_number = issueNumber; } + if (!isUpdateMode && selectedStatus) { + params.status = selectedStatus; + } if (selectedLabels.length > 0) { params.labels = selectedLabels.map((l) => l.text); } @@ -1155,6 +1169,7 @@ function CreateIssueApp() { selectedMilestone, selectedIssueType, issueTypeCleared, + selectedStatus, isUpdateMode, issueNumber, stateReason, @@ -1665,6 +1680,31 @@ function CreateIssueApp() { + + {!isUpdateMode && ( + + + {`Status: ${selectedStatus || "Default (Backlog)"}`} + + + + setSelectedStatus("")}> + Default (Backlog) + + + {issueCreationStatuses.map((status) => ( + setSelectedStatus(status)} + > + {status} + + ))} + + + + )} {/* Fields section */}