diff --git a/README.md b/README.md index f340bff74e..c9f503d66b 100644 --- a/README.md +++ b/README.md @@ -756,6 +756,17 @@ For negotiated supported protocol versions `2026-07-28` or newer, the consolidat - `state`: Filter code scanning alerts by state. Defaults to open (string, optional) - `tool_name`: The name of the tool used for code scanning. (string, optional) +- **update_code_scanning_alert** - Update code scanning alert + - **OAuth Challenge Scopes**: `security_events` + - `alertNumber`: Code scanning alert number. (integer, required) + - `assignees`: Replace assignees with human usernames or copilot-swe-agent[bot]. [] unassigns everyone. Copilot assignment starts remediation, not just ownership. (string[], optional) + - `create_request`: Attempt a delegated dismissal request with state:dismissed and a reason. Does not bypass policy. (boolean, optional) + - `dismissed_comment`: Optional dismissal comment, up to 280 characters, or null. Requires a state or assignee update; not a standalone comment API. (string | null, optional) + - `dismissed_reason`: Required and non-null when dismissing. (string | null, optional) + - `owner`: Repository owner. (string, required) + - `repo`: Repository name. (string, required) + - `state`: Reopen or dismiss the alert. Omission leaves state unchanged. (string, optional) +
diff --git a/cmd/github-mcp-server/main_test.go b/cmd/github-mcp-server/main_test.go index 192ba60286..0bc797f7ba 100644 --- a/cmd/github-mcp-server/main_test.go +++ b/cmd/github-mcp-server/main_test.go @@ -89,6 +89,25 @@ func TestDependabotUpdateListScopes(t *testing.T) { } } +func TestCodeScanningUpdateListScopes(t *testing.T) { + for _, readOnly := range []bool{false, true} { + inv, err := github.NewInventory(translations.NullTranslationHelper). + WithToolsets([]string{"code_security"}).WithReadOnly(readOnly).Build() + require.NoError(t, err) + output := collectToolScopes(inv, readOnly) + if readOnly { + assert.NotContains(t, output.ScopesByTool, "update_code_scanning_alert") + continue + } + assert.Equal(t, []string{"security_events"}, output.ScopesByTool["update_code_scanning_alert"]) + assert.Contains(t, output.ToolsByScope["security_events"], "update_code_scanning_alert") + assert.Contains(t, output.Tools, ToolScopeInfo{ + Name: "update_code_scanning_alert", Toolset: "code_security", + ReadOnly: false, ChallengeScopes: []string{"security_events"}, + }) + } +} + func TestSchemaTypeString(t *testing.T) { tests := []struct { name string diff --git a/pkg/github/__toolsnaps__/update_code_scanning_alert.snap b/pkg/github/__toolsnaps__/update_code_scanning_alert.snap new file mode 100644 index 0000000000..58fb80657d --- /dev/null +++ b/pkg/github/__toolsnaps__/update_code_scanning_alert.snap @@ -0,0 +1,131 @@ +{ + "annotations": { + "destructiveHint": true, + "idempotentHint": false, + "openWorldHint": true, + "readOnlyHint": false, + "title": "Update code scanning alert" + }, + "description": "Reopen, dismiss, or replace assignees on a code scanning alert. Requires state or assignees. Dismissal requires a non-null dismissed_reason. Omitted fields are unchanged; [] clears all assignees. create_request:true requires state:dismissed and attempts a delegated dismissal request, not necessarily dismissal. The returned state and assignees are the actual API result; no request approval or agent session is inferred. Assigning copilot-swe-agent[bot] starts agentic remediation and may open a draft pull request, consuming Code Security AI Credits and Actions minutes. Repository permissions, delegated dismissal policy, and agentic Autofix eligibility are enforced by GitHub; errors are returned without fallback.", + "inputSchema": { + "additionalProperties": false, + "properties": { + "alertNumber": { + "description": "Code scanning alert number.", + "minimum": 1, + "type": "integer" + }, + "assignees": { + "description": "Replace assignees with human usernames or copilot-swe-agent[bot]. [] unassigns everyone. Copilot assignment starts remediation, not just ownership.", + "items": { + "type": "string" + }, + "type": "array" + }, + "create_request": { + "description": "Attempt a delegated dismissal request with state:dismissed and a reason. Does not bypass policy.", + "type": "boolean" + }, + "dismissed_comment": { + "description": "Optional dismissal comment, up to 280 characters, or null. Requires a state or assignee update; not a standalone comment API.", + "maxLength": 280, + "type": [ + "string", + "null" + ] + }, + "dismissed_reason": { + "description": "Required and non-null when dismissing.", + "enum": [ + "false positive", + "won't fix", + "used in tests", + "mitigated", + null + ], + "type": [ + "string", + "null" + ] + }, + "owner": { + "description": "Repository owner.", + "minLength": 1, + "type": "string" + }, + "repo": { + "description": "Repository name.", + "minLength": 1, + "type": "string" + }, + "state": { + "description": "Reopen or dismiss the alert. Omission leaves state unchanged.", + "enum": [ + "open", + "dismissed" + ], + "type": "string" + } + }, + "required": [ + "owner", + "repo", + "alertNumber" + ], + "type": "object" + }, + "name": "update_code_scanning_alert", + "outputSchema": { + "additionalProperties": false, + "properties": { + "assignees": { + "description": "Actual API assignments, when returned. Empty means unassigned; omitted means the API did not report assignments.", + "items": { + "additionalProperties": false, + "properties": { + "login": { + "type": "string" + } + }, + "required": [ + "login" + ], + "type": "object" + }, + "type": [ + "null", + "array" + ] + }, + "dismissed_reason": { + "type": [ + "null", + "string" + ] + }, + "html_url": { + "type": "string" + }, + "number": { + "description": "Exact alert number as a decimal string to preserve integer precision.", + "type": "string" + }, + "state": { + "description": "Actual API state, not the requested state. An open alert is not dismissed even when a dismissal request was attempted.", + "type": [ + "null", + "string" + ] + } + }, + "required": [ + "number", + "state", + "html_url" + ], + "type": [ + "null", + "object" + ] + } +} \ No newline at end of file diff --git a/pkg/github/tools.go b/pkg/github/tools.go index 3a94885216..46a6d7fc38 100644 --- a/pkg/github/tools.go +++ b/pkg/github/tools.go @@ -323,6 +323,7 @@ func AllTools(t translations.TranslationHelperFunc, opts ...ToolOption) []invent // Code security tools GetCodeScanningAlert(t), ListCodeScanningAlerts(t), + UpdateCodeScanningAlert(t), // Secret protection tools GetSecretScanningAlert(t), diff --git a/pkg/github/typed_security_outputs_test.go b/pkg/github/typed_security_outputs_test.go index 737d5018a9..ab1b5831dc 100644 --- a/pkg/github/typed_security_outputs_test.go +++ b/pkg/github/typed_security_outputs_test.go @@ -26,6 +26,8 @@ func securityOutputSchema(t *testing.T, name string) *jsonschema.Schema { schema, err = jsonschema.For[*CodeQualityFindingOutput](nil) case "get_code_scanning_alert": schema, err = jsonschema.For[*CodeScanningAlertOutput](nil) + case "update_code_scanning_alert": + schema, err = jsonschema.For[*CodeScanningAlertUpdateOutput](nil) case "list_code_scanning_alerts": schema, err = jsonschema.For[[]*CodeScanningAlertOutput](nil) case "get_secret_scanning_alert": diff --git a/pkg/github/update_code_scanning_alert.go b/pkg/github/update_code_scanning_alert.go new file mode 100644 index 0000000000..3808bad539 --- /dev/null +++ b/pkg/github/update_code_scanning_alert.go @@ -0,0 +1,226 @@ +package github + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/ifc" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/google/jsonschema-go/jsonschema" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +type UpdateCodeScanningAlertInput struct { + CodeScanningAlertPatch + Owner string `json:"owner"` + Repo string `json:"repo"` + AlertNumber int64 `json:"alertNumber"` +} + +// RawMessage distinguishes an omitted field from an explicit JSON null. +type CodeScanningAlertPatch struct { + State *string `json:"state,omitempty"` + DismissedReason json.RawMessage `json:"dismissed_reason,omitempty"` + DismissedComment json.RawMessage `json:"dismissed_comment,omitempty"` + CreateRequest *bool `json:"create_request,omitempty"` + Assignees *[]string `json:"assignees,omitempty"` +} + +type CodeScanningAlertAssignee struct { + Login string `json:"login"` +} + +type CodeScanningAlertUpdateOutput struct { + Number string `json:"number" jsonschema:"Exact alert number as a decimal string to preserve integer precision."` + State *string `json:"state" jsonschema:"Actual API state, not the requested state. An open alert is not dismissed even when a dismissal request was attempted."` + HTMLURL string `json:"html_url"` + DismissedReason *string `json:"dismissed_reason,omitempty"` + Assignees *[]CodeScanningAlertAssignee `json:"assignees,omitempty" jsonschema:"Actual API assignments, when returned. Empty means unassigned; omitted means the API did not report assignments."` +} + +func UpdateCodeScanningAlert(t translations.TranslationHelperFunc) inventory.ServerTool { + return NewTool( + ToolsetMetadataCodeSecurity, + mcp.Tool{ + Name: "update_code_scanning_alert", + Description: t("TOOL_UPDATE_CODE_SCANNING_ALERT_DESCRIPTION", + "Reopen, dismiss, or replace assignees on a code scanning alert. Requires state or assignees. "+ + "Dismissal requires a non-null dismissed_reason. Omitted fields are unchanged; [] clears all assignees. "+ + "create_request:true requires state:dismissed and attempts a delegated dismissal request, not necessarily dismissal. "+ + "The returned state and assignees are the actual API result; no request approval or agent session is inferred. "+ + "Assigning copilot-swe-agent[bot] starts agentic remediation and may open a draft pull request, consuming Code Security AI Credits and Actions minutes. "+ + "Repository permissions, delegated dismissal policy, and agentic Autofix eligibility are enforced by GitHub; errors are returned without fallback."), + Annotations: &mcp.ToolAnnotations{ + Title: t("TOOL_UPDATE_CODE_SCANNING_ALERT_USER_TITLE", "Update code scanning alert"), + ReadOnlyHint: false, + DestructiveHint: new(true), + IdempotentHint: false, + OpenWorldHint: new(true), + }, + InputSchema: &jsonschema.Schema{ + Type: "object", + AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}}, + Properties: map[string]*jsonschema.Schema{ + "owner": {Type: "string", MinLength: new(1), Description: "Repository owner."}, + "repo": {Type: "string", MinLength: new(1), Description: "Repository name."}, + "alertNumber": {Type: "integer", Minimum: new(1.0), Description: "Code scanning alert number."}, + "state": {Type: "string", Enum: []any{"open", "dismissed"}, Description: "Reopen or dismiss the alert. Omission leaves state unchanged."}, + "dismissed_reason": {Types: []string{"string", "null"}, Enum: []any{"false positive", "won't fix", "used in tests", "mitigated", nil}, Description: "Required and non-null when dismissing."}, + "dismissed_comment": {Types: []string{"string", "null"}, MaxLength: new(280), Description: "Optional dismissal comment, up to 280 characters, or null. Requires a state or assignee update; not a standalone comment API."}, + "create_request": {Type: "boolean", Description: "Attempt a delegated dismissal request with state:dismissed and a reason. Does not bypass policy."}, + "assignees": {Type: "array", Items: &jsonschema.Schema{Type: "string"}, Description: "Replace assignees with human usernames or copilot-swe-agent[bot]. [] unassigns everyone. Copilot assignment starts remediation, not just ownership."}, + }, + Required: []string{"owner", "repo", "alertNumber"}, + }, + }, + scopes.RequireAll(scopes.SecurityEvents), + func(ctx context.Context, deps ToolDependencies, call *mcp.CallToolRequest, _ json.RawMessage) (*mcp.CallToolResult, *CodeScanningAlertUpdateOutput, error) { + // Typed schema validation passes through float64. Decode the original + // JSON so large IDs and fractional inputs cannot change the write target. + args, err := decodeCodeScanningAlertUpdate(call.Params.Arguments) + if err != nil { + return utils.NewToolResultErrorFromErr("invalid code scanning alert update arguments", err), nil, nil + } + client, err := deps.GetClient(ctx) + if err != nil { + return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, err + } + path := fmt.Sprintf("repos/%s/%s/code-scanning/alerts/%d", url.PathEscape(args.Owner), url.PathEscape(args.Repo), args.AlertNumber) + // The SDK's update type requires state and lacks assignees and create_request. + request, err := client.NewRequest(ctx, http.MethodPatch, path, args.CodeScanningAlertPatch) + if err != nil { + return utils.NewToolResultErrorFromErr("failed to create code scanning alert update request", err), nil, err + } + var alert struct { + Number int64 `json:"number"` + State json.RawMessage `json:"state"` + HTMLURL string `json:"html_url"` + DismissedReason *string `json:"dismissed_reason"` + Assignees *[]CodeScanningAlertAssignee `json:"assignees"` + } + resp, err := client.Do(request, &alert) + if resp != nil && resp.Body != nil { + defer func() { _ = resp.Body.Close() }() + } + const uncertainUpdate = "The code scanning alert update may already have been applied; verify the alert with get_code_scanning_alert before retrying" + if err != nil { + if resp != nil && resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices { + return utils.NewToolResultErrorFromErr(uncertainUpdate, err), nil, nil + } + return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to update code scanning alert", resp, err), nil, nil + } + if resp.StatusCode != http.StatusOK || alert.Number != args.AlertNumber || alert.HTMLURL == "" || len(alert.State) == 0 { + return utils.NewToolResultError("invalid code scanning alert update response. " + uncertainUpdate + "."), nil, nil + } + output := CodeScanningAlertUpdateOutput{ + Number: strconv.FormatInt(alert.Number, 10), HTMLURL: alert.HTMLURL, + DismissedReason: alert.DismissedReason, Assignees: alert.Assignees, + } + if err := json.Unmarshal(alert.State, &output.State); err != nil { + return utils.NewToolResultErrorFromErr("invalid code scanning alert state. "+uncertainUpdate, err), nil, nil + } + encoded, err := json.Marshal(output) + if err != nil { + return utils.NewToolResultErrorFromErr("failed to marshal code scanning alert update", err), nil, err + } + result := attachStaticIFCLabel(ctx, deps, utils.NewToolResultText(string(encoded)), ifc.LabelSecurityAlert()) + return result, &output, nil + }, + normalizeCodeScanningAlertUpdate, + ) +} + +func normalizeCodeScanningAlertUpdate(raw json.RawMessage) (json.RawMessage, error) { + if _, err := decodeCodeScanningAlertUpdate(raw); err != nil { + return nil, &inventory.ToolInputError{Message: err.Error()} + } + return raw, nil +} + +func decodeCodeScanningAlertUpdate(raw json.RawMessage) (UpdateCodeScanningAlertInput, error) { + var args UpdateCodeScanningAlertInput + var fields map[string]json.RawMessage + if err := json.Unmarshal(raw, &fields); err != nil { + return args, err + } + for name, value := range fields { + switch name { + case "dismissed_reason", "dismissed_comment": + continue + case "owner", "repo", "alertNumber", "state", "create_request", "assignees": + default: + return args, fmt.Errorf("unknown parameter: %s", name) + } + if bytes.Equal(bytes.TrimSpace(value), []byte("null")) { + return args, fmt.Errorf("parameter %s must not be null", name) + } + } + if err := json.Unmarshal(raw, &args); err != nil { + return args, err + } + for name, value := range map[string]string{"owner": args.Owner, "repo": args.Repo} { + if value == "" || value == "." || value == ".." || + strings.ContainsAny(value, `/\%?#`) || strings.ContainsFunc(value, func(r rune) bool { + return unicode.IsSpace(r) || unicode.IsControl(r) + }) { + return args, fmt.Errorf("%s must be a non-empty repository path segment", name) + } + } + if args.AlertNumber < 1 { + return args, errors.New("alertNumber must be a positive int64 integer") + } + if args.State == nil && args.Assignees == nil { + return args, errors.New("provide state or assignees") + } + if args.State != nil && !slices.Contains([]string{"open", "dismissed"}, *args.State) { + return args, errors.New("state must be open or dismissed") + } + var reason *string + if len(args.DismissedReason) != 0 { + if err := json.Unmarshal(args.DismissedReason, &reason); err != nil { + return args, fmt.Errorf("invalid dismissed_reason: %w", err) + } + if reason != nil && !slices.Contains([]string{"false positive", "won't fix", "used in tests", "mitigated"}, *reason) { + return args, errors.New("invalid dismissed_reason") + } + } + if args.State != nil && *args.State == "dismissed" && reason == nil { + return args, errors.New("a non-null dismissed_reason is required when state is dismissed") + } + if args.CreateRequest != nil && *args.CreateRequest && (args.State == nil || *args.State != "dismissed") { + return args, errors.New("create_request:true requires state:dismissed and dismissed_reason") + } + if len(args.DismissedComment) != 0 { + var comment *string + if err := json.Unmarshal(args.DismissedComment, &comment); err != nil { + return args, fmt.Errorf("invalid dismissed_comment: %w", err) + } + if comment != nil && utf8.RuneCountInString(*comment) > 280 { + return args, errors.New("dismissed_comment must not exceed 280 characters") + } + } + if args.Assignees != nil { + var assignees []*string + if err := json.Unmarshal(fields["assignees"], &assignees); err != nil { + return args, err + } + if slices.Contains(assignees, nil) { + return args, errors.New("assignees must contain only strings") + } + } + return args, nil +} diff --git a/pkg/github/update_code_scanning_alert_test.go b/pkg/github/update_code_scanning_alert_test.go new file mode 100644 index 0000000000..6942d84661 --- /dev/null +++ b/pkg/github/update_code_scanning_alert_test.go @@ -0,0 +1,434 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "io" + "maps" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/github/github-mcp-server/v2/pkg/ifc" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/google/go-github/v92/github" + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func codeScanningUpdateSession(t *testing.T, handler http.HandlerFunc, protocol string, labels bool) (*mcp.ClientSession, *BaseDeps) { + t.Helper() + deps := &BaseDeps{Client: mustNewGHClient(t, MockHTTPClientWithHandler(handler))} + if labels { + deps.featureChecker = featureCheckerFor(FeatureFlagIFCLabels) + } + server := mcp.NewServer(&mcp.Implementation{Name: "code-scanning-update-test", Version: "1"}, nil) + server.AddReceivingMiddleware(InjectDepsMiddleware(deps)) + tool := UpdateCodeScanningAlert(translations.NullTranslationHelper) + tool.RegisterFunc(server, deps) + return connectCommentVisibilityClient(t, server, protocol), deps +} + +func TestUpdateCodeScanningAlert(t *testing.T) { + t.Parallel() + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + for _, tc := range []struct { + name, patch, response, expected string + }{ + {"dismiss", `{"state":"dismissed","dismissed_reason":"false positive","dismissed_comment":"sanitized"}`, + `{"state":"dismissed","dismissed_reason":"false positive","rule":{"help":"do not echo"},"most_recent_instance":{"message":{"text":"untrusted code"}}}`, + `{"state":"dismissed","dismissed_reason":"false positive"}`}, + {"reopen with nulls", `{"state":"open","dismissed_reason":null,"dismissed_comment":null,"create_request":false}`, + `{"state":"open","dismissed_reason":null,"assignees":[{"login":"octocat","email":"not returned"}]}`, + `{"state":"open","assignees":[{"login":"octocat"}]}`}, + {"assignment only", `{"assignees":["octocat","copilot-swe-agent[bot]"]}`, + `{"state":"open","assignees":[{"login":"copilot-swe-agent[bot]"}]}`, + `{"state":"open","assignees":[{"login":"copilot-swe-agent[bot]"}]}`}, + {"clear", `{"assignees":[]}`, `{"state":"open","assignees":[]}`, `{"state":"open","assignees":[]}`}, + {"dismissal request does not dismiss", `{"state":"dismissed","dismissed_reason":"mitigated","create_request":true}`, + `{"state":"open"}`, `{"state":"open"}`}, + {"request attempt can return dismissed", `{"state":"dismissed","dismissed_reason":"won't fix","create_request":true}`, + `{"state":"dismissed"}`, `{"state":"dismissed"}`}, + {"nullable actual state", `{"assignees":["octocat"]}`, `{"state":null}`, `{"state":null}`}, + {"combined", `{"state":"dismissed","dismissed_reason":"used in tests","assignees":["octocat"]}`, + `{"state":"dismissed","assignees":[{"login":"octocat"}]}`, `{"state":"dismissed","assignees":[{"login":"octocat"}]}`}, + } { + t.Run(protocol+"/"+tc.name, func(t *testing.T) { + t.Parallel() + var calls int + session, deps := codeScanningUpdateSession(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.Equal(t, "PATCH /repos/octo/widgets/code-scanning/alerts/42", r.Method+" "+r.URL.Path) + assert.Empty(t, r.URL.RawQuery) + assert.Equal(t, "2022-11-28", r.Header.Get("X-GitHub-Api-Version")) + body, err := io.ReadAll(r.Body) + require.NoError(t, err) + assert.JSONEq(t, tc.patch, string(body), "preserve omitted, null and empty PATCH fields") + _, _ = fmt.Fprintf(w, `{"number":42,"html_url":"https://github.com/octo/widgets/security/code-scanning/42",%s}`, tc.response[1:len(tc.response)-1]) + }, protocol, true) + args := json.RawMessage(`{"owner":"octo","repo":"widgets","alertNumber":42,` + tc.patch[1:]) + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "update_code_scanning_alert", Arguments: args}) + require.NoError(t, err) + require.False(t, result.IsError, "%+v", result.Content) + assert.Equal(t, 1, calls, "one PATCH, no fallback or policy preflights") + expected := `{"number":"42","html_url":"https://github.com/octo/widgets/security/code-scanning/42",` + tc.expected[1:] + text := getTextResult(t, result).Text + assert.JSONEq(t, expected, text) + if protocol == inventory.ProtocolVersionMultiRoundTrip { + require.NotNil(t, result.StructuredContent) + assert.JSONEq(t, expected, mustMarshalJSON(t, result.StructuredContent)) + } else { + assert.Nil(t, result.StructuredContent) + } + assert.JSONEq(t, mustMarshalJSON(t, ifc.LabelSecurityAlert()), mustMarshalJSON(t, result.Meta["ifc"])) + request, err := deps.Client.NewRequest(t.Context(), http.MethodGet, "repos/octo/widgets", nil) + require.NoError(t, err) + assert.Equal(t, "2022-11-28", request.Header.Get("X-GitHub-Api-Version"), "do not mutate the shared client's API version") + }) + } + } +} + +func TestUpdateCodeScanningAlertConfiguredClient(t *testing.T) { + t.Parallel() + for _, enterprise := range []bool{false, true} { + t.Run(fmt.Sprint("enterprise=", enterprise), func(t *testing.T) { + t.Parallel() + prefix := "" + if enterprise { + prefix = "/api/v3" + } + var calls int + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.Equal(t, "PATCH", r.Method) + assert.Equal(t, prefix+"/repos/octo/widgets/code-scanning/alerts/42", r.URL.Path) + assert.Equal(t, "Bearer test-token", r.Header.Get("Authorization")) + assert.Equal(t, "2022-11-28", r.Header.Get("X-GitHub-Api-Version")) + assert.Equal(t, "application/vnd.github.v3+json", r.Header.Get("Accept")) + _, _ = io.WriteString(w, `{"number":42,"state":"open","html_url":"https://github.com/octo/widgets/security/code-scanning/42"}`) + if !enterprise { + assert.Equal(t, "api.github.com", r.URL.Host) + } + }) + opts := []github.ClientOptionsFunc{ + github.WithHTTPClient(MockHTTPClientWithHandler(handler)), + github.WithAuthToken("test-token"), + } + if enterprise { + api := httptest.NewServer(handler) + t.Cleanup(api.Close) + opts = append(opts, github.WithHTTPClient(api.Client()), github.WithEnterpriseURLs(api.URL+"/api/v3/", api.URL+"/api/uploads/")) + } + client, err := github.NewClient(opts...) + require.NoError(t, err) + baseURL := client.BaseURL() + deps := &BaseDeps{Client: client} + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + server := mcp.NewServer(&mcp.Implementation{Name: "configured-client-test", Version: "1"}, nil) + server.AddReceivingMiddleware(InjectDepsMiddleware(deps)) + tool := UpdateCodeScanningAlert(translations.NullTranslationHelper) + tool.RegisterFunc(server, deps) + session := connectCommentVisibilityClient(t, server, protocol) + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: tool.Tool.Name, Arguments: map[string]any{ + "owner": "octo", "repo": "widgets", "alertNumber": 42, "state": "open", + }}) + require.NoError(t, err) + require.False(t, result.IsError, "%+v", result.Content) + } + assert.Equal(t, 2, calls) + assert.Equal(t, baseURL, client.BaseURL()) + }) + } +} + +func TestUpdateCodeScanningAlertReasonsAndComments(t *testing.T) { + t.Parallel() + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + for _, reason := range []string{"false positive", "won't fix", "used in tests", "mitigated"} { + t.Run(protocol+"/"+reason, func(t *testing.T) { + t.Parallel() + session, _ := codeScanningUpdateSession(t, func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + assert.Equal(t, reason, body["dismissed_reason"]) + assert.Contains(t, body, "dismissed_comment") + _, _ = io.WriteString(w, `{"number":42,"state":"dismissed","html_url":"https://github.com/octo/widgets/security/code-scanning/42"}`) + }, protocol, false) + for _, comment := range []any{nil, "", strings.Repeat("a", 280), strings.Repeat("\u00e9", 280)} { + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "update_code_scanning_alert", Arguments: map[string]any{ + "owner": "octo", "repo": "widgets", "alertNumber": 42, "state": "dismissed", "dismissed_reason": reason, "dismissed_comment": comment, + }}) + require.NoError(t, err) + require.False(t, result.IsError, "%+v", result.Content) + assert.NotContains(t, result.Meta, "ifc") + } + }) + } + } +} + +func TestUpdateCodeScanningAlertRejectsInvalidInput(t *testing.T) { + t.Parallel() + base := map[string]any{"owner": "octo", "repo": "widgets", "alertNumber": 42, "state": "open"} + var inputs []json.RawMessage + for _, tc := range []struct { + field string + value any + }{ + {"owner", ""}, {"repo", ""}, {"owner", "../octo"}, {"repo", ".."}, {"repo", "."}, + {"owner", "octo/widgets"}, {"repo", "widgets/../../issues"}, {"repo", `widgets\repo`}, + {"owner", " octo"}, {"repo", "widgets\n"}, {"owner", "octo?x=y"}, {"repo", "widgets#fragment"}, {"repo", "%2e%2e"}, + {"owner", nil}, {"repo", nil}, {"alertNumber", 0}, {"alertNumber", -1}, {"alertNumber", 1.5}, + {"alertNumber", "42"}, {"alertNumber", 1e30}, {"alertNumber", nil}, + {"state", "fixed"}, {"state", ""}, {"state", nil}, {"state", "dismissed"}, + {"dismissed_reason", "fix_started"}, {"dismissed_reason", false}, {"dismissed_comment", 7}, + {"dismissed_comment", strings.Repeat("x", 281)}, {"dismissed_comment", strings.Repeat("\u00e9", 281)}, + {"create_request", true}, {"create_request", "true"}, {"create_request", nil}, + {"assignees", nil}, {"assignees", "octocat"}, {"assignees", []any{nil}}, {"assignees", []any{1}}, + {"agent_assignment", map[string]any{"model": "unsupported"}}, {"confirm", true}, {"unexpected", true}, {"STATE", "dismissed"}, + } { + args := maps.Clone(base) + args[tc.field] = tc.value + raw, err := json.Marshal(args) + require.NoError(t, err) + inputs = append(inputs, raw) + } + for _, patch := range []string{ + ``, `,"dismissed_comment":"comment only"`, `,"dismissed_reason":"mitigated"`, `,"create_request":false`, + `,"state":"dismissed"`, `,"state":"dismissed","dismissed_reason":null`, + `,"assignees":[],"create_request":true`, + } { + inputs = append(inputs, json.RawMessage(`{"owner":"octo","repo":"widgets","alertNumber":42`+patch+`}`)) + } + for _, field := range []string{"owner", "repo", "alertNumber"} { + args := maps.Clone(base) + delete(args, field) + raw, err := json.Marshal(args) + require.NoError(t, err) + inputs = append(inputs, raw) + } + inputs = append(inputs, json.RawMessage(`null`), json.RawMessage(`[]`)) + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + t.Run(protocol, func(t *testing.T) { + t.Parallel() + session, deps := codeScanningUpdateSession(t, func(w http.ResponseWriter, _ *http.Request) { + t.Error("invalid input reached GitHub") + w.WriteHeader(http.StatusInternalServerError) + }, protocol, false) + tool := UpdateCodeScanningAlert(translations.NullTranslationHelper) + for _, raw := range inputs { + t.Run(string(raw), func(t *testing.T) { + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: tool.Tool.Name, Arguments: raw}) + require.NoError(t, err) + require.True(t, result.IsError, "%+v", result.Content) + assert.Nil(t, result.StructuredContent) + result, err = tool.Handler(deps)(ContextWithDeps(t.Context(), deps), &mcp.CallToolRequest{ + Params: &mcp.CallToolParamsRaw{Name: tool.Tool.Name, Arguments: raw}, + }) + require.NoError(t, err) + require.True(t, result.IsError, "%+v", result.Content) + }) + } + }) + } +} + +func TestUpdateCodeScanningAlertInvalidDismissalFieldTypes(t *testing.T) { + t.Parallel() + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + t.Run(protocol, func(t *testing.T) { + t.Parallel() + session, deps := codeScanningUpdateSession(t, func(_ http.ResponseWriter, _ *http.Request) { + t.Error("invalid input reached GitHub") + }, protocol, false) + tool := UpdateCodeScanningAlert(translations.NullTranslationHelper) + for _, field := range []string{"dismissed_reason", "dismissed_comment"} { + for _, value := range []string{`false`, `7`, `[]`, `{}`} { + t.Run(field+"/"+value, func(t *testing.T) { + raw := json.RawMessage(`{"owner":"octo","repo":"widgets","alertNumber":42,"state":"open","` + field + `":` + value + `}`) + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: tool.Tool.Name, Arguments: raw}) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, "invalid "+field+":") + result, err = tool.Handler(deps)(ContextWithDeps(t.Context(), deps), &mcp.CallToolRequest{ + Params: &mcp.CallToolParamsRaw{Name: tool.Tool.Name, Arguments: raw}, + }) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, "invalid "+field+":") + }) + } + } + }) + } +} + +func TestUpdateCodeScanningAlertErrors(t *testing.T) { + t.Parallel() + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + for _, status := range []int{400, 403, 404, 409, 410, 422, 500, 503} { + t.Run(protocol+"/"+fmt.Sprint(status), func(t *testing.T) { + t.Parallel() + var calls int + session, _ := codeScanningUpdateSession(t, func(w http.ResponseWriter, _ *http.Request) { + calls++ + w.WriteHeader(status) + _, _ = io.WriteString(w, `{"message":"upstream policy denied this update"}`) + }, protocol, true) + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "update_code_scanning_alert", Arguments: map[string]any{ + "owner": "octo", "repo": "widgets", "alertNumber": 42, "state": "dismissed", "dismissed_reason": "mitigated", "create_request": true, + }}) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, "upstream policy denied this update") + assert.Equal(t, 1, calls, "no fallback writes") + assert.Nil(t, result.StructuredContent) + assert.NotContains(t, result.Meta, "ifc") + }) + } + for _, response := range []string{ + `{`, `{}`, ``, `{"number":"42"}`, `{"number":42,"state":"open"}`, + `{"number":42,"html_url":"https://github.com/octo/widgets/security/code-scanning/42"}`, + `{"number":42,"state":true,"html_url":"https://github.com/octo/widgets/security/code-scanning/42"}`, + `{"number":43,"state":"open","html_url":"https://github.com/octo/widgets/security/code-scanning/43"}`, + } { + t.Run(protocol+"/"+response, func(t *testing.T) { + t.Parallel() + var calls int + session, _ := codeScanningUpdateSession(t, func(w http.ResponseWriter, _ *http.Request) { + calls++ + _, _ = io.WriteString(w, response) + }, protocol, true) + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "update_code_scanning_alert", Arguments: map[string]any{ + "owner": "octo", "repo": "widgets", "alertNumber": 42, "state": "open", + }}) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Nil(t, result.StructuredContent) + assert.NotContains(t, result.Meta, "ifc") + assert.Contains(t, getTextResult(t, result).Text, "may already have been applied") + assert.Contains(t, getTextResult(t, result).Text, "verify the alert with get_code_scanning_alert before retrying") + assert.Equal(t, 1, calls, "do not retry uncertain writes") + }) + } + for _, status := range []int{http.StatusAccepted, http.StatusNoContent} { + t.Run(protocol+"/"+fmt.Sprint(status), func(t *testing.T) { + t.Parallel() + var calls int + session, _ := codeScanningUpdateSession(t, func(w http.ResponseWriter, _ *http.Request) { + calls++ + w.WriteHeader(status) + }, protocol, false) + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "update_code_scanning_alert", Arguments: map[string]any{ + "owner": "octo", "repo": "widgets", "alertNumber": 42, "state": "open", + }}) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Nil(t, result.StructuredContent) + assert.Contains(t, getTextResult(t, result).Text, "may already have been applied") + assert.Contains(t, getTextResult(t, result).Text, "verify the alert with get_code_scanning_alert before retrying") + assert.Equal(t, 1, calls, "do not retry uncertain writes") + }) + } + } +} + +func TestUpdateCodeScanningAlertExactNumbers(t *testing.T) { + t.Parallel() + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + for _, number := range []string{"9007199254740993", "9223372036854775807", "9223372036854775808", "1.0000000000000000001", "9007199254740993.1", "42.000000000000000001", "1e-500"} { + t.Run(protocol+"/"+number, func(t *testing.T) { + t.Parallel() + valid := number == "9007199254740993" || number == "9223372036854775807" + var calls int + session, _ := codeScanningUpdateSession(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.True(t, valid, "invalid input must not reach GitHub") + assert.Equal(t, "/repos/octo/widgets/code-scanning/alerts/"+number, r.URL.Path) + _, _ = fmt.Fprintf(w, `{"number":%s,"state":"open","html_url":"https://github.com/octo/widgets/security/code-scanning/%s"}`, number, number) + }, protocol, false) + args := json.RawMessage(`{"owner":"octo","repo":"widgets","alertNumber":` + number + `,"state":"open"}`) + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "update_code_scanning_alert", Arguments: args}) + require.NoError(t, err) + if !valid { + require.True(t, result.IsError) + assert.Zero(t, calls) + return + } + require.False(t, result.IsError, "%+v", result.Content) + assert.Equal(t, 1, calls) + var output struct { + Number string `json:"number"` + } + require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &output)) + assert.Equal(t, number, output.Number) + if protocol == inventory.ProtocolVersionMultiRoundTrip { + require.NoError(t, json.Unmarshal([]byte(mustMarshalJSON(t, result.StructuredContent)), &output)) + assert.Equal(t, number, output.Number) + } + }) + } + } +} + +func TestUpdateCodeScanningAlertInventoryAndSchema(t *testing.T) { + t.Parallel() + tool := UpdateCodeScanningAlert(translations.NullTranslationHelper) + testSecurityToolSnapshot(t, tool.Tool) + assert.Equal(t, ToolsetMetadataCodeSecurity, tool.Toolset) + assert.Equal(t, scopes.RequireAll(scopes.SecurityEvents).Scopes, tool.ScopeAccess.Scopes) + assert.NotEmpty(t, tool.ScopeAccess.Challenge(map[string]any{}, nil)) + assert.False(t, tool.IsReadOnly()) + assert.True(t, *tool.Tool.Annotations.DestructiveHint) + assert.False(t, tool.Tool.Annotations.IdempotentHint) + for _, tc := range []struct { + name string + toolsets []string + readOnly bool + scopes []string + want bool + }{ + {"opt-in", []string{"code_security"}, false, []string{"security_events"}, true}, + {"default excludes", []string{"default"}, false, []string{"security_events"}, false}, + {"read-only excludes", []string{"code_security"}, true, []string{"security_events"}, false}, + {"missing scope excludes", []string{"code_security"}, false, []string{}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + inv, err := NewInventory(translations.NullTranslationHelper). + WithToolsets(tc.toolsets).WithReadOnly(tc.readOnly). + WithFilter(CreateToolScopeFilter(tc.scopes)).Build() + require.NoError(t, err) + found := false + for _, candidate := range inv.AvailableTools(context.Background()) { + found = found || candidate.Tool.Name == tool.Tool.Name + } + assert.Equal(t, tc.want, found) + }) + } + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + session, _ := codeScanningUpdateSession(t, func(_ http.ResponseWriter, _ *http.Request) { + t.Error("listing tools must not call GitHub") + }, protocol, false) + listed, err := session.ListTools(t.Context(), nil) + require.NoError(t, err) + require.Len(t, listed.Tools, 1) + encoded := mustMarshalJSON(t, listed.Tools[0].InputSchema) + var schema map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(encoded), &schema)) + for _, keyword := range []string{"anyOf", "oneOf", "allOf", "if", "then", "else"} { + assert.NotContains(t, schema, keyword) + } + assert.NotContains(t, encoded, `"default"`) + if protocol == inventory.ProtocolVersionMultiRoundTrip { + assert.JSONEq(t, mustMarshalJSON(t, securityOutputSchema(t, tool.Tool.Name)), mustMarshalJSON(t, listed.Tools[0].OutputSchema)) + } else { + assert.Nil(t, listed.Tools[0].OutputSchema) + } + } +} diff --git a/pkg/skills/catalog/skills/security-alert-triage/SKILL.md b/pkg/skills/catalog/skills/security-alert-triage/SKILL.md index f39d315ccf..c6216e6a65 100644 --- a/pkg/skills/catalog/skills/security-alert-triage/SKILL.md +++ b/pkg/skills/catalog/skills/security-alert-triage/SKILL.md @@ -11,6 +11,8 @@ evidence a maintainer can check. The output is a recommendation with evidence unless a specific update is requested. When available, `update_dependabot_alert` can reopen or dismiss a Dependabot alert, or replace its assignees. It does not merge a fix or revoke a credential. +`update_code_scanning_alert` can reopen or dismiss a code scanning alert, request +delegated dismissal, or replace its assignees when enabled and not read-only. ## Sequence @@ -97,6 +99,21 @@ If GitHub accepts the update but its response cannot be read or validated, the update may already have been applied. Check `get_dependabot_alert` before retrying; never automatically repeat a remediation assignment after an uncertain result. +For a requested code scanning update, use `update_code_scanning_alert` with separate +`owner`, `repo` and a positive integer `alertNumber`, plus state or assignees. +`state` is `open` or `dismissed`; dismissal requires a non-null `dismissed_reason`: +`false positive`, `won't fix`, `used in tests`, or `mitigated`. Omitted fields stay +unchanged. `dismissed_reason` and `dismissed_comment` also accept explicit null; +non-null comments are limited to 280 characters. Comments alone are not supported. +`assignees` replaces the full set and `[]` clears it. Copilot assignment starts +agentic remediation and may open a draft pull request, consuming Code Security AI +Credits and Actions minutes; do not infer a session or pull request from assignment. +Use `create_request: true` with `state: dismissed` and a reason to attempt delegated +dismissal when appropriate; GitHub may also require a comment under repository +policy. Report the actual returned state and assignees, not presumed dismissal or +approval. GitHub enforces permissions, policy and agentic Autofix eligibility; +report errors without fallback or agent configuration. + ## Empty and failure cases - **An empty list and a disabled feature look alike.** An empty result means no open diff --git a/pkg/skills/catalog/skills/security-alert-triage/references/alert-sources.md b/pkg/skills/catalog/skills/security-alert-triage/references/alert-sources.md index 0dd32c2d27..ef4a3df36f 100644 --- a/pkg/skills/catalog/skills/security-alert-triage/references/alert-sources.md +++ b/pkg/skills/catalog/skills/security-alert-triage/references/alert-sources.md @@ -6,7 +6,8 @@ Keep them apart when reporting. ## Code scanning -- **Tools** — `list_code_scanning_alerts`, `get_code_scanning_alert`. +- **Tools** — `list_code_scanning_alerts`, `get_code_scanning_alert`, + `update_code_scanning_alert` (when enabled and not read-only). - **What it finds** — problems in this repository's own code, from analysis tools. - **Identity** — alert number, plus `rule.id`. The rule id is stable across repositories, so it is the right thing to group or compare on. @@ -16,6 +17,7 @@ Keep them apart when reporting. - **Where to look** — `most_recent_instance.location` gives file, line and column. - **Closed means** — `fixed` when the code changed, `dismissed` when a person judged it inapplicable. + A delegated dismissal request can leave the alert open; use the returned state. ## Dependabot diff --git a/pkg/skills/catalog/tools.go b/pkg/skills/catalog/tools.go index 42db2f0278..f6dc78951e 100644 --- a/pkg/skills/catalog/tools.go +++ b/pkg/skills/catalog/tools.go @@ -73,7 +73,7 @@ var requirements = map[string]toolRequirements{ }, "security-alert-triage": { required: [][]string{{"list_code_scanning_alerts", "list_dependabot_alerts", "list_secret_scanning_alerts", "list_repository_security_advisories", "list_org_repository_security_advisories"}}, - optional: []string{"get_code_scanning_alert", "get_dependabot_alert", "update_dependabot_alert", "get_secret_scanning_alert", "list_global_security_advisories", "get_global_security_advisory", "get_file_contents", "search_code"}, + optional: []string{"get_code_scanning_alert", "update_code_scanning_alert", "get_dependabot_alert", "update_dependabot_alert", "get_secret_scanning_alert", "list_global_security_advisories", "get_global_security_advisory", "get_file_contents", "search_code"}, }, "workflow-failure-triage": { required: [][]string{{"actions_list"}, {"actions_get"}, {"get_job_logs"}},