diff --git a/README.md b/README.md index 1fcee4b1d6..f340bff74e 100644 --- a/README.md +++ b/README.md @@ -839,6 +839,16 @@ For negotiated supported protocol versions `2026-07-28` or newer, the consolidat - `severity`: Filter dependabot alerts by severity (string, optional) - `state`: Filter dependabot alerts by state. Defaults to open (string, optional) +- **update_dependabot_alert** - Update Dependabot alert + - **OAuth Challenge Scopes**: `security_events` + - `alertNumber`: The repository's Dependabot alert number. (integer, required) + - `assignees`: Usernames replacing the entire assignee set; [] clears all, omission leaves it unchanged. Including copilot-swe-agent[bot] requests remediation, not just ownership bookkeeping. (string[], optional) + - `dismissed_comment`: Optional dismissal comment, up to 280 characters; not a standalone comment API. (string, optional) + - `dismissed_reason`: Required when state is dismissed. (string, optional) + - `owner`: Repository owner (username or organization). (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 48d1367acf..192ba60286 100644 --- a/cmd/github-mcp-server/main_test.go +++ b/cmd/github-mcp-server/main_test.go @@ -6,8 +6,10 @@ import ( "strings" "testing" + "github.com/github/github-mcp-server/v2/pkg/github" "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/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/spf13/viper" @@ -68,6 +70,25 @@ func TestWriteToolDocScopes(t *testing.T) { assert.Contains(t, buf.String(), "**OAuth Challenge Scopes**: `delete_repo`, `repo`") } +func TestDependabotUpdateListScopes(t *testing.T) { + for _, readOnly := range []bool{false, true} { + inv, err := github.NewInventory(translations.NullTranslationHelper). + WithToolsets([]string{"dependabot"}).WithReadOnly(readOnly).Build() + require.NoError(t, err) + output := collectToolScopes(inv, readOnly) + if readOnly { + assert.NotContains(t, output.ScopesByTool, "update_dependabot_alert") + continue + } + assert.Equal(t, []string{"security_events"}, output.ScopesByTool["update_dependabot_alert"]) + assert.Contains(t, output.ToolsByScope["security_events"], "update_dependabot_alert") + assert.Contains(t, output.Tools, ToolScopeInfo{ + Name: "update_dependabot_alert", Toolset: "dependabot", + ReadOnly: false, ChallengeScopes: []string{"security_events"}, + }) + } +} + func TestSchemaTypeString(t *testing.T) { tests := []struct { name string diff --git a/pkg/github/__toolsnaps__/update_dependabot_alert.snap b/pkg/github/__toolsnaps__/update_dependabot_alert.snap new file mode 100644 index 0000000000..4de43f2616 --- /dev/null +++ b/pkg/github/__toolsnaps__/update_dependabot_alert.snap @@ -0,0 +1,124 @@ +{ + "annotations": { + "destructiveHint": true, + "idempotentHint": false, + "openWorldHint": true, + "readOnlyHint": false, + "title": "Update Dependabot alert" + }, + "description": "Update a Dependabot alert's state or assignees. Provide state or assignees; dismissal requires dismissed_reason. Assigning copilot-swe-agent[bot] requests remediation that attempts a fix; a pull request is not guaranteed. Requires Dependabot alerts write permission or the security_events OAuth scope. GitHub enforces authorization, licensing, repository policies and delegated-dismissal review requirements. Agent configuration (agent_assignment) is not supported.", + "inputSchema": { + "additionalProperties": false, + "properties": { + "alertNumber": { + "description": "The repository's Dependabot alert number.", + "minimum": 1, + "type": "integer" + }, + "assignees": { + "description": "Usernames replacing the entire assignee set; [] clears all, omission leaves it unchanged. Including copilot-swe-agent[bot] requests remediation, not just ownership bookkeeping.", + "items": { + "type": "string" + }, + "type": "array" + }, + "dismissed_comment": { + "description": "Optional dismissal comment, up to 280 characters; not a standalone comment API.", + "maxLength": 280, + "type": "string" + }, + "dismissed_reason": { + "description": "Required when state is dismissed.", + "enum": [ + "fix_started", + "inaccurate", + "no_bandwidth", + "not_used", + "tolerable_risk" + ], + "type": "string" + }, + "owner": { + "description": "Repository owner (username or organization).", + "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_dependabot_alert", + "outputSchema": { + "additionalProperties": false, + "properties": { + "assignees": { + "items": { + "additionalProperties": false, + "properties": { + "login": { + "type": "string" + } + }, + "required": [ + "login" + ], + "type": "object" + }, + "type": [ + "null", + "array" + ] + }, + "dismissed_comment": { + "type": [ + "null", + "string" + ] + }, + "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": { + "type": "string" + } + }, + "required": [ + "number", + "state", + "html_url", + "dismissed_reason", + "dismissed_comment" + ], + "type": [ + "null", + "object" + ] + } +} \ No newline at end of file diff --git a/pkg/github/tools.go b/pkg/github/tools.go index 0fdd924728..3a94885216 100644 --- a/pkg/github/tools.go +++ b/pkg/github/tools.go @@ -331,6 +331,7 @@ func AllTools(t translations.TranslationHelperFunc, opts ...ToolOption) []invent // Dependabot tools GetDependabotAlert(t), ListDependabotAlerts(t), + UpdateDependabotAlert(t), // Notification tools ListNotifications(t), diff --git a/pkg/github/typed_security_outputs_test.go b/pkg/github/typed_security_outputs_test.go index edd28fe359..737d5018a9 100644 --- a/pkg/github/typed_security_outputs_test.go +++ b/pkg/github/typed_security_outputs_test.go @@ -36,6 +36,8 @@ func securityOutputSchema(t *testing.T, name string) *jsonschema.Schema { schema, err = jsonschema.For[*DependabotAlertOutput](nil) case "list_dependabot_alerts": schema, err = jsonschema.For[DependabotAlertsOutput](nil) + case "update_dependabot_alert": + schema, err = jsonschema.For[*DependabotAlertUpdateOutput](nil) case "get_global_security_advisory": schema, err = jsonschema.For[*GlobalSecurityAdvisoryOutput](nil) case "list_global_security_advisories": diff --git a/pkg/github/update_dependabot_alert.go b/pkg/github/update_dependabot_alert.go new file mode 100644 index 0000000000..cad135fb04 --- /dev/null +++ b/pkg/github/update_dependabot_alert.go @@ -0,0 +1,215 @@ +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 UpdateDependabotAlertInput struct { + DependabotAlertPatch + Owner string `json:"owner"` + Repo string `json:"repo"` + AlertNumber int64 `json:"alertNumber"` +} + +// Pointers distinguish untouched fields from an empty comment or assignee set. +type DependabotAlertPatch struct { + State *string `json:"state,omitempty"` + DismissedReason *string `json:"dismissed_reason,omitempty"` + DismissedComment *string `json:"dismissed_comment,omitempty"` + Assignees *[]string `json:"assignees,omitempty"` +} + +type DependabotAlertUpdateOutput struct { + Number string `json:"number" jsonschema:"Exact alert number as a decimal string to preserve integer precision."` + State string `json:"state"` + HTMLURL string `json:"html_url"` + DismissedReason *string `json:"dismissed_reason"` + DismissedComment *string `json:"dismissed_comment"` + Assignees *[]DependabotAlertAssignee `json:"assignees,omitempty"` +} + +type DependabotAlertAssignee struct { + Login string `json:"login"` +} + +func UpdateDependabotAlert(t translations.TranslationHelperFunc) inventory.ServerTool { + return NewTool( + ToolsetMetadataDependabot, + mcp.Tool{ + Name: "update_dependabot_alert", + Description: t("TOOL_UPDATE_DEPENDABOT_ALERT_DESCRIPTION", + "Update a Dependabot alert's state or assignees. Provide state or assignees; dismissal requires dismissed_reason. "+ + "Assigning copilot-swe-agent[bot] requests remediation that attempts a fix; a pull request is not guaranteed. "+ + "Requires Dependabot alerts write permission or the security_events OAuth scope. "+ + "GitHub enforces authorization, licensing, repository policies and delegated-dismissal review requirements. "+ + "Agent configuration (agent_assignment) is not supported."), + Annotations: &mcp.ToolAnnotations{ + Title: t("TOOL_UPDATE_DEPENDABOT_ALERT_USER_TITLE", "Update Dependabot 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 (username or organization)."}, + "repo": {Type: "string", MinLength: new(1), Description: "Repository name."}, + "alertNumber": {Type: "integer", Minimum: new(1.0), Description: "The repository's Dependabot alert number."}, + "state": { + Type: "string", Enum: []any{"open", "dismissed"}, + Description: "Reopen or dismiss the alert. Omission leaves state unchanged.", + }, + "dismissed_reason": { + Type: "string", Enum: []any{"fix_started", "inaccurate", "no_bandwidth", "not_used", "tolerable_risk"}, + Description: "Required when state is dismissed.", + }, + "dismissed_comment": { + Type: "string", MaxLength: new(280), + Description: "Optional dismissal comment, up to 280 characters; not a standalone comment API.", + }, + "assignees": { + Type: "array", Items: &jsonschema.Schema{Type: "string"}, + Description: "Usernames replacing the entire assignee set; [] clears all, omission leaves it unchanged. " + + "Including copilot-swe-agent[bot] requests remediation, not just ownership bookkeeping.", + }, + }, + Required: []string{"owner", "repo", "alertNumber"}, + }, + }, + scopes.RequireAll(scopes.SecurityEvents), + func(ctx context.Context, deps ToolDependencies, call *mcp.CallToolRequest, _ json.RawMessage) (*mcp.CallToolResult, *DependabotAlertUpdateOutput, error) { + // Typed schema validation passes through float64. Decode the original + // JSON so large IDs and fractional inputs cannot change the write target. + args, err := decodeDependabotAlertUpdate(call.Params.Arguments) + if err != nil { + return utils.NewToolResultErrorFromErr("invalid Dependabot 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/dependabot/alerts/%d", url.PathEscape(args.Owner), url.PathEscape(args.Repo), args.AlertNumber) + // The SDK's state update method requires state and lacks assignees. + request, err := client.NewRequest(ctx, http.MethodPatch, path, args.DependabotAlertPatch) + if err != nil { + return utils.NewToolResultErrorFromErr("failed to create Dependabot alert update request", err), nil, err + } + var alert struct { + DependabotAlertUpdateOutput + Number int64 `json:"number"` + } + resp, err := client.Do(request, &alert) + if resp != nil && resp.Body != nil { + defer func() { _ = resp.Body.Close() }() + } + const uncertainUpdate = "The Dependabot alert update may already have been applied; verify the alert with get_dependabot_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 Dependabot alert", resp, err), nil, nil + } + if resp.StatusCode != http.StatusOK || alert.Number != args.AlertNumber || alert.State == "" || alert.HTMLURL == "" { + return utils.NewToolResultError("unexpected Dependabot alert update response. " + uncertainUpdate + "."), nil, nil + } + output := alert.DependabotAlertUpdateOutput + output.Number = strconv.FormatInt(alert.Number, 10) + encoded, err := json.Marshal(output) + if err != nil { + return utils.NewToolResultErrorFromErr("failed to marshal Dependabot alert update", err), nil, err + } + result := attachStaticIFCLabel(ctx, deps, utils.NewToolResultText(string(encoded)), ifc.LabelSecurityAlert()) + return result, &output, nil + }, + normalizeDependabotAlertUpdate, + ) +} + +func normalizeDependabotAlertUpdate(raw json.RawMessage) (json.RawMessage, error) { + if _, err := decodeDependabotAlertUpdate(raw); err != nil { + return nil, &inventory.ToolInputError{Message: err.Error()} + } + return raw, nil +} + +func decodeDependabotAlertUpdate(raw json.RawMessage) (UpdateDependabotAlertInput, error) { + var args UpdateDependabotAlertInput + 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 "owner", "repo", "alertNumber", "state", "dismissed_reason", "dismissed_comment", "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 { + if !slices.Contains([]string{"open", "dismissed"}, *args.State) { + return args, errors.New("state must be open or dismissed") + } + if *args.State == "dismissed" && args.DismissedReason == nil { + return args, errors.New("dismissed_reason is required when state is dismissed") + } + } + if args.DismissedReason != nil && + !slices.Contains([]string{"fix_started", "inaccurate", "no_bandwidth", "not_used", "tolerable_risk"}, *args.DismissedReason) { + return args, errors.New("invalid dismissed_reason") + } + if args.DismissedComment != nil && utf8.RuneCountInString(*args.DismissedComment) > 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_dependabot_alert_test.go b/pkg/github/update_dependabot_alert_test.go new file mode 100644 index 0000000000..88ce23dd49 --- /dev/null +++ b/pkg/github/update_dependabot_alert_test.go @@ -0,0 +1,419 @@ +package github + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "maps" + "net/http" + "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" + gogithub "github.com/google/go-github/v92/github" + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +func dependabotUpdateSession(t *testing.T, handler http.HandlerFunc, protocol string) (*mcp.ClientSession, *BaseDeps) { + t.Helper() + deps := &BaseDeps{ + Client: mustNewGHClient(t, MockHTTPClientWithHandler(handler)), + featureChecker: featureCheckerFor(FeatureFlagIFCLabels), + } + server := mcp.NewServer(&mcp.Implementation{Name: "dependabot-update-test", Version: "1"}, nil) + server.AddReceivingMiddleware(InjectDepsMiddleware(deps)) + tool := UpdateDependabotAlert(translations.NullTranslationHelper) + tool.RegisterFunc(server, deps) + return connectCommentVisibilityClient(t, server, protocol), deps +} + +func TestUpdateDependabotAlert(t *testing.T) { + t.Parallel() + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + for _, tc := range []struct { + name, patch, response string + }{ + {"assign human", `{"assignees":["octocat"]}`, `{"state":"open","assignees":[{"login":"octocat"}]}`}, + {"assign Copilot", `{"assignees":["copilot-swe-agent[bot]"]}`, `{"state":"open","assignees":[{"login":"copilot-swe-agent[bot]"}]}`}, + {"clear", `{"assignees":[]}`, `{"state":"open","assignees":[]}`}, + {"dismiss", `{"state":"dismissed","dismissed_reason":"tolerable_risk","dismissed_comment":""}`, `{"state":"dismissed","dismissed_reason":"tolerable_risk","dismissed_comment":"","assignees":[{"login":"existing-owner"}]}`}, + {"reopen", `{"state":"open"}`, `{"state":"open","dismissed_reason":null,"dismissed_comment":null,"assignees":[]}`}, + {"combined", `{"state":"dismissed","dismissed_reason":"fix_started","assignees":["octocat"]}`, `{"state":"dismissed","dismissed_reason":"fix_started","assignees":[{"login":"octocat"}]}`}, + {"actual state differs", `{"state":"dismissed","dismissed_reason":"not_used"}`, `{"state":"open","assignees":[]}`}, + {"missing assignments stay unknown", `{"state":"open"}`, `{"state":"open"}`}, + {"280 Unicode characters", `{"state":"dismissed","dismissed_reason":"inaccurate","dismissed_comment":"` + strings.Repeat("\u00e9", 280) + `"}`, `{"state":"dismissed"}`}, + } { + t.Run(protocol+"/"+tc.name, func(t *testing.T) { + t.Parallel() + var calls int + session, deps := dependabotUpdateSession(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.Equal(t, "PATCH /repos/octo/widgets/dependabot/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), "forward only provided PATCH fields") + _, _ = fmt.Fprintf(w, `{"number":42,"html_url":"https://github.com/octo/widgets/security/dependabot/42","security_advisory":{"description":"not returned"},%s}`, tc.response[1:len(tc.response)-1]) + }, protocol) + args := json.RawMessage(`{"owner":"octo","repo":"widgets","alertNumber":42,` + tc.patch[1:]) + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "update_dependabot_alert", Arguments: args}) + require.NoError(t, err) + require.False(t, result.IsError, "%+v", result.Content) + assert.Equal(t, 1, calls, "one PATCH, no policy or issue preflights") + text := getTextResult(t, result).Text + assert.NotContains(t, text, "security_advisory") + assert.NotContains(t, text, "pull_request") + var expected map[string]any + require.NoError(t, json.Unmarshal([]byte(tc.response), &expected)) + var actual map[string]any + require.NoError(t, json.Unmarshal([]byte(text), &actual)) + for key, value := range expected { + assert.Equal(t, value, actual[key], "return the actual API %s", key) + } + assert.Equal(t, "42", actual["number"]) + if _, present := expected["assignees"]; !present { + assert.NotContains(t, actual, "assignees") + } + if protocol == inventory.ProtocolVersionMultiRoundTrip { + require.NotNil(t, result.StructuredContent) + assert.JSONEq(t, text, 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 TestUpdateDependabotAlertAPIVersionByHost(t *testing.T) { + t.Parallel() + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + for _, tc := range []struct { + name string + baseURL string + wantPath string + rejectAssignment bool + }{ + {"dotcom", "", "/repos/octo/widgets/dependabot/alerts/42", false}, + {"ghec", "https://api.example.ghe.com/", "/repos/octo/widgets/dependabot/alerts/42", false}, + {"ghes", "https://github.example.com/api/v3/", "/api/v3/repos/octo/widgets/dependabot/alerts/42", false}, + {"ghes unsupported assignment", "https://github.example.com/api/v3/", "/api/v3/repos/octo/widgets/dependabot/alerts/42", true}, + } { + t.Run(protocol+"/"+tc.name, func(t *testing.T) { + t.Parallel() + var calls int + clientOptions := []gogithub.ClientOptionsFunc{ + gogithub.WithAuthToken("test-token"), + gogithub.WithUserAgent("configured-dependabot-client"), + gogithub.WithHTTPClient(MockHTTPClientWithHandler(func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.Equal(t, http.MethodPatch, r.Method) + assert.Equal(t, tc.wantPath, r.URL.Path) + assert.Equal(t, "2022-11-28", r.Header.Get("X-GitHub-Api-Version")) + assert.Equal(t, "Bearer test-token", r.Header.Get("Authorization")) + assert.Equal(t, "configured-dependabot-client", r.Header.Get("User-Agent")) + if tc.baseURL == "" { + assert.Equal(t, "api.github.com", r.URL.Host) + } else { + assert.True(t, strings.HasPrefix(r.URL.String(), tc.baseURL)) + } + if tc.rejectAssignment { + body, err := io.ReadAll(r.Body) + require.NoError(t, err) + assert.JSONEq(t, `{"assignees":["copilot-swe-agent[bot]"]}`, string(body)) + w.WriteHeader(http.StatusUnprocessableEntity) + _, _ = io.WriteString(w, `{"message":"assignment is not supported on this server"}`) + return + } + _, _ = io.WriteString(w, `{"number":42,"state":"open","html_url":"https://github.example.com/octo/widgets/security/dependabot/42"}`) + }))} + if tc.baseURL != "" { + clientOptions = append(clientOptions, gogithub.WithEnterpriseURLs(tc.baseURL, tc.baseURL)) + } + client, err := gogithub.NewClient(clientOptions...) + require.NoError(t, err) + deps := &BaseDeps{Client: client} + inv, err := NewInventory(translations.NullTranslationHelper). + WithToolsets([]string{"dependabot"}).Build() + require.NoError(t, err) + server := mcp.NewServer(&mcp.Implementation{Name: "dependabot-host-test", Version: "1"}, nil) + server.AddReceivingMiddleware(InjectDepsMiddleware(deps)) + inv.RegisterTools(t.Context(), server, deps) + session := connectCommentVisibilityClient(t, server, protocol) + args := map[string]any{"owner": "octo", "repo": "widgets", "alertNumber": 42, "state": "open"} + if tc.rejectAssignment { + delete(args, "state") + args["assignees"] = []string{"copilot-swe-agent[bot]"} + } + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{ + Name: "update_dependabot_alert", + Arguments: args, + }) + require.NoError(t, err) + if tc.rejectAssignment { + require.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, "assignment is not supported on this server") + } else { + require.False(t, result.IsError, "%+v", result.Content) + } + assert.Equal(t, 1, calls) + request, err := 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"), "retain the shared client's default on every host") + }) + } + } +} + +func TestUpdateDependabotAlertRejectsInvalidInput(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"}, + {"alertNumber", 0}, {"alertNumber", -1}, {"alertNumber", 1.5}, {"alertNumber", "42"}, + {"alertNumber", 1e30}, {"alertNumber", nil}, + {"state", "fixed"}, {"state", ""}, {"state", nil}, + {"state", "dismissed"}, {"dismissed_reason", "false_positive"}, {"dismissed_reason", nil}, + {"dismissed_comment", nil}, {"dismissed_comment", strings.Repeat("x", 281)}, + {"dismissed_comment", strings.Repeat("\u00e9", 281)}, + {"assignees", nil}, {"assignees", "octocat"}, {"assignees", []any{nil}}, + {"agent_assignment", map[string]any{"model": "unsupported"}}, {"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":"fix_started"`, + `,"state":"dismissed"`, `,"state":"dismissed","dismissed_reason":null`, + } { + 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 := dependabotUpdateSession(t, func(w http.ResponseWriter, _ *http.Request) { + t.Error("invalid input reached GitHub") + w.WriteHeader(http.StatusInternalServerError) + }, protocol) + tool := UpdateDependabotAlert(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) + 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 TestUpdateDependabotAlertErrors(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} { + t.Run(protocol+"/"+fmt.Sprint(status), func(t *testing.T) { + t.Parallel() + var calls int + session, _ := dependabotUpdateSession(t, func(w http.ResponseWriter, _ *http.Request) { + calls++ + w.WriteHeader(status) + _, _ = io.WriteString(w, `{"message":"upstream policy denied this update"}`) + }, protocol) + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "update_dependabot_alert", Arguments: map[string]any{ + "owner": "octo", "repo": "widgets", "alertNumber": 42, "assignees": []string{"copilot-swe-agent[bot]"}, + }}) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, "upstream policy denied this update") + assert.NotContains(t, getTextResult(t, result).Text, "may already have been applied") + assert.Equal(t, 1, calls, "no fallback writes") + assert.Nil(t, result.StructuredContent) + assert.NotContains(t, result.Meta, "ifc") + }) + } + } + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + for _, tc := range []struct { + name, response, detail string + status int + }{ + {"malformed JSON", `{`, "unexpected end of JSON input", 200}, + {"wrong field type", `{"number":"42"}`, "cannot unmarshal", 200}, + {"empty body", ``, "unexpected Dependabot alert update response", 200}, + {"missing fields", `{}`, "unexpected Dependabot alert update response", 200}, + {"missing URL", `{"number":42,"state":"open"}`, "unexpected Dependabot alert update response", 200}, + {"mismatched ID", `{"number":43,"state":"open","html_url":"https://github.com/octo/widgets/security/dependabot/43"}`, "unexpected Dependabot alert update response", 200}, + {"accepted", `{`, "job scheduled on GitHub side", 202}, + {"no content", ``, "unexpected Dependabot alert update response", 204}, + } { + t.Run(protocol+"/"+tc.name, func(t *testing.T) { + t.Parallel() + var calls int + session, _ := dependabotUpdateSession(t, func(w http.ResponseWriter, _ *http.Request) { + calls++ + w.WriteHeader(tc.status) + _, _ = io.WriteString(w, tc.response) + }, protocol) + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "update_dependabot_alert", Arguments: map[string]any{ + "owner": "octo", "repo": "widgets", "alertNumber": 42, "assignees": []string{"copilot-swe-agent[bot]"}, + }}) + require.NoError(t, err) + require.True(t, result.IsError) + text := getTextResult(t, result).Text + assert.Contains(t, text, "may already have been applied") + assert.Contains(t, text, "get_dependabot_alert") + assert.Contains(t, text, "before retrying") + assert.Contains(t, text, tc.detail) + assert.Equal(t, 1, calls, "never retry an update with an unusable success response") + assert.Nil(t, result.StructuredContent) + }) + } + } +} + +func TestUpdateDependabotAlertTransportError(t *testing.T) { + t.Parallel() + session, deps := dependabotUpdateSession(t, func(_ http.ResponseWriter, _ *http.Request) { + t.Fatal("unexpected original transport call") + }, inventory.ProtocolVersionMultiRoundTrip) + httpClient, transport := NewMockHTTPClient() + transport.On("RoundTrip", mock.Anything).Return((*http.Response)(nil), errors.New("connection failed")).Once() + deps.Client = mustNewGHClient(t, httpClient) + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{ + Name: "update_dependabot_alert", + Arguments: map[string]any{"owner": "octo", "repo": "widgets", "alertNumber": 42, "state": "open"}, + }) + require.NoError(t, err) + require.True(t, result.IsError) + text := getTextResult(t, result).Text + assert.Contains(t, text, "connection failed") + assert.NotContains(t, text, "may already have been applied") + transport.AssertExpectations(t) +} + +func TestUpdateDependabotAlertExactNumbers(t *testing.T) { + t.Parallel() + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + for _, number := range []string{"9007199254740993", "9223372036854775807", "9223372036854775808", "42.000000000000000001", "1e-500"} { + t.Run(protocol+"/"+number, func(t *testing.T) { + t.Parallel() + valid := number == "9007199254740993" || number == "9223372036854775807" + var calls int + session, _ := dependabotUpdateSession(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/dependabot/alerts/"+number, r.URL.Path) + _, _ = fmt.Fprintf(w, `{"number":%s,"state":"open","html_url":"https://github.com/octo/widgets/security/dependabot/%s"}`, number, number) + }, protocol) + args := json.RawMessage(`{"owner":"octo","repo":"widgets","alertNumber":` + number + `,"state":"open"}`) + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "update_dependabot_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 TestUpdateDependabotAlertInventoryAndSchema(t *testing.T) { + t.Parallel() + tool := UpdateDependabotAlert(translations.NullTranslationHelper) + testSecurityToolSnapshot(t, tool.Tool) + assert.Equal(t, ToolsetMetadataDependabot, tool.Toolset) + assert.Equal(t, scopes.RequireAll(scopes.SecurityEvents).Scopes, tool.ScopeAccess.Scopes) + assert.False(t, tool.IsReadOnly()) + assert.True(t, *tool.Tool.Annotations.DestructiveHint) + for _, tc := range []struct { + name string + toolsets []string + readOnly bool + scopes []string + want bool + }{ + {"opt-in", []string{"dependabot"}, false, []string{"security_events"}, true}, + {"default excludes", []string{"default"}, false, []string{"security_events"}, false}, + {"read-only excludes", []string{"dependabot"}, true, []string{"security_events"}, false}, + {"missing scope excludes", []string{"dependabot"}, 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, _ := dependabotUpdateSession(t, func(_ http.ResponseWriter, _ *http.Request) { + t.Error("listing tools must not call GitHub") + }, protocol) + 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 fce4ddf6b6..f39d315ccf 100644 --- a/pkg/skills/catalog/skills/security-alert-triage/SKILL.md +++ b/pkg/skills/catalog/skills/security-alert-triage/SKILL.md @@ -8,9 +8,9 @@ description: "USE FOR: investigating GitHub security alerts — code scanning, D Turn four separate alert streams into one ordered list of decisions, each backed by evidence a maintainer can check. -**This server reads alerts; it does not resolve them.** No tool here dismisses an -alert, merges a fix, or revokes a credential. The output is a recommendation with -evidence. +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. ## Sequence @@ -81,10 +81,21 @@ outranks nothing; a moderate one on a public entry point may outrank everything. ## Confirm before anything is acted on -Every action this workflow leads to happens elsewhere: dismissing, upgrading, -revoking. Present the ordered recommendations with their evidence and get explicit -agreement before anyone acts. Never describe an alert as resolved on the strength of -a recommendation. +Present the ordered recommendations with their evidence and get explicit agreement +before acting. Never describe an alert as resolved on the strength of a recommendation. +For a requested Dependabot update, use `update_dependabot_alert` with separate +`owner`, `repo` and a positive integer `alertNumber`. Send only fields to change: +`state` is `open` or `dismissed`; dismissal also requires `dismissed_reason`. +`dismissed_comment` is a non-null string of at most 280 characters. +`assignees` replaces the entire set; `[]` clears it. Provide state or assignees; +comments alone are not supported. Assigning `copilot-swe-agent[bot]` requests +remediation but does not guarantee a fix or a pull request. Agent configuration is +not supported. GitHub enforces permissions, licensing and repository policies; +report API errors rather than claiming the update succeeded. Report the returned +state, including when a dismissal remains open pending review. +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. ## Empty and failure cases 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 33860052e6..0dd32c2d27 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 @@ -19,7 +19,8 @@ Keep them apart when reporting. ## Dependabot -- **Tools** — `list_dependabot_alerts`, `get_dependabot_alert`. +- **Tools** — `list_dependabot_alerts`, `get_dependabot_alert`, + `update_dependabot_alert` (when enabled and not read-only). - **What it finds** — known vulnerabilities in declared dependencies. It reasons about manifests, not about whether the project calls the affected code. - **Identity** — alert number, plus the advisory GHSA id. diff --git a/pkg/skills/catalog/tools.go b/pkg/skills/catalog/tools.go index 263eb5bc9d..42db2f0278 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", "get_secret_scanning_alert", "list_global_security_advisories", "get_global_security_advisory", "get_file_contents", "search_code"}, + 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"}, }, "workflow-failure-triage": { required: [][]string{{"actions_list"}, {"actions_get"}, {"get_job_logs"}},