From 302cf8a2e0dfee1ab40e965ec5bae5c1e40066a7 Mon Sep 17 00:00:00 2001 From: Peter 'Happy' Thomas <74061989+plthomasva@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:00:17 -0500 Subject: [PATCH 1/4] feat(pull-requests): add enable/disable pull request auto-merge tools Implements the enablePullRequestAutoMerge and disablePullRequestAutoMerge GraphQL mutations as two new tools in the pull requests toolset, following the standalone shape of merge_pull_request (upstream issue #2411 proposes an enable_auto_merge method 'or similar'). Each tool resolves the pull request's node ID through the REST API, then runs the mutation through the existing GraphQL client, mirroring the hide/unhide comment tools. Enable accepts an optional merge_method (merge/squash/rebase) and merge commit title/message. Includes unit tests (mocked REST + GraphQL), tool snapshots, skills catalog registration, and regenerated README/docs catalogs. Full pkg/internal test suite passes; golangci-lint reports 0 issues. --- README.md | 15 ++ .../disable_pull_request_auto_merge.snap | 66 +++++ .../enable_pull_request_auto_merge.snap | 83 ++++++ pkg/github/consolidated_pull_request_types.go | 4 + pkg/github/pullrequest_auto_merge.go | 207 ++++++++++++++ pkg/github/pullrequest_auto_merge_test.go | 255 ++++++++++++++++++ pkg/github/tools.go | 2 + pkg/skills/catalog/tools.go | 2 +- 8 files changed, 633 insertions(+), 1 deletion(-) create mode 100644 pkg/github/__toolsnaps__/disable_pull_request_auto_merge.snap create mode 100644 pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap create mode 100644 pkg/github/pullrequest_auto_merge.go create mode 100644 pkg/github/pullrequest_auto_merge_test.go diff --git a/README.md b/README.md index 166dbe0c9c..4f9716e0ba 100644 --- a/README.md +++ b/README.md @@ -1339,6 +1339,21 @@ For negotiated supported protocol versions `2026-07-28` or newer, the consolidat - `reviewers`: GitHub usernames or ORG/team-slug team reviewers to request reviews from (string[], optional) - `title`: PR title (string, required) +- **disable_pull_request_auto_merge** - Disable pull request auto-merge + - **OAuth Challenge Scopes**: `repo` + - `owner`: Repository owner (string, required) + - `pullNumber`: Pull request number (number, required) + - `repo`: Repository name (string, required) + +- **enable_pull_request_auto_merge** - Enable pull request auto-merge + - **OAuth Challenge Scopes**: `repo` + - `commit_message`: Extra detail (body) for the merge commit. If omitted, a default message will be used. Ignored when the pull request enters a merge queue. (string, optional) + - `commit_title`: Title (headline) for the merge commit. If omitted, a default message will be used. Ignored when the pull request enters a merge queue. (string, optional) + - `merge_method`: Merge method to use when the pull request becomes mergeable. If omitted, defaults to merge. Ignored when the pull request enters a merge queue. (string, optional) + - `owner`: Repository owner (string, required) + - `pullNumber`: Pull request number (number, required) + - `repo`: Repository name (string, required) + - **list_pull_requests** - List pull requests - **OAuth Challenge Scopes**: `repo` - `base`: Filter by base branch (string, optional) diff --git a/pkg/github/__toolsnaps__/disable_pull_request_auto_merge.snap b/pkg/github/__toolsnaps__/disable_pull_request_auto_merge.snap new file mode 100644 index 0000000000..5b7d029677 --- /dev/null +++ b/pkg/github/__toolsnaps__/disable_pull_request_auto_merge.snap @@ -0,0 +1,66 @@ +{ + "annotations": { + "destructiveHint": false, + "idempotentHint": false, + "openWorldHint": true, + "readOnlyHint": false, + "title": "Disable pull request auto-merge" + }, + "description": "Disable auto-merge on a pull request, so it no longer merges automatically when requirements are met. Requires write access to the repository. Auto-merge can only be enabled when the repository allows it, and disabling requires the pull request to have auto-merge enabled.", + "icons": [ + { + "mimeType": "image/png", + "src": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAACwUlEQVRIie2Vz28UZRjHP993pi0QIC3YahNjirtmd3bS3Q1eUHvQEPUiEv8A4kXjwRJ78MCFBLjBBRKCHowHE38cNCbGGx6IUoKiodtNpoNmTJp4oSJNQ3pw29l5POxus2wo3QTwxPc0887zfD7zvu9kXnjEUfdNrjj5vJOmMP4e9JrfR1G02tuQD8tvgpck0dxCPwK30ViqnJTcr4bOmfRlI/PrhUJ5313woDpDpu8ss7f6nYHrvDnGcYlPsoY/bKaXwHY3HWfvgmNnMX0zvMM7069A3c3pkEYWa7UVgFxQPSfs7SSeH3k2rEy5jMubMBoG1yQ+SBbm53of+gCybMkk/H8VAFdbZisZLAFsJ11oyL+BUURcwrjWAZixXeIwxs/5UuVAr0QAYRjubGR+HWy3mb6QCIBXQe8nce0jgIkwfMo3/xLG085x8I9ofkMyUa0O+w2rgS0mcf3lboEDiKJo1cvsIDDr4D1DhTb8407hYhTdTJW+AvrdMnuhG9Je1m9BBzbfjXbyQcXypeqJLQt7+0rVE/mgYr3j7l7FDzOPBY8FDx6vc1EolPeNjI5/Jpgw7Lm9o+Pry//c/K0PhnLFyrSMDxE79jwxvn9079gvt28vrUD7V1EoFHalbltd2C7DfS4sAF4DTSdx7cL96LliZVriPPADuL+geRh0Z8il5SiKVn2ATENvCCYw78U/b8xdBcgHlYuGHQXuK5A4ClxM4vnXW8Lqp5JdWWt6h4CvWnsgxgDSbRZ3Gg0tCJ7sY4nGwDZOt/WBZtzN9FswLgM2sGann5mcPDaw5pWEHQH7cUu86SdkR3LF6tfrA814MNVpwNrM1leUxPXrSKfMeHcwdctyNotY8c3NbMX3LJsB3ZHsymDqlkHvYHYyievXWxPpSj4o75eYIuPWZof+vRKG4c61pncIx6gZsx34/5L/ACy3ElqUYhuvAAAAAElFTkSuQmCC", + "theme": "light" + }, + { + "mimeType": "image/png", + "src": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAABn0lEQVRIie2Vvy5EURDGvyMUkhUU/pS2Q2clwvIKqL0Cm9ArrBcQShJPoLFR2YaIhIjQ7a7E39IiCgqVn8KsPY697E3oTHPumTPf990z986M9Mfm/A0wKGlMUlnSlnPuOQQAE5LOnXOFWErAIvBK1S6BZBAzZ2fzcckHjXwVaAXSwD2wWYN8A2iKK1ABt3m+ZeDRnseIthdgDxioxd1o662tfZIO7Lnf8xcklST1StqRdORxNEualHQIDDvnTmvdIGE5vwdWgLy93bQX0w0UgSdgKMC3AdfA7ndpSgKbduUbYBoI/7Ju4BiYrYFfAl4iBbxAgOyPgV9xWYDQ3xCXKK79C/wL/KJZoeW8QpsJCy0C54AMULaGmQu7sIAW4MpaxTKwbQU3U4dAxmLzwLpxXAIJP2jKgkY8Xx4o1SFwBmx7+7RxTUnVb9Bpa9HDFiR1/SRgWH+6FT3/h2qK6sBpB0aBB7yB880NcpaWtGHXjCsVBmb5PDIvgJ46BJKW84q9AguV87Adp/Q+9O8UMfQjRBKSxiV1SNp3zp3Ug/sVewPruexhKwhGXQAAAABJRU5ErkJggg==", + "theme": "dark" + } + ], + "inputSchema": { + "properties": { + "owner": { + "description": "Repository owner", + "type": "string" + }, + "pullNumber": { + "description": "Pull request number", + "minimum": 1, + "type": "number" + }, + "repo": { + "description": "Repository name", + "type": "string" + } + }, + "required": [ + "owner", + "repo", + "pullNumber" + ], + "type": "object" + }, + "name": "disable_pull_request_auto_merge", + "outputSchema": { + "additionalProperties": false, + "properties": { + "auto_merge_enabled": { + "type": "boolean" + }, + "merge_method": { + "description": "The merge method auto-merge will use, in GitHub's lowercase form (merge, squash, or rebase); omitted when auto-merge is disabled or no method was reported.", + "type": "string" + }, + "node_id": { + "type": "string" + } + }, + "required": [ + "node_id", + "auto_merge_enabled" + ], + "type": "object" + } +} \ No newline at end of file diff --git a/pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap b/pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap new file mode 100644 index 0000000000..dee0691911 --- /dev/null +++ b/pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap @@ -0,0 +1,83 @@ +{ + "annotations": { + "destructiveHint": false, + "idempotentHint": false, + "openWorldHint": true, + "readOnlyHint": false, + "title": "Enable pull request auto-merge" + }, + "description": "Enable auto-merge on a pull request, so it merges automatically once all required reviews and status checks pass. Requires write access to the repository. Auto-merge can only be enabled when the repository allows it, and disabling requires the pull request to have auto-merge enabled.", + "icons": [ + { + "mimeType": "image/png", + "src": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAACeElEQVRIibWVTUhUYRSGn/e74+iiQih1F9Vcmj9sptylUVBYkO4jcNeuJBdFKxe1CYQokGrRKjCEdtmqwEVmtqomQWeiUdc2EBUtUufe0yLHn1KLGXtX5zvn4zz3vd8f/Gfp90Qs0drmpA6MT1EveDo1NfV92wB+KnMdo39Nfs4L7eSHD5Nz1QJcJYglWtsw+iUehAuRRjO1g+0KHLerbb4OIHnHAC1FdW129s3XmUJuwnBDoOPbA7BwHsD7QWq1HKYN5msBRCpB1AueLoSROSkciSUyj5ClhE6BLtYC8CpBqVRabNrdMmIiJdQjuUbQ1WI+d78WwIbykxnzU9np7ejlNq2YxQ4ebNtTKyCyWcEgYl55EDj/a7ihFEtkLkr0As2YxjwL+9aem00dCEYNzvnJzLDvH27aaM5y80HEnKGHKGwPnEbT6fSOvzpAmrDQnkncpC7siiUzz2QqIPu25iOuGBorTufO/AJmH0v2ajHwuoHhrQHATOH9rQPJ7IjDLgs6kZ0F6it1AzArVcZLdUE+WnYgmv/uYFmz+dxH4NJGNT+RfYLCE7F4tn0pGkxHy94AmBm8/GfAVvIs7AukUTkbj5YdYIbZ9WJh8m1lzrrbNB4/tD+QuyPsdCibF26gmM/dY/NdRDqd3rEYeN04mswYL+ZXm68DxOPxnWXXMClsp+GGhCWBTtClYj53t1qXK78oVH2XYB/mHZ0pvHsN4Cczzw3rBaoGrJ6D5ZUvN1i+kjI0LWiptjmscbC88hZZCAf2trZeq1v0UsJ6wF7UAlhxUMxPvkW6AboQLbvPcjaO+BIx11cL4I9H308eOiLRQUhpOx79/66fNKzrOCYNDm0AAAAASUVORK5CYII=", + "theme": "light" + }, + { + "mimeType": "image/png", + "src": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAABjElEQVRIibWVPS/DURTGnysSC0HiZdWVrZ28JDaLT8BHaBsMdjqZJDXiAzC2LF5mX6GtATGiIsGARH+Gnj9X8a/kf3uWe3Py3Oc559xz75E6bK7VAWQkzUi6lXTonHsOpgYUgAZfdgmkQpFnjHwb6AemgDpQCiWwYlEPeL4i8JCEt8vb39g67vkmPH8yA3qt5nVgCzi1jLJBBEwkBZSAdxPKAj86LYQQQCU4cYvAKzDUSYF3YC+uRIAD8sA58ACU//VuTODE1n1g+A9c3jBH1tJ1a5TeCPNrdACSCpKeJG1IepN0LKkm6dGDrkqqOOdm7dyUpDNJi865PUnqjsvEObcJHEhaljQnaV5STwvszttXbR2J441KtB4LauLKVpZpYBDYte8mHUogZTWPrAGstTtQBl6AayDX7qHZD7AALMVGDvQBV5ZyETi2qHLtMvmXWRQAk57vBKgl4fV/0+jmq56vImk0icCnAWm7pB3riGngnlADx0TW+T4yL4CxJJy/Df20mkP/TqGHfifsA7INs3X5i3+yAAAAAElFTkSuQmCC", + "theme": "dark" + } + ], + "inputSchema": { + "properties": { + "commit_message": { + "description": "Extra detail (body) for the merge commit. If omitted, a default message will be used. Ignored when the pull request enters a merge queue.", + "type": "string" + }, + "commit_title": { + "description": "Title (headline) for the merge commit. If omitted, a default message will be used. Ignored when the pull request enters a merge queue.", + "type": "string" + }, + "merge_method": { + "description": "Merge method to use when the pull request becomes mergeable. If omitted, defaults to merge. Ignored when the pull request enters a merge queue.", + "enum": [ + "merge", + "squash", + "rebase" + ], + "type": "string" + }, + "owner": { + "description": "Repository owner", + "type": "string" + }, + "pullNumber": { + "description": "Pull request number", + "minimum": 1, + "type": "number" + }, + "repo": { + "description": "Repository name", + "type": "string" + } + }, + "required": [ + "owner", + "repo", + "pullNumber" + ], + "type": "object" + }, + "name": "enable_pull_request_auto_merge", + "outputSchema": { + "additionalProperties": false, + "properties": { + "auto_merge_enabled": { + "type": "boolean" + }, + "merge_method": { + "description": "The merge method auto-merge will use, in GitHub's lowercase form (merge, squash, or rebase); omitted when auto-merge is disabled or no method was reported.", + "type": "string" + }, + "node_id": { + "type": "string" + } + }, + "required": [ + "node_id", + "auto_merge_enabled" + ], + "type": "object" + } +} \ No newline at end of file diff --git a/pkg/github/consolidated_pull_request_types.go b/pkg/github/consolidated_pull_request_types.go index fbe8c1102a..547460e53b 100644 --- a/pkg/github/consolidated_pull_request_types.go +++ b/pkg/github/consolidated_pull_request_types.go @@ -431,6 +431,10 @@ var pullRequestArgumentSpecs = map[string]pullRequestArgumentSpec{ required: []string{"owner", "repo"}, requiredInts: []string{"pullNumber"}, strings: []string{"commit_title", "commit_message", "merge_method", "expectedHeadSha"}, }, + "auto_merge": { + required: []string{"owner", "repo"}, requiredInts: []string{"pullNumber"}, + strings: []string{"commit_title", "commit_message", "merge_method"}, + }, "branch": { required: []string{"owner", "repo"}, requiredInts: []string{"pullNumber"}, strings: []string{"expectedHeadSha"}, }, diff --git a/pkg/github/pullrequest_auto_merge.go b/pkg/github/pullrequest_auto_merge.go new file mode 100644 index 0000000000..48a4e64240 --- /dev/null +++ b/pkg/github/pullrequest_auto_merge.go @@ -0,0 +1,207 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/octicons" + "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" + "github.com/shurcooL/githubv4" +) + +// PullRequestAutoMergeInput identifies the pull request whose auto-merge +// setting changes, plus the optional merge settings used when enabling it. +type PullRequestAutoMergeInput struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + PullNumber int `json:"pullNumber"` + MergeMethod string `json:"merge_method,omitempty"` + CommitTitle string `json:"commit_title,omitempty"` + CommitMessage string `json:"commit_message,omitempty"` +} + +// PullRequestAutoMergeResult is the response returned by the enable and +// disable auto-merge tools. +type PullRequestAutoMergeResult struct { + NodeID string `json:"node_id"` + AutoMergeEnabled bool `json:"auto_merge_enabled"` + MergeMethod string `json:"merge_method,omitempty" jsonschema:"The merge method auto-merge will use, in GitHub's lowercase form (merge, squash, or rebase); omitted when auto-merge is disabled or no method was reported."` +} + +const autoMergePermissionNote = " Requires write access to the repository. Auto-merge can only be enabled when the repository allows it, and disabling requires the pull request to have auto-merge enabled." + +// EnablePullRequestAutoMerge creates a tool to enable auto-merge on a pull request. +func EnablePullRequestAutoMerge(t translations.TranslationHelperFunc) inventory.ServerTool { + return pullRequestAutoMergeTool(t, true) +} + +// DisablePullRequestAutoMerge creates a tool to disable auto-merge on a pull request. +func DisablePullRequestAutoMerge(t translations.TranslationHelperFunc) inventory.ServerTool { + return pullRequestAutoMergeTool(t, false) +} + +func pullRequestAutoMergeTool(t translations.TranslationHelperFunc, enable bool) inventory.ServerTool { + action, titleAction, icon := "disable", "Disable", "git-pull-request" + description := "Disable auto-merge on a pull request, so it no longer merges automatically when requirements are met." + if enable { + action, titleAction, icon = "enable", "Enable", "git-merge" + description = "Enable auto-merge on a pull request, so it merges automatically once all required reviews and status checks pass." + } + name := action + "_pull_request_auto_merge" + + properties := map[string]*jsonschema.Schema{ + "owner": { + Type: "string", + Description: "Repository owner", + }, + "repo": { + Type: "string", + Description: "Repository name", + }, + "pullNumber": { + Type: "number", + Description: "Pull request number", + Minimum: new(1.0), + }, + } + if enable { + properties["merge_method"] = &jsonschema.Schema{ + Type: "string", + Description: "Merge method to use when the pull request becomes mergeable. If omitted, defaults to merge. Ignored when the pull request enters a merge queue.", + Enum: []any{"merge", "squash", "rebase"}, + } + properties["commit_title"] = &jsonschema.Schema{ + Type: "string", + Description: "Title (headline) for the merge commit. If omitted, a default message will be used. Ignored when the pull request enters a merge queue.", + } + properties["commit_message"] = &jsonschema.Schema{ + Type: "string", + Description: "Extra detail (body) for the merge commit. If omitted, a default message will be used. Ignored when the pull request enters a merge queue.", + } + } + + outputSchema, err := inventory.CachedSchemaFor[PullRequestAutoMergeResult](nil) + if err != nil { + panic(fmt.Sprintf("failed to generate pull request auto-merge output schema: %v", err)) + } + + return NewTool[PullRequestAutoMergeInput, PullRequestAutoMergeResult]( + ToolsetMetadataPullRequests, + mcp.Tool{ + Name: name, + Description: t("TOOL_"+strings.ToUpper(name)+"_DESCRIPTION", description+autoMergePermissionNote), + Icons: octicons.Icons(icon), + Annotations: &mcp.ToolAnnotations{ + Title: t("TOOL_"+strings.ToUpper(name)+"_USER_TITLE", titleAction+" pull request auto-merge"), + ReadOnlyHint: false, + DestructiveHint: new(false), + OpenWorldHint: new(true), + }, + InputSchema: &jsonschema.Schema{ + Type: "object", + Properties: properties, + Required: []string{"owner", "repo", "pullNumber"}, + }, + OutputSchema: outputSchema, + }, + scopes.RequireAll(scopes.Repo), + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input PullRequestAutoMergeInput) (*mcp.CallToolResult, PullRequestAutoMergeResult, error) { + result, output := setPullRequestAutoMerge(ctx, deps, input, enable) + return result, output, nil + }, + normalizePullRequestArguments("auto_merge"), + ) +} + +func setPullRequestAutoMerge(ctx context.Context, deps ToolDependencies, input PullRequestAutoMergeInput, enable bool) (*mcp.CallToolResult, PullRequestAutoMergeResult) { + client, err := deps.GetClient(ctx) + if err != nil { + return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), PullRequestAutoMergeResult{} + } + pr, resp, err := client.PullRequests.Get(ctx, input.Owner, input.Repo, input.PullNumber) + nodeID, errResult := nodeIDFromResponse(ctx, "failed to get pull request", pr.GetNodeID(), resp, err) + if errResult != nil { + return errResult, PullRequestAutoMergeResult{} + } + + gqlClient, err := deps.GetGQLClient(ctx) + if err != nil { + return utils.NewToolResultErrorFromErr("failed to get GitHub GraphQL client", err), PullRequestAutoMergeResult{} + } + + output := PullRequestAutoMergeResult{NodeID: nodeID} + if enable { + method, err := enablePullRequestAutoMerge(ctx, gqlClient, nodeID, input) + if err != nil { + return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to enable auto-merge for pull request", nil, err), PullRequestAutoMergeResult{} + } + output.AutoMergeEnabled = true + output.MergeMethod = method + } else { + if err := disablePullRequestAutoMerge(ctx, gqlClient, nodeID); err != nil { + return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to disable auto-merge for pull request", nil, err), PullRequestAutoMergeResult{} + } + } + + r, err := json.Marshal(output) + if err != nil { + return utils.NewToolResultErrorFromErr("failed to marshal response", err), PullRequestAutoMergeResult{} + } + return utils.NewToolResultText(string(r)), output +} + +// enablePullRequestAutoMerge runs the enablePullRequestAutoMerge mutation and +// returns the merge method GitHub recorded for the auto-merge request, in +// lowercase form ("" when GitHub does not report one). +func enablePullRequestAutoMerge(ctx context.Context, client *githubv4.Client, nodeID string, input PullRequestAutoMergeInput) (string, error) { + var mutation struct { + EnablePullRequestAutoMerge struct { + PullRequest struct { + AutoMergeRequest struct { + MergeMethod githubv4.String + } + } + } `graphql:"enablePullRequestAutoMerge(input: $input)"` + } + mutationInput := githubv4.EnablePullRequestAutoMergeInput{ + PullRequestID: githubv4.ID(nodeID), + } + if input.MergeMethod != "" { + method := githubv4.PullRequestMergeMethod(strings.ToUpper(input.MergeMethod)) + mutationInput.MergeMethod = &method + } + if input.CommitTitle != "" { + headline := githubv4.String(input.CommitTitle) + mutationInput.CommitHeadline = &headline + } + if input.CommitMessage != "" { + body := githubv4.String(input.CommitMessage) + mutationInput.CommitBody = &body + } + if err := client.Mutate(ctx, &mutation, mutationInput, nil); err != nil { + return "", err + } + return strings.ToLower(string(mutation.EnablePullRequestAutoMerge.PullRequest.AutoMergeRequest.MergeMethod)), nil +} + +func disablePullRequestAutoMerge(ctx context.Context, client *githubv4.Client, nodeID string) error { + var mutation struct { + DisablePullRequestAutoMerge struct { + PullRequest struct { + ID githubv4.ID + } + } `graphql:"disablePullRequestAutoMerge(input: $input)"` + } + mutationInput := githubv4.DisablePullRequestAutoMergeInput{ + PullRequestID: githubv4.ID(nodeID), + } + return client.Mutate(ctx, &mutation, mutationInput, nil) +} diff --git a/pkg/github/pullrequest_auto_merge_test.go b/pkg/github/pullrequest_auto_merge_test.go new file mode 100644 index 0000000000..943698cd2c --- /dev/null +++ b/pkg/github/pullrequest_auto_merge_test.go @@ -0,0 +1,255 @@ +package github + +import ( + "context" + "encoding/json" + "net/http" + "testing" + + "github.com/github/github-mcp-server/v2/internal/githubv4mock" + "github.com/github/github-mcp-server/v2/internal/toolsnaps" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/google/jsonschema-go/jsonschema" + "github.com/shurcooL/githubv4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func enableAutoMergeMatcher(input githubv4.EnablePullRequestAutoMergeInput, mergeMethod string) githubv4mock.Matcher { + return githubv4mock.NewMutationMatcher( + struct { + EnablePullRequestAutoMerge struct { + PullRequest struct { + AutoMergeRequest struct { + MergeMethod githubv4.String + } + } + } `graphql:"enablePullRequestAutoMerge(input: $input)"` + }{}, + input, + nil, + githubv4mock.DataResponse(map[string]any{ + "enablePullRequestAutoMerge": map[string]any{ + "pullRequest": map[string]any{ + "autoMergeRequest": map[string]any{ + "mergeMethod": mergeMethod, + }, + }, + }, + }), + ) +} + +func disableAutoMergeMatcher(nodeID string) githubv4mock.Matcher { + return githubv4mock.NewMutationMatcher( + struct { + DisablePullRequestAutoMerge struct { + PullRequest struct { + ID githubv4.ID + } + } `graphql:"disablePullRequestAutoMerge(input: $input)"` + }{}, + githubv4.DisablePullRequestAutoMergeInput{ + PullRequestID: githubv4.ID(nodeID), + }, + nil, + githubv4mock.DataResponse(map[string]any{ + "disablePullRequestAutoMerge": map[string]any{ + "pullRequest": map[string]any{ + "id": nodeID, + }, + }, + }), + ) +} + +func autoMergeDeps(t *testing.T, prStatus int, matchers ...githubv4mock.Matcher) BaseDeps { + t.Helper() + var prHandler http.HandlerFunc + if prStatus == http.StatusOK { + prHandler = mockResponse(t, http.StatusOK, map[string]any{"node_id": "PR_42"}) + } else { + prHandler = func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(prStatus) + _, _ = w.Write([]byte(`{"message": "Not Found"}`)) + } + } + return BaseDeps{ + Client: mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + GetReposPullsByOwnerByRepoByPullNumber: prHandler, + })), + GQLClient: githubv4.NewClient(githubv4mock.NewMockedHTTPClient(matchers...)), + } +} + +func Test_EnablePullRequestAutoMerge(t *testing.T) { + serverTool := EnablePullRequestAutoMerge(translations.NullTranslationHelper) + tool := serverTool.Tool + require.NoError(t, toolsnaps.Test(tool.Name, tool)) + + assert.Equal(t, "enable_pull_request_auto_merge", tool.Name) + assert.NotEmpty(t, tool.Description) + schema := tool.InputSchema.(*jsonschema.Schema) + assert.Contains(t, schema.Properties, "owner") + assert.Contains(t, schema.Properties, "repo") + assert.Contains(t, schema.Properties, "pullNumber") + assert.Contains(t, schema.Properties, "merge_method") + assert.Contains(t, schema.Properties, "commit_title") + assert.Contains(t, schema.Properties, "commit_message") + assert.ElementsMatch(t, schema.Required, []string{"owner", "repo", "pullNumber"}) + + squash := githubv4.PullRequestMergeMethodSquash + headline := githubv4.String("Add the thing") + body := githubv4.String("Extra detail") + + tests := []struct { + name string + deps BaseDeps + requestArgs map[string]any + expectError bool + expectedResult *PullRequestAutoMergeResult + expectedErrMsg string + }{ + { + name: "enable with method and commit text", + deps: autoMergeDeps(t, http.StatusOK, enableAutoMergeMatcher(githubv4.EnablePullRequestAutoMergeInput{ + PullRequestID: githubv4.ID("PR_42"), + MergeMethod: &squash, + CommitHeadline: &headline, + CommitBody: &body, + }, "SQUASH")), + requestArgs: map[string]any{ + "owner": "owner", "repo": "repo", "pullNumber": float64(42), + "merge_method": "squash", "commit_title": "Add the thing", "commit_message": "Extra detail", + }, + expectedResult: &PullRequestAutoMergeResult{NodeID: "PR_42", AutoMergeEnabled: true, MergeMethod: "squash"}, + }, + { + name: "enable with defaults only", + deps: autoMergeDeps(t, http.StatusOK, enableAutoMergeMatcher(githubv4.EnablePullRequestAutoMergeInput{ + PullRequestID: githubv4.ID("PR_42"), + }, "MERGE")), + requestArgs: map[string]any{ + "owner": "owner", "repo": "repo", "pullNumber": float64(42), + }, + expectedResult: &PullRequestAutoMergeResult{NodeID: "PR_42", AutoMergeEnabled: true, MergeMethod: "merge"}, + }, + { + name: "pull request not found", + deps: autoMergeDeps(t, http.StatusNotFound), + requestArgs: map[string]any{ + "owner": "owner", "repo": "repo", "pullNumber": float64(42), + }, + expectError: true, + expectedErrMsg: "failed to get pull request", + }, + { + name: "mutation failure surfaces", + deps: autoMergeDeps(t, http.StatusOK, githubv4mock.NewMutationMatcher( + struct { + EnablePullRequestAutoMerge struct { + PullRequest struct { + AutoMergeRequest struct { + MergeMethod githubv4.String + } + } + } `graphql:"enablePullRequestAutoMerge(input: $input)"` + }{}, + githubv4.EnablePullRequestAutoMergeInput{PullRequestID: githubv4.ID("PR_42")}, + nil, + githubv4mock.ErrorResponse("auto-merge is not allowed for this repository"), + )), + requestArgs: map[string]any{ + "owner": "owner", "repo": "repo", "pullNumber": float64(42), + }, + expectError: true, + expectedErrMsg: "failed to enable auto-merge for pull request", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + serverTool := EnablePullRequestAutoMerge(translations.NullTranslationHelper) + handler := serverTool.Handler(tc.deps) + request := createMCPRequest(tc.requestArgs) + result, err := handler(ContextWithDeps(context.Background(), tc.deps), &request) + require.NoError(t, err) + if tc.expectError { + require.True(t, result.IsError) + errorContent := getErrorResult(t, result) + assert.Contains(t, errorContent.Text, tc.expectedErrMsg) + return + } + require.False(t, result.IsError) + textContent := getTextResult(t, result) + var returnedResult PullRequestAutoMergeResult + require.NoError(t, json.Unmarshal([]byte(textContent.Text), &returnedResult)) + assert.Equal(t, *tc.expectedResult, returnedResult) + }) + } +} + +func Test_DisablePullRequestAutoMerge(t *testing.T) { + serverTool := DisablePullRequestAutoMerge(translations.NullTranslationHelper) + tool := serverTool.Tool + require.NoError(t, toolsnaps.Test(tool.Name, tool)) + + assert.Equal(t, "disable_pull_request_auto_merge", tool.Name) + assert.NotEmpty(t, tool.Description) + schema := tool.InputSchema.(*jsonschema.Schema) + assert.Contains(t, schema.Properties, "owner") + assert.Contains(t, schema.Properties, "repo") + assert.Contains(t, schema.Properties, "pullNumber") + assert.NotContains(t, schema.Properties, "merge_method") + assert.NotContains(t, schema.Properties, "commit_title") + assert.NotContains(t, schema.Properties, "commit_message") + assert.ElementsMatch(t, schema.Required, []string{"owner", "repo", "pullNumber"}) + + tests := []struct { + name string + deps BaseDeps + requestArgs map[string]any + expectError bool + expectedResult *PullRequestAutoMergeResult + expectedErrMsg string + }{ + { + name: "disable succeeds", + deps: autoMergeDeps(t, http.StatusOK, disableAutoMergeMatcher("PR_42")), + requestArgs: map[string]any{ + "owner": "owner", "repo": "repo", "pullNumber": float64(42), + }, + expectedResult: &PullRequestAutoMergeResult{NodeID: "PR_42", AutoMergeEnabled: false}, + }, + { + name: "pull request not found", + deps: autoMergeDeps(t, http.StatusNotFound), + requestArgs: map[string]any{ + "owner": "owner", "repo": "repo", "pullNumber": float64(42), + }, + expectError: true, + expectedErrMsg: "failed to get pull request", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + serverTool := DisablePullRequestAutoMerge(translations.NullTranslationHelper) + handler := serverTool.Handler(tc.deps) + request := createMCPRequest(tc.requestArgs) + result, err := handler(ContextWithDeps(context.Background(), tc.deps), &request) + require.NoError(t, err) + if tc.expectError { + require.True(t, result.IsError) + errorContent := getErrorResult(t, result) + assert.Contains(t, errorContent.Text, tc.expectedErrMsg) + return + } + require.False(t, result.IsError) + textContent := getTextResult(t, result) + var returnedResult PullRequestAutoMergeResult + require.NoError(t, json.Unmarshal([]byte(textContent.Text), &returnedResult)) + assert.Equal(t, *tc.expectedResult, returnedResult) + }) + } +} diff --git a/pkg/github/tools.go b/pkg/github/tools.go index 6a0a262175..6a5c970d36 100644 --- a/pkg/github/tools.go +++ b/pkg/github/tools.go @@ -290,6 +290,8 @@ func AllTools(t translations.TranslationHelperFunc, opts ...ToolOption) []invent ListPullRequests(t), SearchPullRequests(t), MergePullRequest(t), + EnablePullRequestAutoMerge(t), + DisablePullRequestAutoMerge(t), UpdatePullRequestBranch(t), CreatePullRequest(t), UpdatePullRequest(t), diff --git a/pkg/skills/catalog/tools.go b/pkg/skills/catalog/tools.go index abe173d4b6..9848499261 100644 --- a/pkg/skills/catalog/tools.go +++ b/pkg/skills/catalog/tools.go @@ -45,7 +45,7 @@ var requirements = map[string]toolRequirements{ }, "pull-request-authoring": { required: [][]string{{"create_pull_request"}}, - optional: []string{"list_branches", "list_commits", "update_pull_request", "pull_request_read", "update_pull_request_branch", "actions_list", "merge_pull_request", "fork_repository", "get_file_contents", "request_pull_request_reviewers", "update_pull_request_body", "update_pull_request_draft_state", "update_pull_request_state", "update_pull_request_title"}, + optional: []string{"list_branches", "list_commits", "update_pull_request", "pull_request_read", "update_pull_request_branch", "actions_list", "merge_pull_request", "enable_pull_request_auto_merge", "disable_pull_request_auto_merge", "fork_repository", "get_file_contents", "request_pull_request_reviewers", "update_pull_request_body", "update_pull_request_draft_state", "update_pull_request_state", "update_pull_request_title"}, }, "pull-request-code-review": { required: [][]string{{"pull_request_read"}, {"pull_request_review_write", "create_pull_request_review"}, {"pull_request_review_write", "submit_pending_pull_request_review"}, {"add_comment_to_pending_review", "add_pull_request_review_comment"}}, From 6e1f878f44d39690d9583cf336c46d452529f1a5 Mon Sep 17 00:00:00 2001 From: Peter 'Happy' Thomas <74061989+plthomasva@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:16:09 -0500 Subject: [PATCH 2/4] fix(pull-requests): address Copilot review on auto-merge tools - Enable tool now sets destructiveHint: true (enabling auto-merge authorizes a later merge of the base branch); disable stays false. Enable snapshot regenerated. - Mutation failures now use NewGitHubGraphQLErrorResponse instead of the REST error helper, matching comment_minimize.go, so GetGitHubGraphQLErrors consumers see enable/disable failures. --- .../__toolsnaps__/enable_pull_request_auto_merge.snap | 2 +- pkg/github/pullrequest_auto_merge.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap b/pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap index dee0691911..d205a4fde2 100644 --- a/pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap +++ b/pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap @@ -1,6 +1,6 @@ { "annotations": { - "destructiveHint": false, + "destructiveHint": true, "idempotentHint": false, "openWorldHint": true, "readOnlyHint": false, diff --git a/pkg/github/pullrequest_auto_merge.go b/pkg/github/pullrequest_auto_merge.go index 48a4e64240..ba92d98cc6 100644 --- a/pkg/github/pullrequest_auto_merge.go +++ b/pkg/github/pullrequest_auto_merge.go @@ -102,7 +102,7 @@ func pullRequestAutoMergeTool(t translations.TranslationHelperFunc, enable bool) Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_"+strings.ToUpper(name)+"_USER_TITLE", titleAction+" pull request auto-merge"), ReadOnlyHint: false, - DestructiveHint: new(false), + DestructiveHint: new(enable), OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ @@ -141,13 +141,13 @@ func setPullRequestAutoMerge(ctx context.Context, deps ToolDependencies, input P if enable { method, err := enablePullRequestAutoMerge(ctx, gqlClient, nodeID, input) if err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to enable auto-merge for pull request", nil, err), PullRequestAutoMergeResult{} + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to enable auto-merge for pull request", err), PullRequestAutoMergeResult{} } output.AutoMergeEnabled = true output.MergeMethod = method } else { if err := disablePullRequestAutoMerge(ctx, gqlClient, nodeID); err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to disable auto-merge for pull request", nil, err), PullRequestAutoMergeResult{} + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to disable auto-merge for pull request", err), PullRequestAutoMergeResult{} } } From 9b6216551a9b164d601c4ef658e4fe8c7a837621 Mon Sep 17 00:00:00 2001 From: Peter 'Happy' Thomas <74061989+plthomasva@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:45:35 -0500 Subject: [PATCH 3/4] docs(pull-requests): state the merge_method default behavior in the enable tool Per the GraphQL schema, an omitted mergeMethod defaults to MERGE; on repositories that disallow merge commits the mutation fails with GitHub's error. Say so in the parameter description so callers pass a permitted method. Verified empirically on a squash-only repository (see PR discussion). --- pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap | 2 +- pkg/github/pullrequest_auto_merge.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap b/pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap index d205a4fde2..caa69a77b6 100644 --- a/pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap +++ b/pkg/github/__toolsnaps__/enable_pull_request_auto_merge.snap @@ -30,7 +30,7 @@ "type": "string" }, "merge_method": { - "description": "Merge method to use when the pull request becomes mergeable. If omitted, defaults to merge. Ignored when the pull request enters a merge queue.", + "description": "Merge method to use when the pull request becomes mergeable. If omitted, GitHub applies MERGE, which fails on repositories that do not allow merge commits — pass the method the repository permits. Ignored when the pull request enters a merge queue.", "enum": [ "merge", "squash", diff --git a/pkg/github/pullrequest_auto_merge.go b/pkg/github/pullrequest_auto_merge.go index ba92d98cc6..5718d0b908 100644 --- a/pkg/github/pullrequest_auto_merge.go +++ b/pkg/github/pullrequest_auto_merge.go @@ -75,7 +75,7 @@ func pullRequestAutoMergeTool(t translations.TranslationHelperFunc, enable bool) if enable { properties["merge_method"] = &jsonschema.Schema{ Type: "string", - Description: "Merge method to use when the pull request becomes mergeable. If omitted, defaults to merge. Ignored when the pull request enters a merge queue.", + Description: "Merge method to use when the pull request becomes mergeable. If omitted, GitHub applies MERGE, which fails on repositories that do not allow merge commits — pass the method the repository permits. Ignored when the pull request enters a merge queue.", Enum: []any{"merge", "squash", "rebase"}, } properties["commit_title"] = &jsonschema.Schema{ From d94c39deff0c001251a589e09f74f6b73f3a2863 Mon Sep 17 00:00:00 2001 From: Peter 'Happy' Thomas <74061989+plthomasva@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:37:05 -0500 Subject: [PATCH 4/4] docs(pull-requests): regenerate docs for the merge_method description The README's generated tool documentation still carried the pre-9b621655 merge_method wording for enable_pull_request_auto_merge. Regenerated with generate-docs so the docs check passes. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4f9716e0ba..e27c7c7595 100644 --- a/README.md +++ b/README.md @@ -1349,7 +1349,7 @@ For negotiated supported protocol versions `2026-07-28` or newer, the consolidat - **OAuth Challenge Scopes**: `repo` - `commit_message`: Extra detail (body) for the merge commit. If omitted, a default message will be used. Ignored when the pull request enters a merge queue. (string, optional) - `commit_title`: Title (headline) for the merge commit. If omitted, a default message will be used. Ignored when the pull request enters a merge queue. (string, optional) - - `merge_method`: Merge method to use when the pull request becomes mergeable. If omitted, defaults to merge. Ignored when the pull request enters a merge queue. (string, optional) + - `merge_method`: Merge method to use when the pull request becomes mergeable. If omitted, GitHub applies MERGE, which fails on repositories that do not allow merge commits — pass the method the repository permits. Ignored when the pull request enters a merge queue. (string, optional) - `owner`: Repository owner (string, required) - `pullNumber`: Pull request number (number, required) - `repo`: Repository name (string, required)