From 59c5219676f820f8d4177169ee50579170e07432 Mon Sep 17 00:00:00 2001 From: Tracy Lum <11878752+talum@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:01:37 +0000 Subject: [PATCH 1/5] Add pull request artifact read and write tools Expose list, upsert, and delete operations behind the pull_request_artifacts MCP feature flag, with repository rollout enforced by the GitHub API. Include commit-aware pagination, lockdown handling, tool snapshots, regression tests, and documentation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7bc67675-583d-4ef1-9b2a-25ae850acee2 --- docs/feature-flags.md | 72 +++ ...tifact_read_ff_pull_request_artifacts.snap | 183 ++++++ ...ifact_write_ff_pull_request_artifacts.snap | 176 ++++++ pkg/github/feature_flags.go | 5 + pkg/github/pull_request_artifact_types.go | 72 +++ pkg/github/pull_request_artifacts.go | 246 ++++++++ pkg/github/pull_request_artifacts_test.go | 539 ++++++++++++++++++ pkg/github/tools.go | 2 + pkg/skills/catalog/availability_test.go | 2 + 9 files changed, 1297 insertions(+) create mode 100644 pkg/github/__toolsnaps__/pull_request_artifact_read_ff_pull_request_artifacts.snap create mode 100644 pkg/github/__toolsnaps__/pull_request_artifact_write_ff_pull_request_artifacts.snap create mode 100644 pkg/github/pull_request_artifact_types.go create mode 100644 pkg/github/pull_request_artifacts.go create mode 100644 pkg/github/pull_request_artifacts_test.go diff --git a/docs/feature-flags.md b/docs/feature-flags.md index f19886f1be..64df579a46 100644 --- a/docs/feature-flags.md +++ b/docs/feature-flags.md @@ -136,6 +136,56 @@ Get, create, and update return an `artifact` object. List returns a `list` objec containing `artifacts`, `page`, and `perPage`; delete returns a `deleted` object containing `issue_number`, `artifact_number`, and a confirmation message. +### Pull request artifacts + +Enable `--features=pull_request_artifacts` (or +`GITHUB_FEATURES=pull_request_artifacts`) to expose +`pull_request_artifact_read` (`method: list`) and +`pull_request_artifact_write` (`method: upsert | delete`) in the +`pull_requests` toolset. This flag is **off by default**, including in Insiders +mode. Read-only mode exposes only the read tool. Both tools reject calls in +lockdown mode. + +The MCP exposure flag `pull_request_artifacts` is separate from GitHub's +`pull_request_artifacts_api` rollout flag. **The API checks the rollout flag +for the target repository, with organization context, on every operation.** +Enabling the MCP flag does not enable the API for a repository. The tools do +not substitute a per-user feature check or cache repository rollout decisions. +A 404 can mean a disabled rollout, missing resource, or insufficient access; +it is not interpreted as a definitive flag status. + +All operations require `owner`, `repo`, and `pull_number`. The tools resolve +the repository's numeric ID and use the configured authenticated GitHub +client and API base URL. They declare `repo` in OAuth challenge metadata; +the API separately enforces pull request read access for list and artifact +write access for upsert/delete, including repository writeability and storage +availability. No endpoint-specific preview header is added. + +Upsert and delete address artifacts by **name**, not artifact number or global +ID. Upsert requires `name` and `body`, and optionally accepts `commit_oid`. +The body is sent unchanged, including an empty string; the API validates its +content and constraints. Upsert accepts both creation (201) and replacement +(200) responses. Delete requires `name` and rejects `body` and `commit_oid`. +Writes are not automatically retried; API errors, including conflicts, +validation failures, throttling, and storage failures, are returned explicitly. + +List includes artifact bodies and accepts `commit_oid`: omit it or use +`current` for the PR's current head, use `all` for every commit, or supply an +explicit commit OID. For a stable commit selection across pages, use an +explicit OID instead of a moving PR head. List returns one requested page +(`page` defaults to 1, `perPage` defaults to 30 and is limited to 100). +Request `next_page` when present; its value comes from the API's REST Link +header, not the number of returned artifacts. + +Upsert returns an `artifact` object. List returns a `list` object containing +`artifacts`, `page`, `perPage`, and optional `next_page`. Delete returns a +`deleted` object containing `pull_number`, `name`, and a confirmation message. +Artifact IDs are opaque JSON strings or integers and are never mutation +identifiers. Results preserve nullable commit, creator, and timestamp +metadata; list metadata describes the returned artifact version. Names and +creator logins receive plain-text sanitization, and bodies use the existing +content sanitizer, preserving HTML source while filtering invisible characters. + Tools, resources, and prompts use `inventory.NewFeatureRule` when feature flags change whether they are available. Each rule declares the flags it references and evaluates them with a fail-closed `FeatureResolver`, so normal Go boolean @@ -518,6 +568,28 @@ as output formatting) won't appear here. - `repo`: Repository name (string, required) - `type`: (string, optional) +### `pull_request_artifacts` + +- **pull_request_artifact_read** - Read pull request artifacts + - **OAuth Challenge Scopes**: `repo` + - `commit_oid`: Commit selection: omitted or current for the current PR head, all for every commit, or an explicit commit OID (string, optional) + - `method`: (string, required) + - `owner`: Repository owner (string, required) + - `page`: Page number, starting at 1 (default 1) (integer, optional) + - `perPage`: Results per page, from 1 to 100 (default 30) (integer, optional) + - `pull_number`: Positive pull request number (integer, required) + - `repo`: Repository name (string, required) + +- **pull_request_artifact_write** - Write pull request artifacts + - **OAuth Challenge Scopes**: `repo` + - `body`: Required for upsert: artifact content; an empty string is sent unchanged. Not supported for delete (string, optional) + - `commit_oid`: Optional commit OID for upsert only; omission preserves the API default (string, optional) + - `method`: (string, required) + - `name`: Artifact name, not its number or global ID (string, required) + - `owner`: Repository owner (string, required) + - `pull_number`: Positive pull request number (integer, required) + - `repo`: Repository name (string, required) + ### `duplicate_detection` - **find_duplicate** - Find duplicate issues diff --git a/pkg/github/__toolsnaps__/pull_request_artifact_read_ff_pull_request_artifacts.snap b/pkg/github/__toolsnaps__/pull_request_artifact_read_ff_pull_request_artifacts.snap new file mode 100644 index 0000000000..36ab557c75 --- /dev/null +++ b/pkg/github/__toolsnaps__/pull_request_artifact_read_ff_pull_request_artifacts.snap @@ -0,0 +1,183 @@ +{ + "annotations": { + "destructiveHint": false, + "idempotentHint": false, + "readOnlyHint": true, + "title": "Read pull request artifacts" + }, + "description": "List GitHub pull request artifact versions including their bodies. commit_oid defaults to the current PR head; use all or an explicit commit OID to change the selection. Returns one page; request next_page when present. Repository access and the repository's pull_request_artifacts_api rollout are enforced by GitHub. Unavailable in lockdown mode.", + "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": { + "additionalProperties": false, + "properties": { + "commit_oid": { + "description": "Commit selection: omitted or current for the current PR head, all for every commit, or an explicit commit OID", + "type": "string" + }, + "method": { + "enum": [ + "list" + ], + "type": "string" + }, + "owner": { + "description": "Repository owner", + "minLength": 1, + "type": "string", + "x-mcp-header": "owner" + }, + "page": { + "description": "Page number, starting at 1 (default 1)", + "minimum": 1, + "type": "integer" + }, + "perPage": { + "description": "Results per page, from 1 to 100 (default 30)", + "maximum": 100, + "minimum": 1, + "type": "integer" + }, + "pull_number": { + "description": "Positive pull request number", + "minimum": 1, + "type": "integer" + }, + "repo": { + "description": "Repository name", + "minLength": 1, + "type": "string", + "x-mcp-header": "repo" + } + }, + "required": [ + "owner", + "repo", + "pull_number", + "method" + ], + "type": "object" + }, + "name": "pull_request_artifact_read", + "outputSchema": { + "additionalProperties": false, + "properties": { + "list": { + "additionalProperties": false, + "properties": { + "artifacts": { + "items": { + "additionalProperties": false, + "properties": { + "body": { + "type": "string" + }, + "commit_oid": { + "type": [ + "null", + "string" + ] + }, + "created_at": { + "type": [ + "null", + "string" + ] + }, + "creator": { + "additionalProperties": false, + "properties": { + "id": { + "type": "integer" + }, + "login": { + "type": "string" + } + }, + "required": [ + "login", + "id" + ], + "type": [ + "null", + "object" + ] + }, + "id": { + "description": "Opaque artifact ID; mutations use name instead", + "type": [ + "string", + "integer" + ] + }, + "name": { + "type": "string" + }, + "number": { + "type": "integer" + }, + "updated_at": { + "type": [ + "null", + "string" + ] + } + }, + "required": [ + "id", + "number", + "name", + "body", + "commit_oid", + "creator", + "created_at", + "updated_at" + ], + "type": "object" + }, + "type": [ + "null", + "array" + ] + }, + "next_page": { + "description": "Next page from the API Link header; absent when there is no next page", + "type": "integer" + }, + "page": { + "type": "integer" + }, + "perPage": { + "type": "integer" + } + }, + "required": [ + "artifacts", + "page", + "perPage" + ], + "type": [ + "null", + "object" + ] + } + }, + "required": [ + "list" + ], + "type": [ + "null", + "object" + ] + } +} \ No newline at end of file diff --git a/pkg/github/__toolsnaps__/pull_request_artifact_write_ff_pull_request_artifacts.snap b/pkg/github/__toolsnaps__/pull_request_artifact_write_ff_pull_request_artifacts.snap new file mode 100644 index 0000000000..939f0ad2fd --- /dev/null +++ b/pkg/github/__toolsnaps__/pull_request_artifact_write_ff_pull_request_artifacts.snap @@ -0,0 +1,176 @@ +{ + "annotations": { + "destructiveHint": true, + "idempotentHint": false, + "readOnlyHint": false, + "title": "Write pull request artifacts" + }, + "description": "Upsert or delete a GitHub pull request artifact by name, not its number or global ID. Upsert requires body and optionally accepts commit_oid; creates a new artifact or replaces the named artifact's content. Delete does not accept body or commit_oid. Writes are not automatically retried. Repository access and the repository's pull_request_artifacts_api rollout are enforced by GitHub. Unavailable in lockdown mode.", + "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": { + "additionalProperties": false, + "properties": { + "body": { + "description": "Required for upsert: artifact content; an empty string is sent unchanged. Not supported for delete", + "type": "string" + }, + "commit_oid": { + "description": "Optional commit OID for upsert only; omission preserves the API default", + "type": "string" + }, + "method": { + "enum": [ + "upsert", + "delete" + ], + "type": "string" + }, + "name": { + "description": "Artifact name, not its number or global ID", + "minLength": 1, + "type": "string" + }, + "owner": { + "description": "Repository owner", + "minLength": 1, + "type": "string", + "x-mcp-header": "owner" + }, + "pull_number": { + "description": "Positive pull request number", + "minimum": 1, + "type": "integer" + }, + "repo": { + "description": "Repository name", + "minLength": 1, + "type": "string", + "x-mcp-header": "repo" + } + }, + "required": [ + "owner", + "repo", + "pull_number", + "method", + "name" + ], + "type": "object" + }, + "name": "pull_request_artifact_write", + "outputSchema": { + "additionalProperties": false, + "properties": { + "artifact": { + "additionalProperties": false, + "properties": { + "body": { + "type": "string" + }, + "commit_oid": { + "type": [ + "null", + "string" + ] + }, + "created_at": { + "type": [ + "null", + "string" + ] + }, + "creator": { + "additionalProperties": false, + "properties": { + "id": { + "type": "integer" + }, + "login": { + "type": "string" + } + }, + "required": [ + "login", + "id" + ], + "type": [ + "null", + "object" + ] + }, + "id": { + "description": "Opaque artifact ID; mutations use name instead", + "type": [ + "string", + "integer" + ] + }, + "name": { + "type": "string" + }, + "number": { + "type": "integer" + }, + "updated_at": { + "type": [ + "null", + "string" + ] + } + }, + "required": [ + "id", + "number", + "name", + "body", + "commit_oid", + "creator", + "created_at", + "updated_at" + ], + "type": [ + "null", + "object" + ] + }, + "deleted": { + "additionalProperties": false, + "properties": { + "message": { + "type": "string" + }, + "name": { + "type": "string" + }, + "pull_number": { + "type": "integer" + } + }, + "required": [ + "pull_number", + "name", + "message" + ], + "type": [ + "null", + "object" + ] + } + }, + "type": [ + "null", + "object" + ] + } +} \ No newline at end of file diff --git a/pkg/github/feature_flags.go b/pkg/github/feature_flags.go index b88ba7a512..978c4529a9 100644 --- a/pkg/github/feature_flags.go +++ b/pkg/github/feature_flags.go @@ -32,6 +32,10 @@ const FeatureFlagIssueDependencies = "issue_dependencies" // endpoints. Access requirements are unverified; insiders mode does not enable it. const FeatureFlagIssueArtifacts = "issue_artifacts" +// FeatureFlagPullRequestArtifacts exposes the PR artifact tools. The API +// separately enforces pull_request_artifacts_api for the target repository. +const FeatureFlagPullRequestArtifacts = "pull_request_artifacts" + // FeatureFlagDuplicateDetection is the feature flag name for the find_duplicate // tool, which returns ranked duplicate candidates for an existing issue. It is // gated so the extra tool is not advertised by default, and is deliberately @@ -59,6 +63,7 @@ var AllowedFeatureFlags = []string{ FeatureFlagFileBlame, FeatureFlagIssueDependencies, FeatureFlagIssueArtifacts, + FeatureFlagPullRequestArtifacts, FeatureFlagDuplicateDetection, FeatureFlagThreadResolutionReason, FeatureFlagSkillsExtension, diff --git a/pkg/github/pull_request_artifact_types.go b/pkg/github/pull_request_artifact_types.go new file mode 100644 index 0000000000..ce0ceed318 --- /dev/null +++ b/pkg/github/pull_request_artifact_types.go @@ -0,0 +1,72 @@ +package github + +import "encoding/json" + +// PullRequestArtifact is an artifact or artifact version returned by the PR API. +type PullRequestArtifact struct { + ID json.RawMessage `json:"id" jsonschema:"Opaque artifact ID; mutations use name instead"` + Number int `json:"number"` + Name string `json:"name"` + Body string `json:"body"` + CommitOID *string `json:"commit_oid"` + Creator *PullRequestArtifactCreator `json:"creator"` + CreatedAt *string `json:"created_at"` + UpdatedAt *string `json:"updated_at"` +} + +// PullRequestArtifactCreator identifies the actor who wrote an artifact version. +type PullRequestArtifactCreator struct { + Login string `json:"login"` + ID int64 `json:"id"` +} + +// PullRequestArtifactCoordinates identifies the target pull request. +type PullRequestArtifactCoordinates struct { + Owner string `json:"owner" jsonschema:"Repository owner"` + Repo string `json:"repo" jsonschema:"Repository name"` + PullNumber int `json:"pull_number" jsonschema:"Positive pull request number"` +} + +// PullRequestArtifactReadInput selects a page of pull request artifact versions. +type PullRequestArtifactReadInput struct { + PullRequestArtifactCoordinates + Method string `json:"method" jsonschema:"Read operation: list"` + CommitOID string `json:"commit_oid,omitempty" jsonschema:"Commit selection: omitted or current for the current PR head, all for every commit, or an explicit commit OID"` + Page int `json:"page,omitempty" jsonschema:"Page number, starting at 1 (default 1)"` + PerPage int `json:"perPage,omitempty" jsonschema:"Results per page, from 1 to 100 (default 30)"` +} + +// PullRequestArtifactWriteInput upserts or deletes an artifact by name. +type PullRequestArtifactWriteInput struct { + PullRequestArtifactCoordinates + Method string `json:"method" jsonschema:"Write operation: upsert or delete"` + Name string `json:"name" jsonschema:"Artifact name, not its number or global ID"` + Body *string `json:"body,omitempty" jsonschema:"Required for upsert: artifact content; an empty string is sent unchanged. Not supported for delete"` + CommitOID *string `json:"commit_oid,omitempty" jsonschema:"Optional commit OID for upsert only; omission preserves the API default"` +} + +// PullRequestArtifactReadOutput contains a page of artifact versions. +type PullRequestArtifactReadOutput struct { + List *ListPullRequestArtifactsOutput `json:"list"` +} + +// ListPullRequestArtifactsOutput includes REST Link-based pagination. +type ListPullRequestArtifactsOutput struct { + Artifacts []PullRequestArtifact `json:"artifacts"` + Page int `json:"page"` + PerPage int `json:"perPage"` + NextPage int `json:"next_page,omitempty" jsonschema:"Next page from the API Link header; absent when there is no next page"` +} + +// PullRequestArtifactWriteOutput contains an upsert result or delete confirmation. +type PullRequestArtifactWriteOutput struct { + Artifact *PullRequestArtifact `json:"artifact,omitempty"` + Deleted *DeletePullRequestArtifactOutput `json:"deleted,omitempty"` +} + +// DeletePullRequestArtifactOutput confirms the named artifact that was deleted. +type DeletePullRequestArtifactOutput struct { + PullNumber int `json:"pull_number"` + Name string `json:"name"` + Message string `json:"message"` +} diff --git a/pkg/github/pull_request_artifacts.go b/pkg/github/pull_request_artifacts.go new file mode 100644 index 0000000000..2904c57693 --- /dev/null +++ b/pkg/github/pull_request_artifacts.go @@ -0,0 +1,246 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "reflect" + "slices" + "strconv" + "strings" + + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/ifc" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/sanitize" + "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" + gogithub "github.com/google/go-github/v92/github" + "github.com/google/jsonschema-go/jsonschema" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func newPullRequestArtifactTool[In, Out any](t translations.TranslationHelperFunc, name, title, description string, readOnly bool, methods []string, + handler func(context.Context, ToolDependencies, *mcp.CallToolRequest, In) (*mcp.CallToolResult, Out, error), +) inventory.ServerTool { + key := "TOOL_" + strings.ToUpper(name) + schema := issueDTOschema[In]() + schema.Properties["method"] = inventory.EnumSchema(methods...) + for _, field := range []string{"pull_number", "page", "perPage"} { + if property := schema.Properties[field]; property != nil { + property.Minimum = new(1.0) + } + } + for _, field := range []string{"owner", "repo", "name"} { + if property := schema.Properties[field]; property != nil { + property.MinLength = new(1) + } + } + for _, field := range []string{"body", "commit_oid"} { + if property := schema.Properties[field]; property != nil { + property.Type, property.Types = "string", nil + } + } + if property := schema.Properties["perPage"]; property != nil { + property.Maximum = new(100.0) + } + st := NewToolWithSchemaOptions(ToolsetMetadataPullRequests, mcp.Tool{ + Name: name, Description: t(key+"_DESCRIPTION", description), + InputSchema: schema, + Annotations: &mcp.ToolAnnotations{ + Title: t(key+"_USER_TITLE", title), ReadOnlyHint: readOnly, + DestructiveHint: new(!readOnly), + }, + }, scopes.RequireAll(scopes.Repo), inventory.TypedSchemaOptions{ + PreserveHandlerContent: true, + Output: &jsonschema.ForOptions{TypeSchemas: map[reflect.Type]*jsonschema.Schema{ + reflect.TypeFor[json.RawMessage](): {Types: []string{"string", "integer"}}, + }}, + }, handler) + st.FeatureRule = featureEnabledRule(FeatureFlagPullRequestArtifacts) + return st +} + +// PullRequestArtifactRead lists pull request artifact versions, including bodies. +func PullRequestArtifactRead(t translations.TranslationHelperFunc) inventory.ServerTool { + return newPullRequestArtifactTool(t, "pull_request_artifact_read", "Read pull request artifacts", + "List GitHub pull request artifact versions including their bodies. commit_oid defaults to the current PR head; use all or an explicit commit OID to change the selection. Returns one page; request next_page when present. Repository access and the repository's pull_request_artifacts_api rollout are enforced by GitHub. Unavailable in lockdown mode.", + true, []string{"list"}, + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input PullRequestArtifactReadInput) (*mcp.CallToolResult, *PullRequestArtifactReadOutput, error) { + if input.Method != "list" { + return utils.NewToolResultError("method must be list"), nil, nil + } + if input.Page < 0 || input.PerPage < 0 || input.PerPage > 100 { + return utils.NewToolResultError("page must be positive and perPage must be between 1 and 100"), nil, nil + } + if input.Page == 0 { + input.Page = 1 + } + if input.PerPage == 0 { + input.PerPage = 30 + } + query := url.Values{"page": {strconv.Itoa(input.Page)}, "per_page": {strconv.Itoa(input.PerPage)}} + if input.CommitOID != "" { + query.Set("commit_oid", input.CommitOID) + } + var artifacts []PullRequestArtifact + response, repository, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, "", http.MethodGet, query, nil, &artifacts, http.StatusOK) + if failure != nil { + return failure, nil, nil + } + if artifacts == nil || len(artifacts) > input.PerPage { + return utils.NewToolResultError("invalid pull request artifact list response"), nil, nil + } + for i := range artifacts { + if err := validatePullRequestArtifact(&artifacts[i]); err != nil { + return utils.NewToolResultErrorFromErr("invalid pull request artifact list response", err), nil, nil + } + sanitizePullRequestArtifact(&artifacts[i]) + } + output := &PullRequestArtifactReadOutput{List: &ListPullRequestArtifactsOutput{ + Artifacts: artifacts, Page: input.Page, PerPage: input.PerPage, NextPage: response.NextPage, + }} + return pullRequestArtifactResult(ctx, deps, repository, output), output, nil + }) +} + +// PullRequestArtifactWrite upserts or deletes a pull request artifact by name. +func PullRequestArtifactWrite(t translations.TranslationHelperFunc) inventory.ServerTool { + return newPullRequestArtifactTool(t, "pull_request_artifact_write", "Write pull request artifacts", + "Upsert or delete a GitHub pull request artifact by name, not its number or global ID. Upsert requires body and optionally accepts commit_oid; creates a new artifact or replaces the named artifact's content. Delete does not accept body or commit_oid. Writes are not automatically retried. Repository access and the repository's pull_request_artifacts_api rollout are enforced by GitHub. Unavailable in lockdown mode.", + false, []string{"upsert", "delete"}, + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input PullRequestArtifactWriteInput) (*mcp.CallToolResult, *PullRequestArtifactWriteOutput, error) { + if strings.TrimSpace(input.Name) == "" || input.Name == "." || input.Name == ".." || strings.ContainsAny(input.Name, "/\\") { + return utils.NewToolResultError("name must be a nonempty artifact path segment"), nil, nil + } + switch input.Method { + case "upsert": + if input.Body == nil { + return utils.NewToolResultError("body is required for upsert"), nil, nil + } + body := struct { + Body string `json:"body"` + CommitOID *string `json:"commit_oid,omitempty"` + }{*input.Body, input.CommitOID} + var artifact PullRequestArtifact + _, repository, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, input.Name, http.MethodPut, nil, body, &artifact, http.StatusOK, http.StatusCreated) + if failure != nil { + return failure, nil, nil + } + if err := validatePullRequestArtifact(&artifact); err != nil { + return utils.NewToolResultErrorFromErr("invalid pull request artifact response", err), nil, nil + } + if artifact.Name != input.Name { + return utils.NewToolResultError("response artifact name does not match requested name"), nil, nil + } + sanitizePullRequestArtifact(&artifact) + output := &PullRequestArtifactWriteOutput{Artifact: &artifact} + return pullRequestArtifactResult(ctx, deps, repository, output), output, nil + case "delete": + if input.Body != nil || input.CommitOID != nil { + return utils.NewToolResultError("body and commit_oid are not supported for delete"), nil, nil + } + if _, _, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, input.Name, http.MethodDelete, nil, nil, nil, http.StatusNoContent); failure != nil { + return failure, nil, nil + } + output := &PullRequestArtifactWriteOutput{Deleted: &DeletePullRequestArtifactOutput{ + PullNumber: input.PullNumber, Name: sanitize.PlainText(input.Name), Message: "artifact deleted", + }} + return MarshalledTextResult(output), output, nil + default: + return utils.NewToolResultError("method must be upsert or delete"), nil, nil + } + }) +} + +func pullRequestArtifactRequest(ctx context.Context, deps ToolDependencies, coordinates PullRequestArtifactCoordinates, name, method string, query url.Values, body, output any, statuses ...int) (*gogithub.Response, *gogithub.Repository, *mcp.CallToolResult) { + for _, segment := range []string{coordinates.Owner, coordinates.Repo} { + if strings.TrimSpace(segment) == "" || segment == "." || segment == ".." || strings.ContainsAny(segment, "/\\") { + return nil, nil, utils.NewToolResultError("owner and repo must be nonempty repository path segments") + } + } + if coordinates.PullNumber <= 0 { + return nil, nil, utils.NewToolResultError("pull_number must be positive") + } + if deps.GetFlags(ctx).LockdownMode { + return nil, nil, utils.NewToolResultError("pull request artifacts are unavailable in lockdown mode") + } + client, err := deps.GetClient(ctx) + if err != nil { + return nil, nil, utils.NewToolResultErrorFromErr("failed to get GitHub client", err) + } + repository, repoResponse, err := client.Repositories.Get(ctx, url.PathEscape(coordinates.Owner), url.PathEscape(coordinates.Repo)) + if repoResponse != nil { + defer func() { _ = repoResponse.Body.Close() }() + } + if err != nil { + return nil, nil, ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to resolve pull request artifact repository", repoResponse, err) + } + if repository == nil || repository.GetID() <= 0 { + return nil, nil, utils.NewToolResultError("repository response omitted a positive repository ID") + } + path := fmt.Sprintf("repositories/%d/pulls/%d/artifacts", repository.GetID(), coordinates.PullNumber) + if name != "" { + path += "/" + url.PathEscape(name) + } + if len(query) > 0 { + path += "?" + query.Encode() + } + request, err := client.NewRequest(ctx, method, path, body) + if err != nil { + return nil, nil, utils.NewToolResultErrorFromErr("failed to create pull request artifact request", err) + } + response, err := client.Do(request, output) + if response != nil { + defer func() { _ = response.Body.Close() }() + } + if err != nil { + message := "failed to " + strings.ToLower(method) + " pull request artifact" + if response != nil && response.StatusCode == http.StatusTooManyRequests { + if seconds, parseErr := strconv.Atoi(response.Header.Get("Retry-After")); parseErr == nil && seconds > 0 { + message += fmt.Sprintf("; Retry after %d seconds", seconds) + } + } + return nil, nil, ghErrors.NewGitHubAPIErrorResponse(ctx, message, response, err) + } + if !slices.Contains(statuses, response.StatusCode) { + return nil, nil, ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "unexpected pull request artifact response", response, nil) + } + return response, repository, nil +} + +func validatePullRequestArtifact(artifact *PullRequestArtifact) error { + if artifact.Number <= 0 || strings.TrimSpace(artifact.Name) == "" { + return fmt.Errorf("response omitted required artifact metadata") + } + // Storage IDs are opaque; preserve their wire representation rather than + // interpreting them as issue artifact IDs or accepting arbitrary JSON. + var id string + if err := json.Unmarshal(artifact.ID, &id); err == nil && id != "" { + return nil + } + var number uint64 + if err := json.Unmarshal(artifact.ID, &number); err == nil && number > 0 { + return nil + } + return fmt.Errorf("response omitted a valid artifact ID") +} + +func sanitizePullRequestArtifact(artifact *PullRequestArtifact) { + artifact.Name = sanitize.PlainText(artifact.Name) + artifact.Body = sanitize.Content(artifact.Body) + if artifact.Creator != nil { + artifact.Creator.Login = sanitize.PlainText(artifact.Creator.Login) + } +} + +func pullRequestArtifactResult(ctx context.Context, deps ToolDependencies, repository *gogithub.Repository, output any) *mcp.CallToolResult { + result := MarshalledTextResult(output) + if shouldAttachIFCLabel(ctx, deps, result) && repository.Private != nil { + setIFCLabel(result, ifc.LabelRepoUserContent(*repository.Private)) + } + return result +} diff --git a/pkg/github/pull_request_artifacts_test.go b/pkg/github/pull_request_artifacts_test.go new file mode 100644 index 0000000000..d138570b6c --- /dev/null +++ b/pkg/github/pull_request_artifacts_test.go @@ -0,0 +1,539 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "maps" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/github/github-mcp-server/v2/internal/toolsnaps" + "github.com/github/github-mcp-server/v2/pkg/ifc" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/translations" + gogithub "github.com/google/go-github/v92/github" + "github.com/google/jsonschema-go/jsonschema" + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func pullRequestArtifactTestTools() []inventory.ServerTool { + t := translations.NullTranslationHelper + return []inventory.ServerTool{PullRequestArtifactRead(t), PullRequestArtifactWrite(t)} +} + +func pullRequestArtifactTestTool(method string) inventory.ServerTool { + if method == "list" { + return PullRequestArtifactRead(translations.NullTranslationHelper) + } + return PullRequestArtifactWrite(translations.NullTranslationHelper) +} + +func pullRequestArtifactTestClient(t *testing.T, handler http.HandlerFunc) *gogithub.Client { + t.Helper() + server := httptest.NewServer(handler) + t.Cleanup(server.Close) + client, err := gogithub.NewClient( + gogithub.WithHTTPClient(server.Client()), + gogithub.WithEnterpriseURLs(server.URL+"/api/v3/", server.URL+"/api/uploads/"), + ) + require.NoError(t, err) + return client +} + +func pullRequestArtifactTestSession(t *testing.T, deps BaseDeps, protocol string) *mcp.ClientSession { + t.Helper() + inv, err := inventory.NewBuilder().SetTools(pullRequestArtifactTestTools()). + WithFeatureChecker(featureCheckerFor(FeatureFlagPullRequestArtifacts)).Build() + require.NoError(t, err) + server := mcp.NewServer(&mcp.Implementation{Name: "pull-request-artifacts", Version: "v1"}, nil) + server.AddReceivingMiddleware(InjectDepsMiddleware(deps)) + inv.RegisterTools(context.Background(), server, deps) + return connectCommentVisibilityClient(t, server, protocol) +} + +func TestPullRequestArtifactTools(t *testing.T) { + session := pullRequestArtifactTestSession(t, BaseDeps{}, inventory.ProtocolVersionMultiRoundTrip) + list, err := session.ListTools(context.Background(), nil) + require.NoError(t, err) + require.Len(t, list.Tools, 2) + for _, wireTool := range list.Tools { + require.NoError(t, toolsnaps.Test(wireTool.Name+"_ff_"+FeatureFlagPullRequestArtifacts, wireTool)) + assert.NotNil(t, wireTool.OutputSchema) + } + for _, tool := range pullRequestArtifactTestTools() { + assert.Equal(t, ToolsetMetadataPullRequests.ID, tool.Toolset.ID) + assert.Equal(t, []inventory.FeatureFlag{FeatureFlagPullRequestArtifacts}, tool.FeatureRule.Features()) + readOnly := tool.Tool.Name == "pull_request_artifact_read" + assert.Equal(t, readOnly, tool.IsReadOnly()) + assert.Equal(t, !readOnly, *tool.Tool.Annotations.DestructiveHint) + schema := tool.Tool.InputSchema.(*jsonschema.Schema) + required := []string{"owner", "repo", "pull_number", "method"} + if !readOnly { + required = append(required, "name") + } + assert.ElementsMatch(t, required, schema.Required) + } + for _, tc := range []struct { + name string + flags []inventory.FeatureFlag + toolsets []string + readOnly bool + count int + }{ + {name: "default"}, + {name: "explicit", flags: []inventory.FeatureFlag{FeatureFlagPullRequestArtifacts}, count: 2}, + {name: "read only", flags: []inventory.FeatureFlag{FeatureFlagPullRequestArtifacts}, readOnly: true, count: 1}, + {name: "read only default", readOnly: true}, + {name: "granular", flags: []inventory.FeatureFlag{FeatureFlagPullRequestArtifacts, inventory.FeatureFlag(FeatureFlagPullRequestsGranular)}, count: 2}, + {name: "pull request toolset", flags: []inventory.FeatureFlag{FeatureFlagPullRequestArtifacts}, toolsets: []string{"pull_requests"}, count: 2}, + {name: "other toolset", flags: []inventory.FeatureFlag{FeatureFlagPullRequestArtifacts}, toolsets: []string{"issues"}}, + } { + t.Run(tc.name, func(t *testing.T) { + inv, err := inventory.NewBuilder().SetTools(AllTools(translations.NullTranslationHelper)). + WithToolsets(tc.toolsets).WithReadOnly(tc.readOnly). + WithFeatureChecker(featureCheckerFor(tc.flags...)).Build() + require.NoError(t, err) + count := 0 + for _, tool := range inv.AvailableTools(context.Background()) { + if strings.HasPrefix(tool.Tool.Name, "pull_request_artifact_") { + count++ + if tc.readOnly { + assert.True(t, tool.IsReadOnly()) + } + } + } + assert.Equal(t, tc.count, count) + }) + } + assert.False(t, ResolveFeatureFlags(nil, false)[FeatureFlagPullRequestArtifacts]) + assert.False(t, ResolveFeatureFlags(nil, true)[FeatureFlagPullRequestArtifacts]) + assert.True(t, ResolveFeatureFlags([]string{"pull_request_artifacts"}, false)[FeatureFlagPullRequestArtifacts]) + assert.NotContains(t, ResolveFeatureFlags([]string{"pull_request_artifacts_api"}, false), "pull_request_artifacts_api") +} + +func TestPullRequestArtifactRequests(t *testing.T) { + artifact := `{"id":"artifact-id","number":3,"name":"report","body":"full body","commit_oid":null,"creator":null,"created_at":null,"updated_at":null}` + for _, protocol := range []string{inventory.ProtocolVersionMultiRoundTrip, "2025-11-25"} { + for _, tc := range []struct { + name, method, verb, query, body string + args map[string]any + status int + response string + next bool + }{ + {name: "upsert create empty body", method: "upsert", verb: "PUT", args: map[string]any{"name": "report", "body": ""}, body: `{"body":""}`, status: 201, response: artifact}, + {name: "upsert update with commit", method: "upsert", verb: "PUT", args: map[string]any{"name": "report", "body": "new", "commit_oid": "abc123"}, body: `{"body":"new","commit_oid":"abc123"}`, status: 200, response: artifact}, + {name: "delete", method: "delete", verb: "DELETE", args: map[string]any{"name": "report"}, status: 204}, + {name: "list default", method: "list", verb: "GET", query: "page=1&per_page=30", status: 200, response: "[" + artifact + "]"}, + {name: "list current", method: "list", verb: "GET", args: map[string]any{"commit_oid": "current"}, query: "commit_oid=current&page=1&per_page=30", status: 200, response: "[" + artifact + "]"}, + {name: "list all", method: "list", verb: "GET", args: map[string]any{"commit_oid": "all"}, query: "commit_oid=all&page=1&per_page=30", status: 200, response: "[" + artifact + "]"}, + {name: "list explicit commit and page", method: "list", verb: "GET", args: map[string]any{"commit_oid": "abc123", "page": 2, "perPage": 1}, query: "commit_oid=abc123&page=2&per_page=1", status: 200, response: "[" + artifact + "]"}, + {name: "list empty", method: "list", verb: "GET", query: "page=1&per_page=30", status: 200, response: "[]"}, + {name: "short page with next link", method: "list", verb: "GET", query: "page=1&per_page=30", status: 200, response: "[" + artifact + "]", next: true}, + {name: "full page without next link", method: "list", verb: "GET", args: map[string]any{"perPage": 1}, query: "page=1&per_page=1", status: 200, response: "[" + artifact + "]"}, + } { + t.Run(protocol+"/"+tc.name, func(t *testing.T) { + calls := 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + w.Header().Set("Content-Type", "application/json") + if calls == 1 { + assert.Equal(t, http.MethodGet, r.Method) + assert.Equal(t, "/api/v3/repos/o/r", r.URL.Path) + _, _ = w.Write([]byte(`{"id":42,"private":true}`)) + return + } + assert.Equal(t, tc.verb, r.Method) + path := "/api/v3/repositories/42/pulls/12/artifacts" + if tc.method != "list" { + path += "/report" + } + assert.Equal(t, path, r.URL.Path) + assert.Equal(t, tc.query, r.URL.RawQuery) + if tc.body != "" { + var body json.RawMessage + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + assert.JSONEq(t, tc.body, string(body)) + } + if tc.next { + w.Header().Set("Link", `; rel="next"`) + } + w.WriteHeader(tc.status) + _, _ = w.Write([]byte(tc.response)) + }) + deps := BaseDeps{Client: client, featureChecker: featureCheckerFor(FeatureFlagIFCLabels)} + session := pullRequestArtifactTestSession(t, deps, protocol) + args := map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": tc.method} + maps.Copy(args, tc.args) + tool := pullRequestArtifactTestTool(tc.method) + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: tool.Tool.Name, Arguments: args}) + require.NoError(t, err) + require.False(t, result.IsError, mustMarshalJSON(t, result)) + assert.Equal(t, 2, calls, "one repo lookup and one artifact request, without pagination or IFC refetches") + text := getTextResult(t, result).Text + if protocol == inventory.ProtocolVersionMultiRoundTrip { + assert.JSONEq(t, text, mustMarshalJSON(t, result.StructuredContent)) + } else { + assert.Nil(t, result.StructuredContent) + } + if tc.method == "delete" { + assert.JSONEq(t, `{"deleted":{"pull_number":12,"name":"report","message":"artifact deleted"}}`, text) + assert.NotContains(t, result.Meta, "ifc") + } else { + assert.JSONEq(t, mustMarshalJSON(t, ifc.PrivateTrusted()), mustMarshalJSON(t, result.Meta["ifc"])) + } + switch tc.method { + case "list": + var output PullRequestArtifactReadOutput + require.NoError(t, json.Unmarshal([]byte(text), &output)) + require.NotNil(t, output.List) + require.NotNil(t, output.List.Artifacts) + nextPage := 0 + if tc.next { + nextPage = 2 + } + assert.Equal(t, nextPage, output.List.NextPage) + if tc.name == "list explicit commit and page" { + assert.Equal(t, 2, output.List.Page) + assert.Equal(t, 1, output.List.PerPage) + } + case "upsert": + assert.JSONEq(t, `{"artifact":`+artifact+`}`, text) + } + }) + } + } +} + +func TestPullRequestArtifactEscapedNames(t *testing.T) { + for _, method := range []string{"upsert", "delete"} { + t.Run(method, func(t *testing.T) { + name := "report #1?%draft" + calls := 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + if calls == 1 { + _, _ = w.Write([]byte(`{"id":42}`)) + return + } + assert.Equal(t, "/api/v3/repositories/42/pulls/12/artifacts/"+url.PathEscape(name), r.URL.EscapedPath()) + assert.Empty(t, r.URL.RawQuery) + if method == "delete" { + w.WriteHeader(http.StatusNoContent) + return + } + _, _ = fmt.Fprintf(w, `{"id":9007199254740993,"number":3,"name":%q,"body":""}`, name) + }) + args := map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": method, "name": name} + if method == "upsert" { + args["body"] = "" + } + deps := BaseDeps{Client: client} + tool := pullRequestArtifactTestTool(method) + request := createMCPRequest(args) + result, err := tool.Handler(deps)(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + require.False(t, result.IsError, mustMarshalJSON(t, result)) + assert.Equal(t, 2, calls) + if method == "upsert" { + assert.Contains(t, getTextResult(t, result).Text, `"id":9007199254740993`) + } + }) + } +} + +func TestPullRequestArtifactRepositoryEscaping(t *testing.T) { + calls := 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + if calls == 1 { + assert.Equal(t, "/api/v3/repos/o%3Fquery/r%23fragment%252F", r.URL.EscapedPath()) + assert.Empty(t, r.URL.RawQuery) + _, _ = w.Write([]byte(`{"id":42}`)) + return + } + assert.Equal(t, "/api/v3/repositories/42/pulls/12/artifacts", r.URL.Path) + _, _ = w.Write([]byte(`[]`)) + }) + deps := BaseDeps{Client: client} + tool := PullRequestArtifactRead(translations.NullTranslationHelper) + request := createMCPRequest(map[string]any{"owner": "o?query", "repo": "r#fragment%2F", "pull_number": 12, "method": "list"}) + result, err := tool.Handler(deps)(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + require.False(t, result.IsError, mustMarshalJSON(t, result)) + assert.Equal(t, 2, calls) +} + +func TestPullRequestArtifactInvalidInputs(t *testing.T) { + for _, tc := range []struct { + name, method string + args map[string]any + }{ + {"missing body", "upsert", nil}, + {"missing name", "upsert", map[string]any{"name": "", "body": ""}}, + {"null body", "upsert", map[string]any{"body": nil}}, + {"blank name", "delete", map[string]any{"name": " "}}, + {"dot name", "delete", map[string]any{"name": "."}}, + {"traversal name", "delete", map[string]any{"name": ".."}}, + {"slash name", "delete", map[string]any{"name": "../x"}}, + {"backslash name", "delete", map[string]any{"name": `a\b`}}, + {"delete body", "delete", map[string]any{"body": ""}}, + {"delete commit", "delete", map[string]any{"commit_oid": "abc"}}, + {"negative pull", "list", map[string]any{"pull_number": -1}}, + {"missing pull", "list", map[string]any{"pull_number": 0}}, + {"empty owner", "list", map[string]any{"owner": " "}}, + {"traversal repo", "list", map[string]any{"repo": ".."}}, + {"slash owner", "list", map[string]any{"owner": "a/b"}}, + {"negative page", "list", map[string]any{"page": -1}}, + {"negative size", "list", map[string]any{"perPage": -1}}, + {"large size", "list", map[string]any{"perPage": 101}}, + {"unknown read method", "list", map[string]any{"method": "get"}}, + {"unknown write method", "upsert", map[string]any{"method": "create", "body": ""}}, + {"missing method", "list", map[string]any{"method": ""}}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + calls++ + w.WriteHeader(http.StatusInternalServerError) + }) + args := map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": tc.method} + if tc.method != "list" { + args["name"] = "report" + } + maps.Copy(args, tc.args) + deps := BaseDeps{Client: client} + tool := pullRequestArtifactTestTool(tc.method) + session := pullRequestArtifactTestSession(t, deps, inventory.ProtocolVersionMultiRoundTrip) + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: tool.Tool.Name, Arguments: args}) + require.NoError(t, err) + assert.True(t, result.IsError, mustMarshalJSON(t, result)) + request := createMCPRequest(args) + direct, err := tool.Handler(deps)(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + assert.True(t, direct.IsError, mustMarshalJSON(t, direct)) + assert.Zero(t, calls) + }) + } +} + +func TestPullRequestArtifactLockdown(t *testing.T) { + for _, method := range []string{"list", "upsert", "delete"} { + t.Run(method, func(t *testing.T) { + deps := BaseDeps{Flags: FeatureFlags{LockdownMode: true}} + tool := pullRequestArtifactTestTool(method) + args := map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": method} + if method != "list" { + args["name"] = "report" + } + if method == "upsert" { + args["body"] = "" + } + request := createMCPRequest(args) + result, err := tool.Handler(deps)(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, "lockdown") + }) + } +} + +func TestPullRequestArtifactFailures(t *testing.T) { + for _, method := range []string{"list", "upsert", "delete"} { + for _, status := range []int{400, 401, 403, 404, 409, 422, 429, 500, 503} { + t.Run(method+"/"+http.StatusText(status), func(t *testing.T) { + calls := 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + calls++ + w.Header().Set("Content-Type", "application/json") + if calls == 1 { + _, _ = w.Write([]byte(`{"id":42}`)) + return + } + if status == http.StatusTooManyRequests { + w.Header().Set("Retry-After", "60") + } + w.WriteHeader(status) + _, _ = w.Write([]byte(`{"message":"artifact access failed"}`)) + }) + deps := BaseDeps{Client: client} + tool := pullRequestArtifactTestTool(method) + args := map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": method} + if method != "list" { + args["name"] = "report" + } + if method == "upsert" { + args["body"] = "" + } + request := createMCPRequest(args) + result, err := tool.Handler(deps)(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, "artifact") + if status == http.StatusTooManyRequests { + assert.Contains(t, getTextResult(t, result).Text, "Retry after") + } + assert.Equal(t, 2, calls, "errors must not cause retries or fallback requests") + }) + } + } +} + +func TestPullRequestArtifactRepositoryFailures(t *testing.T) { + for _, response := range []struct { + status int + body string + }{ + {404, `{"message":"Not Found"}`}, + {200, `{}`}, + {200, `null`}, + } { + t.Run(response.body, func(t *testing.T) { + calls := 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.Equal(t, "/api/v3/repos/o/r", r.URL.Path) + w.WriteHeader(response.status) + _, _ = w.Write([]byte(response.body)) + }) + deps := BaseDeps{Client: client} + tool := PullRequestArtifactRead(translations.NullTranslationHelper) + request := createMCPRequest(map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": "list"}) + result, err := tool.Handler(deps)(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Equal(t, 1, calls, "lookup failure must prevent artifact access") + }) + } +} + +func TestPullRequestArtifactRepositoryGate(t *testing.T) { + for _, method := range []string{"list", "upsert", "delete"} { + t.Run(method, func(t *testing.T) { + calls := 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + switch r.URL.Path { + case "/api/v3/repos/o/enabled": + _, _ = w.Write([]byte(`{"id":42}`)) + case "/api/v3/repos/o/disabled": + _, _ = w.Write([]byte(`{"id":43}`)) + default: + if strings.HasPrefix(r.URL.Path, "/api/v3/repositories/43/") { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"message":"Not Found"}`)) + return + } + require.True(t, strings.HasPrefix(r.URL.Path, "/api/v3/repositories/42/")) + artifact := `{"id":"a","number":1,"name":"report","body":""}` + switch method { + case "list": + _, _ = w.Write([]byte("[" + artifact + "]")) + case "upsert": + _, _ = w.Write([]byte(artifact)) + case "delete": + w.WriteHeader(http.StatusNoContent) + } + } + }) + deps := BaseDeps{Client: client} + ctx := inventory.WithFeatureState(ContextWithDeps(context.Background(), deps), featureCheckerFor(FeatureFlagPullRequestArtifacts)) + tool := pullRequestArtifactTestTool(method) + for _, repo := range []string{"enabled", "disabled", "enabled"} { + args := map[string]any{"owner": "o", "repo": repo, "pull_number": 12, "method": method} + if method != "list" { + args["name"] = "report" + } + if method == "upsert" { + args["body"] = "" + } + request := createMCPRequest(args) + result, err := tool.Handler(deps)(ctx, &request) + require.NoError(t, err) + assert.Equal(t, repo == "disabled", result.IsError, mustMarshalJSON(t, result)) + } + assert.Equal(t, 6, calls) + }) + } +} + +func TestPullRequestArtifactResponseValidation(t *testing.T) { + for _, tc := range []struct { + name, method, response string + status int + }{ + {"null list", "list", "null", 200}, + {"missing ID", "list", `[{"number":1,"name":"report","body":""}]`, 200}, + {"invalid ID", "list", `[{"id":{},"number":1,"name":"report","body":""}]`, 200}, + {"missing number", "upsert", `{"id":"a","name":"report","body":""}`, 200}, + {"mismatched name", "upsert", `{"id":"a","number":1,"name":"other","body":""}`, 200}, + {"unexpected success", "upsert", `{}`, 202}, + {"unexpected delete", "delete", `{}`, 200}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + calls++ + if calls == 1 { + _, _ = w.Write([]byte(`{"id":42}`)) + return + } + w.WriteHeader(tc.status) + _, _ = w.Write([]byte(tc.response)) + }) + deps := BaseDeps{Client: client} + tool := pullRequestArtifactTestTool(tc.method) + args := map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": tc.method} + if tc.method != "list" { + args["name"] = "report" + } + if tc.method == "upsert" { + args["body"] = "" + } + request := createMCPRequest(args) + result, err := tool.Handler(deps)(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + require.True(t, result.IsError) + assert.Equal(t, 2, calls) + }) + } +} + +func TestPullRequestArtifactSanitization(t *testing.T) { + calls := 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + calls++ + if calls == 1 { + _, _ = w.Write([]byte(`{"id":42,"private":false}`)) + return + } + _, _ = w.Write([]byte(`[{"id":123,"number":1,"name":"report","body":"

sa\u200bfe

","commit_oid":"abc123","creator":{"login":"octocat","id":7},"created_at":"2026-11-13T00:00:00Z","updated_at":"2026-11-13T00:00:00Z"}]`)) + }) + deps := BaseDeps{Client: client, featureChecker: featureCheckerFor(FeatureFlagIFCLabels)} + session := pullRequestArtifactTestSession(t, deps, inventory.ProtocolVersionMultiRoundTrip) + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{ + Name: "pull_request_artifact_read", Arguments: map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": "list"}, + }) + require.NoError(t, err) + require.False(t, result.IsError, mustMarshalJSON(t, result)) + var output PullRequestArtifactReadOutput + require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &output)) + require.Len(t, output.List.Artifacts, 1) + artifact := output.List.Artifacts[0] + assert.Equal(t, "report", artifact.Name) + assert.Equal(t, "

safe

", artifact.Body) + require.NotNil(t, artifact.Creator) + assert.Equal(t, "octocat", artifact.Creator.Login) + assert.Equal(t, int64(7), artifact.Creator.ID) + assert.Equal(t, "abc123", *artifact.CommitOID) + assert.Equal(t, "2026-11-13T00:00:00Z", *artifact.CreatedAt) + assert.Equal(t, "2026-11-13T00:00:00Z", *artifact.UpdatedAt) + assert.JSONEq(t, mustMarshalJSON(t, ifc.PublicUntrusted()), mustMarshalJSON(t, result.Meta["ifc"])) + assert.Equal(t, 2, calls) +} diff --git a/pkg/github/tools.go b/pkg/github/tools.go index 47189398b8..577c9620ed 100644 --- a/pkg/github/tools.go +++ b/pkg/github/tools.go @@ -287,6 +287,8 @@ func AllTools(t translations.TranslationHelperFunc, opts ...ToolOption) []invent UpdatePullRequestBranch(t), CreatePullRequest(t), UpdatePullRequest(t), + PullRequestArtifactRead(t), + PullRequestArtifactWrite(t), pullRequestReviewWrite(t, false, cfg), PullRequestReviewWriteWithResolutionReason(t, opts...), AddCommentToPendingReview(t), diff --git a/pkg/skills/catalog/availability_test.go b/pkg/skills/catalog/availability_test.go index e95571ef4a..3789deb849 100644 --- a/pkg/skills/catalog/availability_test.go +++ b/pkg/skills/catalog/availability_test.go @@ -32,6 +32,8 @@ var toolCoverageExemptions = map[string]string{ "issue_dependency_read": "Issue dependency graph management is distinct from the current backlog triage workflow.", "issue_dependency_write": "Issue dependency graph management is distinct from the current backlog triage workflow.", "list_gists": "Gist lifecycle is separate from the repository workflows covered by the current catalog.", + "pull_request_artifact_read": "Pull request artifact management is a separate workflow not covered by the current catalog.", + "pull_request_artifact_write": "Pull request artifact management is a separate workflow not covered by the current catalog.", "remove_issue_comment_reaction": "Reactions are optional social signals, not a workflow in the current skills.", "remove_issue_reaction": "Reactions are optional social signals, not a workflow in the current skills.", "remove_pull_request_review_comment_reaction": "Reactions are optional social signals, not a workflow in the current skills.", From b36eda3da83831c49b538dadaf99266f14cd459c Mon Sep 17 00:00:00 2001 From: Tracy Lum <11878752+talum@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:14:42 +0000 Subject: [PATCH 2/5] Require artifact deletion approval and preserve addressing keys Add target-bound, expiring MCP confirmation for pull request artifact deletion and lossless name keys for safe read-to-write round trips. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7bc67675-583d-4ef1-9b2a-25ae850acee2 --- docs/feature-flags.md | 25 +- ...tifact_read_ff_pull_request_artifacts.snap | 10 +- ...ifact_write_ff_pull_request_artifacts.snap | 26 +- .../pull_request_artifact_approval_test.go | 264 ++++++++++++++++++ .../pull_request_artifact_names_test.go | 131 +++++++++ pkg/github/pull_request_artifact_types.go | 11 +- pkg/github/pull_request_artifacts.go | 154 +++++++++- pkg/github/pull_request_artifacts_test.go | 91 +++--- 8 files changed, 647 insertions(+), 65 deletions(-) create mode 100644 pkg/github/pull_request_artifact_approval_test.go create mode 100644 pkg/github/pull_request_artifact_names_test.go diff --git a/docs/feature-flags.md b/docs/feature-flags.md index 64df579a46..7a7857d029 100644 --- a/docs/feature-flags.md +++ b/docs/feature-flags.md @@ -162,10 +162,25 @@ write access for upsert/delete, including repository writeability and storage availability. No endpoint-specific preview header is added. Upsert and delete address artifacts by **name**, not artifact number or global -ID. Upsert requires `name` and `body`, and optionally accepts `commit_oid`. +ID. Supply exactly one of `name` (the exact original name) or `name_key` (the +lossless key returned by reads and writes). Returned `name` values are sanitized +for display and must not be used as mutation keys: distinct original names can +have the same display name. Pass `name_key` verbatim to update or delete an +artifact discovered through a read. Keys use unpadded URL-safe Base64 encoding +of the original name and are not authorization tokens. +Upsert requires `body` and optionally accepts `commit_oid`. The body is sent unchanged, including an empty string; the API validates its content and constraints. Upsert accepts both creation (201) and replacement -(200) responses. Delete requires `name` and rejects `body` and `commit_oid`. +(200) responses. Delete rejects `body` and `commit_oid`. +Before deletion, the client must obtain explicit user confirmation of the exact +repository, PR number, and artifact name through form elicitation. Confirmation +requires MCP protocol `2026-07-28` or later and configured request-state protection. +The protected state binds approval to the target repository ID, PR, and artifact +name and expires after ten minutes. Missing, invalid, expired, declined, or +canceled confirmation prevents deletion, as does a changed repository identity. +Clients without the required protocol or form-elicitation support cannot delete; +list and upsert remain available. This relies on the client to present the +confirmation to the user rather than answer on the model's behalf. Writes are not automatically retried; API errors, including conflicts, validation failures, throttling, and storage failures, are returned explicitly. @@ -179,7 +194,8 @@ header, not the number of returned artifacts. Upsert returns an `artifact` object. List returns a `list` object containing `artifacts`, `page`, `perPage`, and optional `next_page`. Delete returns a -`deleted` object containing `pull_number`, `name`, and a confirmation message. +`deleted` object containing `pull_number`, display `name`, lossless `name_key`, +and a confirmation message. Artifact IDs are opaque JSON strings or integers and are never mutation identifiers. Results preserve nullable commit, creator, and timestamp metadata; list metadata describes the returned artifact version. Names and @@ -585,7 +601,8 @@ as output formatting) won't appear here. - `body`: Required for upsert: artifact content; an empty string is sent unchanged. Not supported for delete (string, optional) - `commit_oid`: Optional commit OID for upsert only; omission preserves the API default (string, optional) - `method`: (string, required) - - `name`: Artifact name, not its number or global ID (string, required) + - `name`: Exact artifact name for creation or addressing; mutually exclusive with name_key. Do not copy sanitized display names from read results (string, optional) + - `name_key`: Lossless addressing key returned by artifact reads or writes; mutually exclusive with name. Pass verbatim without decoding (string, optional) - `owner`: Repository owner (string, required) - `pull_number`: Positive pull request number (integer, required) - `repo`: Repository name (string, required) diff --git a/pkg/github/__toolsnaps__/pull_request_artifact_read_ff_pull_request_artifacts.snap b/pkg/github/__toolsnaps__/pull_request_artifact_read_ff_pull_request_artifacts.snap index 36ab557c75..2641e58969 100644 --- a/pkg/github/__toolsnaps__/pull_request_artifact_read_ff_pull_request_artifacts.snap +++ b/pkg/github/__toolsnaps__/pull_request_artifact_read_ff_pull_request_artifacts.snap @@ -5,7 +5,7 @@ "readOnlyHint": true, "title": "Read pull request artifacts" }, - "description": "List GitHub pull request artifact versions including their bodies. commit_oid defaults to the current PR head; use all or an explicit commit OID to change the selection. Returns one page; request next_page when present. Repository access and the repository's pull_request_artifacts_api rollout are enforced by GitHub. Unavailable in lockdown mode.", + "description": "List GitHub pull request artifact versions including their bodies. Names are sanitized for display; use the returned name_key, not name, for subsequent writes. commit_oid defaults to the current PR head; use all or an explicit commit OID to change the selection. Returns one page; request next_page when present. Repository access and the repository's pull_request_artifacts_api rollout are enforced by GitHub. Unavailable in lockdown mode.", "icons": [ { "mimeType": "image/png", @@ -114,13 +114,18 @@ ] }, "id": { - "description": "Opaque artifact ID; mutations use name instead", + "description": "Opaque artifact ID; mutations use name or name_key instead", "type": [ "string", "integer" ] }, "name": { + "description": "Sanitized display name; use name_key when addressing this artifact", + "type": "string" + }, + "name_key": { + "description": "Lossless base64url-encoded artifact name; pass verbatim as name_key to write operations", "type": "string" }, "number": { @@ -137,6 +142,7 @@ "id", "number", "name", + "name_key", "body", "commit_oid", "creator", diff --git a/pkg/github/__toolsnaps__/pull_request_artifact_write_ff_pull_request_artifacts.snap b/pkg/github/__toolsnaps__/pull_request_artifact_write_ff_pull_request_artifacts.snap index 939f0ad2fd..7e266ddaab 100644 --- a/pkg/github/__toolsnaps__/pull_request_artifact_write_ff_pull_request_artifacts.snap +++ b/pkg/github/__toolsnaps__/pull_request_artifact_write_ff_pull_request_artifacts.snap @@ -5,7 +5,7 @@ "readOnlyHint": false, "title": "Write pull request artifacts" }, - "description": "Upsert or delete a GitHub pull request artifact by name, not its number or global ID. Upsert requires body and optionally accepts commit_oid; creates a new artifact or replaces the named artifact's content. Delete does not accept body or commit_oid. Writes are not automatically retried. Repository access and the repository's pull_request_artifacts_api rollout are enforced by GitHub. Unavailable in lockdown mode.", + "description": "Upsert or delete a GitHub pull request artifact using exactly one of name (the exact original name) or name_key (the lossless key returned by reads or writes), not its number or global ID. Never use a sanitized display name to address an existing artifact. Upsert requires body and optionally accepts commit_oid; creates a new artifact or replaces the named artifact's content. Delete requires explicit user confirmation through form elicitation with MCP protocol 2026-07-28 or later, and does not accept body or commit_oid. Writes are not automatically retried. Repository access and the repository's pull_request_artifacts_api rollout are enforced by GitHub. Unavailable in lockdown mode.", "icons": [ { "mimeType": "image/png", @@ -37,7 +37,12 @@ "type": "string" }, "name": { - "description": "Artifact name, not its number or global ID", + "description": "Exact artifact name for creation or addressing; mutually exclusive with name_key. Do not copy sanitized display names from read results", + "minLength": 1, + "type": "string" + }, + "name_key": { + "description": "Lossless addressing key returned by artifact reads or writes; mutually exclusive with name. Pass verbatim without decoding", "minLength": 1, "type": "string" }, @@ -63,8 +68,7 @@ "owner", "repo", "pull_number", - "method", - "name" + "method" ], "type": "object" }, @@ -110,13 +114,18 @@ ] }, "id": { - "description": "Opaque artifact ID; mutations use name instead", + "description": "Opaque artifact ID; mutations use name or name_key instead", "type": [ "string", "integer" ] }, "name": { + "description": "Sanitized display name; use name_key when addressing this artifact", + "type": "string" + }, + "name_key": { + "description": "Lossless base64url-encoded artifact name; pass verbatim as name_key to write operations", "type": "string" }, "number": { @@ -133,6 +142,7 @@ "id", "number", "name", + "name_key", "body", "commit_oid", "creator", @@ -151,6 +161,11 @@ "type": "string" }, "name": { + "description": "Sanitized display name of the deleted artifact", + "type": "string" + }, + "name_key": { + "description": "Lossless addressing key of the deleted artifact", "type": "string" }, "pull_number": { @@ -160,6 +175,7 @@ "required": [ "pull_number", "name", + "name_key", "message" ], "type": [ diff --git a/pkg/github/pull_request_artifact_approval_test.go b/pkg/github/pull_request_artifact_approval_test.go new file mode 100644 index 0000000000..4540359c52 --- /dev/null +++ b/pkg/github/pull_request_artifact_approval_test.go @@ -0,0 +1,264 @@ +package github + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "testing" + "time" + + "github.com/github/github-mcp-server/v2/internal/requeststate" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func pullRequestArtifactApprovalRequest(args map[string]any) mcp.CallToolRequest { + request := createMCPRequest(args) + request.Params.Meta = mcp.Meta{ + mcp.MetaKeyProtocolVersion: inventory.ProtocolVersionMultiRoundTrip, + mcp.MetaKeyClientCapabilities: map[string]any{ + "elicitation": map[string]any{"form": map[string]any{}}, + }, + } + return request +} + +func invokePullRequestArtifactWithApproval(ctx context.Context, t *testing.T, deps BaseDeps, args map[string]any) *mcp.CallToolResult { + t.Helper() + sealer, err := requeststate.NewRandom() + require.NoError(t, err) + deps.StateSealer = sealer + tool := pullRequestArtifactTestTool(args["method"].(string)) + handler := tool.Handler(deps) + request := pullRequestArtifactApprovalRequest(args) + result, err := handler(ContextWithDeps(ctx, deps), &request) + require.NoError(t, err) + if args["method"] != "delete" || result.IsError { + return result + } + require.Contains(t, result.InputRequests, deletePullRequestArtifactConfirmationID) + require.NotEmpty(t, result.RequestState) + request.Params.RequestState = result.RequestState + request.Params.InputResponses = mcp.InputResponseMap{ + deletePullRequestArtifactConfirmationID: &mcp.ElicitResult{ + Action: "accept", + Content: map[string]any{ + deletePullRequestArtifactConfirmationField: artifactApprovalTarget(args), + }, + }, + } + result, err = handler(ContextWithDeps(ctx, deps), &request) + require.NoError(t, err) + return result +} + +func artifactApprovalTarget(args map[string]any) string { + name, _ := args["name"].(string) + if key, ok := args["name_key"].(string); ok { + decoded, _ := base64.RawURLEncoding.DecodeString(key) + name = string(decoded) + } + return fmt.Sprintf("%s/%s#%d artifact %q", args["owner"], args["repo"], args["pull_number"], name) +} + +func TestPullRequestArtifactDeleteApproval(t *testing.T) { + for _, action := range []string{"accept", "decline", "cancel"} { + t.Run(action, func(t *testing.T) { + lookups, deletes, prompts := 0, 0, 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + lookups++ + assert.Equal(t, "/api/v3/repos/o/r", r.URL.Path) + _, _ = w.Write([]byte(`{"id":42}`)) + case http.MethodDelete: + deletes++ + assert.Equal(t, 1, prompts, "approval must precede DELETE") + assert.Equal(t, "/api/v3/repositories/42/pulls/12/artifacts/report", r.URL.Path) + w.WriteHeader(http.StatusNoContent) + default: + t.Errorf("unexpected method %s", r.Method) + } + }) + sealer, err := requeststate.NewRandom() + require.NoError(t, err) + session := pullRequestArtifactTestSession(t, BaseDeps{Client: client, StateSealer: sealer}, + inventory.ProtocolVersionMultiRoundTrip, &mcp.ClientOptions{ + ElicitationHandler: func(_ context.Context, req *mcp.ElicitRequest) (*mcp.ElicitResult, error) { + prompts++ + assert.Zero(t, deletes) + assert.Equal(t, "form", req.Params.Mode) + assert.Contains(t, req.Params.Message, `o/r#12 artifact \"report\"`) + return &mcp.ElicitResult{ + Action: action, + Content: map[string]any{ + deletePullRequestArtifactConfirmationField: `o/r#12 artifact "report"`, + }, + }, nil + }, + }) + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{ + Name: "pull_request_artifact_write", + Arguments: map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": "delete", "name": "report"}, + }) + require.NoError(t, err) + assert.Equal(t, 1, prompts) + if action == "accept" { + require.False(t, result.IsError, mustMarshalJSON(t, result)) + assert.Equal(t, 2, lookups, "repository identity must be rechecked") + assert.Equal(t, 1, deletes) + assert.JSONEq(t, `{"deleted":{"pull_number":12,"name":"report","name_key":"cmVwb3J0","message":"artifact deleted"}}`, getTextResult(t, result).Text) + assert.JSONEq(t, getTextResult(t, result).Text, mustMarshalJSON(t, result.StructuredContent)) + } else { + require.True(t, result.IsError) + assert.Equal(t, 1, lookups) + assert.Zero(t, deletes) + } + }) + } +} + +func TestPullRequestArtifactDeleteInvalidApproval(t *testing.T) { + for _, name := range []string{ + "missing state", "tampered state", "invalid state JSON", "expired state", + "changed owner", "changed repo", "changed PR", "changed name", "changed operation", + "invalid repository ID", "recreated repository", "wrong confirmation", "missing confirmation", + "invalid response", "lockdown after confirmation", + } { + t.Run(name, func(t *testing.T) { + calls := 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.Equal(t, http.MethodGet, r.Method, "invalid approval must never dispatch DELETE") + id := 42 + if name == "recreated repository" && calls > 1 { + id = 43 + } + require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"id": id})) + }) + sealer, err := requeststate.NewRandom() + require.NoError(t, err) + deps := BaseDeps{Client: client, StateSealer: sealer} + tool := PullRequestArtifactWrite(translations.NullTranslationHelper) + handler := tool.Handler(deps) + args := map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": "delete", "name": "report"} + request := pullRequestArtifactApprovalRequest(args) + ctx := ContextWithDeps(context.Background(), deps) + first, err := handler(ctx, &request) + require.NoError(t, err) + require.False(t, first.IsError, mustMarshalJSON(t, first)) + require.Contains(t, first.InputRequests, deletePullRequestArtifactConfirmationID) + assert.Empty(t, first.Content) + assert.Nil(t, first.StructuredContent) + require.Equal(t, 1, calls, "requesting approval must only resolve the repository") + stateJSON, err := sealer.Open(first.RequestState) + require.NoError(t, err) + var state deletePullRequestArtifactState + require.NoError(t, json.Unmarshal(stateJSON, &state)) + assert.Equal(t, int64(42), state.RepositoryID) + assert.Equal(t, 12, state.PullNumber) + assert.Equal(t, "report", state.Name) + assert.InDelta(t, time.Now().Add(10*time.Minute).Unix(), state.ExpiresAt, 2) + confirmation := &mcp.ElicitResult{ + Action: "accept", + Content: map[string]any{deletePullRequestArtifactConfirmationField: artifactApprovalTarget(args)}, + } + switch name { + case "changed owner": + args["owner"] = "other" + case "changed repo": + args["repo"] = "other" + case "changed PR": + args["pull_number"] = 13 + case "changed name": + args["name"] = "other" + case "changed operation": + state.Operation = "another_tool:delete" + case "invalid repository ID": + state.RepositoryID = 0 + case "expired state": + state.ExpiresAt = time.Now().Add(-time.Second).Unix() + case "wrong confirmation": + confirmation.Content[deletePullRequestArtifactConfirmationField] = "report" + case "missing confirmation": + confirmation.Content = nil + case "lockdown after confirmation": + deps.Flags.LockdownMode = true + handler = tool.Handler(deps) + ctx = ContextWithDeps(context.Background(), deps) + } + stateJSON, err = json.Marshal(state) + require.NoError(t, err) + if name == "invalid state JSON" { + stateJSON = []byte(`{`) + } + request = pullRequestArtifactApprovalRequest(args) + request.Params.RequestState, err = sealer.Seal(ctx, stateJSON) + require.NoError(t, err) + if name == "missing state" { + request.Params.RequestState = "" + } + if name == "tampered state" { + request.Params.RequestState = "forged-token" + } + request.Params.InputResponses = mcp.InputResponseMap{deletePullRequestArtifactConfirmationID: confirmation} + if name == "invalid response" { + request.Params.InputResponses[deletePullRequestArtifactConfirmationID] = nil + } + result, err := handler(ctx, &request) + require.NoError(t, err) + require.True(t, result.IsError, mustMarshalJSON(t, result)) + expectedCalls := 1 + if name == "recreated repository" { + expectedCalls++ + } + assert.Equal(t, expectedCalls, calls) + }) + } +} + +func TestPullRequestArtifactDeleteUnsupportedClient(t *testing.T) { + for _, name := range []string{"legacy", "unknown protocol", "missing capabilities", "URL only", "no sealer", "nil request"} { + t.Run(name, func(t *testing.T) { + calls := 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + calls++ + w.WriteHeader(http.StatusInternalServerError) + }) + sealer, err := requeststate.NewRandom() + require.NoError(t, err) + deps := BaseDeps{Client: client, StateSealer: sealer} + coordinates := PullRequestArtifactCoordinates{Owner: "o", Repo: "r", PullNumber: 12} + input := PullRequestArtifactWriteInput{ + PullRequestArtifactCoordinates: coordinates, + Method: "delete", Name: "report", + } + request := pullRequestArtifactApprovalRequest(nil) + switch name { + case "legacy": + request.Params.Meta[mcp.MetaKeyProtocolVersion] = "2025-11-25" + case "unknown protocol": + delete(request.Params.Meta, mcp.MetaKeyProtocolVersion) + case "missing capabilities": + delete(request.Params.Meta, mcp.MetaKeyClientCapabilities) + case "URL only": + request.Params.Meta[mcp.MetaKeyClientCapabilities] = map[string]any{"elicitation": map[string]any{"url": map[string]any{}}} + case "no sealer": + deps.StateSealer = nil + } + req := &request + if name == "nil request" { + req = nil + } + _, result := confirmPullRequestArtifactDeletion(context.Background(), deps, req, input) + require.NotNil(t, result) + assert.True(t, result.IsError) + assert.Zero(t, calls) + }) + } +} diff --git a/pkg/github/pull_request_artifact_names_test.go b/pkg/github/pull_request_artifact_names_test.go new file mode 100644 index 0000000000..921025af49 --- /dev/null +++ b/pkg/github/pull_request_artifact_names_test.go @@ -0,0 +1,131 @@ +package github + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/url" + "testing" + + "github.com/github/github-mcp-server/v2/internal/requeststate" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPullRequestArtifactNameRoundTrip(t *testing.T) { + for _, names := range [][2]string{ + {"AT&T", "AT&T"}, + {"report", "report"}, + {"rep\u200bort", "report"}, + {"draft #1?% &", "draft #1?% &"}, + } { + t.Run(names[0], func(t *testing.T) { + bodies := map[string]string{names[0]: "original", names[1]: "do not change"} + var mutations []string + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/api/v3/repos/o/r" { + assert.Equal(t, http.MethodGet, r.Method) + _, _ = w.Write([]byte(`{"id":42}`)) + return + } + if r.Method == http.MethodGet { + assert.Equal(t, "/api/v3/repositories/42/pulls/12/artifacts", r.URL.Path) + artifacts := make([]map[string]any, 0, len(names)) + for i, name := range names { + artifacts = append(artifacts, map[string]any{ + "id": "opaque-id", "number": i + 1, "name": name, "body": bodies[name], + }) + } + require.NoError(t, json.NewEncoder(w).Encode(artifacts)) + return + } + assert.Equal(t, "/api/v3/repositories/42/pulls/12/artifacts/"+url.PathEscape(names[0]), r.URL.EscapedPath()) + assert.Empty(t, r.URL.RawQuery) + mutations = append(mutations, r.Method) + switch r.Method { + case http.MethodPut: + var payload struct { + Body string `json:"body"` + } + require.NoError(t, json.NewDecoder(r.Body).Decode(&payload)) + bodies[names[0]] = payload.Body + require.NoError(t, json.NewEncoder(w).Encode(map[string]any{ + "id": "opaque-id", "number": 1, "name": names[0], "body": payload.Body, + })) + case http.MethodDelete: + delete(bodies, names[0]) + w.WriteHeader(http.StatusNoContent) + default: + t.Errorf("unexpected method %s", r.Method) + } + }) + sealer, err := requeststate.NewRandom() + require.NoError(t, err) + deps := BaseDeps{Client: client, StateSealer: sealer} + target := fmt.Sprintf("o/r#12 artifact %q", names[0]) + session := pullRequestArtifactTestSession(t, deps, inventory.ProtocolVersionMultiRoundTrip, &mcp.ClientOptions{ + ElicitationHandler: func(_ context.Context, req *mcp.ElicitRequest) (*mcp.ElicitResult, error) { + assert.Contains(t, req.Params.Message, fmt.Sprintf("%q", target)) + return &mcp.ElicitResult{ + Action: "accept", + Content: map[string]any{ + deletePullRequestArtifactConfirmationField: target, + }, + }, nil + }, + }) + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{ + Name: "pull_request_artifact_read", + Arguments: map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": "list"}, + }) + require.NoError(t, err) + require.False(t, result.IsError, mustMarshalJSON(t, result)) + var listed PullRequestArtifactReadOutput + require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &listed)) + require.Len(t, listed.List.Artifacts, 2) + first, second := listed.List.Artifacts[0], listed.List.Artifacts[1] + assert.Equal(t, first.Name, second.Name, "distinct names collide after display sanitization") + assert.NotEqual(t, first.NameKey, second.NameKey) + assert.Equal(t, base64.RawURLEncoding.EncodeToString([]byte(names[0])), first.NameKey) + + updated, err := session.CallTool(context.Background(), &mcp.CallToolParams{ + Name: "pull_request_artifact_write", + Arguments: map[string]any{ + "owner": "o", "repo": "r", "pull_number": 12, + "method": "upsert", "name_key": first.NameKey, "body": "updated", + }, + }) + require.NoError(t, err) + require.False(t, updated.IsError, mustMarshalJSON(t, updated)) + var written PullRequestArtifactWriteOutput + require.NoError(t, json.Unmarshal([]byte(getTextResult(t, updated).Text), &written)) + require.NotNil(t, written.Artifact) + assert.Equal(t, first.NameKey, written.Artifact.NameKey) + assert.Equal(t, "updated", bodies[names[0]]) + assert.Equal(t, "do not change", bodies[names[1]]) + + deleted, err := session.CallTool(context.Background(), &mcp.CallToolParams{ + Name: "pull_request_artifact_write", + Arguments: map[string]any{ + "owner": "o", "repo": "r", "pull_number": 12, + "method": "delete", "name_key": written.Artifact.NameKey, + }, + }) + require.NoError(t, err) + require.False(t, deleted.IsError, mustMarshalJSON(t, deleted)) + var confirmation PullRequestArtifactWriteOutput + require.NoError(t, json.Unmarshal([]byte(getTextResult(t, deleted).Text), &confirmation)) + require.NotNil(t, confirmation.Deleted) + assert.Equal(t, first.NameKey, confirmation.Deleted.NameKey) + assert.Equal(t, first.Name, confirmation.Deleted.Name) + assert.NotContains(t, bodies, names[0]) + assert.Equal(t, "do not change", bodies[names[1]]) + assert.Equal(t, []string{http.MethodPut, http.MethodDelete}, mutations) + }) + } +} diff --git a/pkg/github/pull_request_artifact_types.go b/pkg/github/pull_request_artifact_types.go index ce0ceed318..b44a80dfdb 100644 --- a/pkg/github/pull_request_artifact_types.go +++ b/pkg/github/pull_request_artifact_types.go @@ -4,9 +4,10 @@ import "encoding/json" // PullRequestArtifact is an artifact or artifact version returned by the PR API. type PullRequestArtifact struct { - ID json.RawMessage `json:"id" jsonschema:"Opaque artifact ID; mutations use name instead"` + ID json.RawMessage `json:"id" jsonschema:"Opaque artifact ID; mutations use name or name_key instead"` Number int `json:"number"` - Name string `json:"name"` + Name string `json:"name" jsonschema:"Sanitized display name; use name_key when addressing this artifact"` + NameKey string `json:"name_key" jsonschema:"Lossless base64url-encoded artifact name; pass verbatim as name_key to write operations"` Body string `json:"body"` CommitOID *string `json:"commit_oid"` Creator *PullRequestArtifactCreator `json:"creator"` @@ -40,7 +41,8 @@ type PullRequestArtifactReadInput struct { type PullRequestArtifactWriteInput struct { PullRequestArtifactCoordinates Method string `json:"method" jsonschema:"Write operation: upsert or delete"` - Name string `json:"name" jsonschema:"Artifact name, not its number or global ID"` + Name string `json:"name,omitempty" jsonschema:"Exact artifact name for creation or addressing; mutually exclusive with name_key. Do not copy sanitized display names from read results"` + NameKey string `json:"name_key,omitempty" jsonschema:"Lossless addressing key returned by artifact reads or writes; mutually exclusive with name. Pass verbatim without decoding"` Body *string `json:"body,omitempty" jsonschema:"Required for upsert: artifact content; an empty string is sent unchanged. Not supported for delete"` CommitOID *string `json:"commit_oid,omitempty" jsonschema:"Optional commit OID for upsert only; omission preserves the API default"` } @@ -67,6 +69,7 @@ type PullRequestArtifactWriteOutput struct { // DeletePullRequestArtifactOutput confirms the named artifact that was deleted. type DeletePullRequestArtifactOutput struct { PullNumber int `json:"pull_number"` - Name string `json:"name"` + Name string `json:"name" jsonschema:"Sanitized display name of the deleted artifact"` + NameKey string `json:"name_key" jsonschema:"Lossless addressing key of the deleted artifact"` Message string `json:"message"` } diff --git a/pkg/github/pull_request_artifacts.go b/pkg/github/pull_request_artifacts.go index 2904c57693..c1ac1feabf 100644 --- a/pkg/github/pull_request_artifacts.go +++ b/pkg/github/pull_request_artifacts.go @@ -2,6 +2,7 @@ package github import ( "context" + "encoding/base64" "encoding/json" "fmt" "net/http" @@ -10,6 +11,8 @@ import ( "slices" "strconv" "strings" + "time" + "unicode/utf8" ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" "github.com/github/github-mcp-server/v2/pkg/ifc" @@ -23,6 +26,20 @@ import ( "github.com/modelcontextprotocol/go-sdk/mcp" ) +const ( + deletePullRequestArtifactConfirmationID = "delete_pull_request_artifact_confirmation" + deletePullRequestArtifactConfirmationField = "artifact_target" + deletePullRequestArtifactConfirmationTTL = 10 * time.Minute +) + +type deletePullRequestArtifactState struct { + PullRequestArtifactCoordinates + Operation string `json:"operation"` + Name string `json:"name"` + RepositoryID int64 `json:"repository_id"` + ExpiresAt int64 `json:"expires_at"` +} + func newPullRequestArtifactTool[In, Out any](t translations.TranslationHelperFunc, name, title, description string, readOnly bool, methods []string, handler func(context.Context, ToolDependencies, *mcp.CallToolRequest, In) (*mcp.CallToolResult, Out, error), ) inventory.ServerTool { @@ -34,7 +51,7 @@ func newPullRequestArtifactTool[In, Out any](t translations.TranslationHelperFun property.Minimum = new(1.0) } } - for _, field := range []string{"owner", "repo", "name"} { + for _, field := range []string{"owner", "repo", "name", "name_key"} { if property := schema.Properties[field]; property != nil { property.MinLength = new(1) } @@ -67,7 +84,7 @@ func newPullRequestArtifactTool[In, Out any](t translations.TranslationHelperFun // PullRequestArtifactRead lists pull request artifact versions, including bodies. func PullRequestArtifactRead(t translations.TranslationHelperFunc) inventory.ServerTool { return newPullRequestArtifactTool(t, "pull_request_artifact_read", "Read pull request artifacts", - "List GitHub pull request artifact versions including their bodies. commit_oid defaults to the current PR head; use all or an explicit commit OID to change the selection. Returns one page; request next_page when present. Repository access and the repository's pull_request_artifacts_api rollout are enforced by GitHub. Unavailable in lockdown mode.", + "List GitHub pull request artifact versions including their bodies. Names are sanitized for display; use the returned name_key, not name, for subsequent writes. commit_oid defaults to the current PR head; use all or an explicit commit OID to change the selection. Returns one page; request next_page when present. Repository access and the repository's pull_request_artifacts_api rollout are enforced by GitHub. Unavailable in lockdown mode.", true, []string{"list"}, func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input PullRequestArtifactReadInput) (*mcp.CallToolResult, *PullRequestArtifactReadOutput, error) { if input.Method != "list" { @@ -87,7 +104,7 @@ func PullRequestArtifactRead(t translations.TranslationHelperFunc) inventory.Ser query.Set("commit_oid", input.CommitOID) } var artifacts []PullRequestArtifact - response, repository, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, "", http.MethodGet, query, nil, &artifacts, http.StatusOK) + response, repository, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, "", http.MethodGet, query, nil, &artifacts, 0, http.StatusOK) if failure != nil { return failure, nil, nil } @@ -110,9 +127,19 @@ func PullRequestArtifactRead(t translations.TranslationHelperFunc) inventory.Ser // PullRequestArtifactWrite upserts or deletes a pull request artifact by name. func PullRequestArtifactWrite(t translations.TranslationHelperFunc) inventory.ServerTool { return newPullRequestArtifactTool(t, "pull_request_artifact_write", "Write pull request artifacts", - "Upsert or delete a GitHub pull request artifact by name, not its number or global ID. Upsert requires body and optionally accepts commit_oid; creates a new artifact or replaces the named artifact's content. Delete does not accept body or commit_oid. Writes are not automatically retried. Repository access and the repository's pull_request_artifacts_api rollout are enforced by GitHub. Unavailable in lockdown mode.", + "Upsert or delete a GitHub pull request artifact using exactly one of name (the exact original name) or name_key (the lossless key returned by reads or writes), not its number or global ID. Never use a sanitized display name to address an existing artifact. Upsert requires body and optionally accepts commit_oid; creates a new artifact or replaces the named artifact's content. Delete requires explicit user confirmation through form elicitation with MCP protocol 2026-07-28 or later, and does not accept body or commit_oid. Writes are not automatically retried. Repository access and the repository's pull_request_artifacts_api rollout are enforced by GitHub. Unavailable in lockdown mode.", false, []string{"upsert", "delete"}, - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input PullRequestArtifactWriteInput) (*mcp.CallToolResult, *PullRequestArtifactWriteOutput, error) { + func(ctx context.Context, deps ToolDependencies, req *mcp.CallToolRequest, input PullRequestArtifactWriteInput) (*mcp.CallToolResult, *PullRequestArtifactWriteOutput, error) { + if input.NameKey != "" { + if input.Name != "" { + return utils.NewToolResultError("provide exactly one of name or name_key"), nil, nil + } + name, err := base64.RawURLEncoding.DecodeString(input.NameKey) + if err != nil || !utf8.Valid(name) || base64.RawURLEncoding.EncodeToString(name) != input.NameKey { + return utils.NewToolResultError("name_key must be a valid lossless key returned by artifact reads or writes"), nil, nil + } + input.Name = string(name) + } if strings.TrimSpace(input.Name) == "" || input.Name == "." || input.Name == ".." || strings.ContainsAny(input.Name, "/\\") { return utils.NewToolResultError("name must be a nonempty artifact path segment"), nil, nil } @@ -126,7 +153,7 @@ func PullRequestArtifactWrite(t translations.TranslationHelperFunc) inventory.Se CommitOID *string `json:"commit_oid,omitempty"` }{*input.Body, input.CommitOID} var artifact PullRequestArtifact - _, repository, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, input.Name, http.MethodPut, nil, body, &artifact, http.StatusOK, http.StatusCreated) + _, repository, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, input.Name, http.MethodPut, nil, body, &artifact, 0, http.StatusOK, http.StatusCreated) if failure != nil { return failure, nil, nil } @@ -143,11 +170,16 @@ func PullRequestArtifactWrite(t translations.TranslationHelperFunc) inventory.Se if input.Body != nil || input.CommitOID != nil { return utils.NewToolResultError("body and commit_oid are not supported for delete"), nil, nil } - if _, _, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, input.Name, http.MethodDelete, nil, nil, nil, http.StatusNoContent); failure != nil { + repositoryID, confirmation := confirmPullRequestArtifactDeletion(ctx, deps, req, input) + if confirmation != nil { + return confirmation, nil, nil + } + if _, _, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, input.Name, http.MethodDelete, nil, nil, nil, repositoryID, http.StatusNoContent); failure != nil { return failure, nil, nil } output := &PullRequestArtifactWriteOutput{Deleted: &DeletePullRequestArtifactOutput{ - PullNumber: input.PullNumber, Name: sanitize.PlainText(input.Name), Message: "artifact deleted", + PullNumber: input.PullNumber, Name: sanitize.PlainText(input.Name), + NameKey: base64.RawURLEncoding.EncodeToString([]byte(input.Name)), Message: "artifact deleted", }} return MarshalledTextResult(output), output, nil default: @@ -156,17 +188,103 @@ func PullRequestArtifactWrite(t translations.TranslationHelperFunc) inventory.Se }) } -func pullRequestArtifactRequest(ctx context.Context, deps ToolDependencies, coordinates PullRequestArtifactCoordinates, name, method string, query url.Values, body, output any, statuses ...int) (*gogithub.Response, *gogithub.Repository, *mcp.CallToolResult) { +func confirmPullRequestArtifactDeletion(ctx context.Context, deps ToolDependencies, req *mcp.CallToolRequest, input PullRequestArtifactWriteInput) (int64, *mcp.CallToolResult) { + if failure := validatePullRequestArtifactCoordinates(ctx, deps, input.PullRequestArtifactCoordinates); failure != nil { + return 0, failure + } + if req == nil || req.Params == nil || req.ProtocolVersion() < inventory.ProtocolVersionMultiRoundTrip { + return 0, utils.NewToolResultError("Artifact deletion requires MCP protocol version 2026-07-28 or later and form elicitation.") + } + capabilities := req.ClientCapabilities() + if capabilities == nil || capabilities.Elicitation == nil || (capabilities.Elicitation.Form == nil && capabilities.Elicitation.URL != nil) { + return 0, utils.NewToolResultError("Artifact deletion requires client support for form elicitation.") + } + sealer := requestStateSealerFromDeps(deps) + if sealer == nil { + return 0, utils.NewToolResultError("Artifact deletion is unavailable because request-state protection is not configured.") + } + target := fmt.Sprintf("%s/%s#%d artifact %q", input.Owner, input.Repo, input.PullNumber, input.Name) + response, ok := req.Params.InputResponses[deletePullRequestArtifactConfirmationID] + if !ok { + _, repository, failure := resolvePullRequestArtifactRepository(ctx, deps, input.PullRequestArtifactCoordinates) + if failure != nil { + return 0, failure + } + state, err := json.Marshal(deletePullRequestArtifactState{ + PullRequestArtifactCoordinates: input.PullRequestArtifactCoordinates, + Operation: "pull_request_artifact_write:delete", + Name: input.Name, RepositoryID: repository.GetID(), + ExpiresAt: time.Now().Add(deletePullRequestArtifactConfirmationTTL).Unix(), + }) + if err != nil { + return 0, utils.NewToolResultErrorFromErr("failed to marshal artifact deletion state", err) + } + requestState, err := sealer.Seal(ctx, state) + if err != nil { + return 0, utils.NewToolResultErrorFromErr("failed to seal artifact deletion state", err) + } + return 0, &mcp.CallToolResult{ + InputRequests: mcp.InputRequestMap{ + deletePullRequestArtifactConfirmationID: &mcp.ElicitParams{ + Mode: "form", + Message: fmt.Sprintf("Type %q to confirm deletion of this pull request artifact.", target), + RequestedSchema: &jsonschema.Schema{ + Type: "object", + Properties: map[string]*jsonschema.Schema{ + deletePullRequestArtifactConfirmationField: { + Type: "string", Title: "Artifact target", + Description: fmt.Sprintf("Enter %s exactly to confirm deletion", target), + }, + }, + Required: []string{deletePullRequestArtifactConfirmationField}, + }, + }, + }, + RequestState: requestState, + } + } + stateJSON, err := sealer.Open(req.Params.RequestState) + if err != nil { + return 0, utils.NewToolResultError("Artifact deletion confirmation state was missing or invalid. The artifact was not deleted.") + } + var state deletePullRequestArtifactState + if err := json.Unmarshal(stateJSON, &state); err != nil { + return 0, utils.NewToolResultError("Artifact deletion confirmation state was invalid. The artifact was not deleted.") + } + if state.Operation != "pull_request_artifact_write:delete" || state.PullRequestArtifactCoordinates != input.PullRequestArtifactCoordinates || state.Name != input.Name || state.RepositoryID <= 0 { + return 0, utils.NewToolResultError("Artifact deletion target changed or confirmation state was invalid. The artifact was not deleted.") + } + if state.ExpiresAt <= time.Now().Unix() { + return 0, utils.NewToolResultError("Artifact deletion confirmation expired. The artifact was not deleted.") + } + confirmation, ok := response.(*mcp.ElicitResult) + if !ok || confirmation == nil || confirmation.Action != "accept" { + return 0, utils.NewToolResultError("Artifact deletion was not confirmed. The artifact was not deleted.") + } + if confirmedTarget, ok := confirmation.Content[deletePullRequestArtifactConfirmationField].(string); !ok || confirmedTarget != target { + return 0, utils.NewToolResultError("Artifact target confirmation did not match. The artifact was not deleted.") + } + return state.RepositoryID, nil +} + +func validatePullRequestArtifactCoordinates(ctx context.Context, deps ToolDependencies, coordinates PullRequestArtifactCoordinates) *mcp.CallToolResult { for _, segment := range []string{coordinates.Owner, coordinates.Repo} { if strings.TrimSpace(segment) == "" || segment == "." || segment == ".." || strings.ContainsAny(segment, "/\\") { - return nil, nil, utils.NewToolResultError("owner and repo must be nonempty repository path segments") + return utils.NewToolResultError("owner and repo must be nonempty repository path segments") } } if coordinates.PullNumber <= 0 { - return nil, nil, utils.NewToolResultError("pull_number must be positive") + return utils.NewToolResultError("pull_number must be positive") } if deps.GetFlags(ctx).LockdownMode { - return nil, nil, utils.NewToolResultError("pull request artifacts are unavailable in lockdown mode") + return utils.NewToolResultError("pull request artifacts are unavailable in lockdown mode") + } + return nil +} + +func resolvePullRequestArtifactRepository(ctx context.Context, deps ToolDependencies, coordinates PullRequestArtifactCoordinates) (*gogithub.Client, *gogithub.Repository, *mcp.CallToolResult) { + if failure := validatePullRequestArtifactCoordinates(ctx, deps, coordinates); failure != nil { + return nil, nil, failure } client, err := deps.GetClient(ctx) if err != nil { @@ -182,6 +300,17 @@ func pullRequestArtifactRequest(ctx context.Context, deps ToolDependencies, coor if repository == nil || repository.GetID() <= 0 { return nil, nil, utils.NewToolResultError("repository response omitted a positive repository ID") } + return client, repository, nil +} + +func pullRequestArtifactRequest(ctx context.Context, deps ToolDependencies, coordinates PullRequestArtifactCoordinates, name, method string, query url.Values, body, output any, expectedRepositoryID int64, statuses ...int) (*gogithub.Response, *gogithub.Repository, *mcp.CallToolResult) { + client, repository, failure := resolvePullRequestArtifactRepository(ctx, deps, coordinates) + if failure != nil { + return nil, nil, failure + } + if expectedRepositoryID != 0 && repository.GetID() != expectedRepositoryID { + return nil, nil, utils.NewToolResultError("Repository identity changed after artifact deletion confirmation was requested. The artifact was not deleted.") + } path := fmt.Sprintf("repositories/%d/pulls/%d/artifacts", repository.GetID(), coordinates.PullNumber) if name != "" { path += "/" + url.PathEscape(name) @@ -230,6 +359,7 @@ func validatePullRequestArtifact(artifact *PullRequestArtifact) error { } func sanitizePullRequestArtifact(artifact *PullRequestArtifact) { + artifact.NameKey = base64.RawURLEncoding.EncodeToString([]byte(artifact.Name)) artifact.Name = sanitize.PlainText(artifact.Name) artifact.Body = sanitize.Content(artifact.Body) if artifact.Creator != nil { diff --git a/pkg/github/pull_request_artifacts_test.go b/pkg/github/pull_request_artifacts_test.go index d138570b6c..e62f5da3d1 100644 --- a/pkg/github/pull_request_artifacts_test.go +++ b/pkg/github/pull_request_artifacts_test.go @@ -46,7 +46,7 @@ func pullRequestArtifactTestClient(t *testing.T, handler http.HandlerFunc) *gogi return client } -func pullRequestArtifactTestSession(t *testing.T, deps BaseDeps, protocol string) *mcp.ClientSession { +func pullRequestArtifactTestSession(t *testing.T, deps BaseDeps, protocol string, options ...*mcp.ClientOptions) *mcp.ClientSession { t.Helper() inv, err := inventory.NewBuilder().SetTools(pullRequestArtifactTestTools()). WithFeatureChecker(featureCheckerFor(FeatureFlagPullRequestArtifacts)).Build() @@ -54,6 +54,18 @@ func pullRequestArtifactTestSession(t *testing.T, deps BaseDeps, protocol string server := mcp.NewServer(&mcp.Implementation{Name: "pull-request-artifacts", Version: "v1"}, nil) server.AddReceivingMiddleware(InjectDepsMiddleware(deps)) inv.RegisterTools(context.Background(), server, deps) + if len(options) > 0 { + serverTransport, clientTransport := mcp.NewInMemoryTransports() + serverSession, err := server.Connect(context.Background(), serverTransport, nil) + require.NoError(t, err) + t.Cleanup(func() { _ = serverSession.Close() }) + client := mcp.NewClient(&mcp.Implementation{Name: "artifact-approval-test", Version: "v1"}, options[0]) + session, err := client.Connect(context.Background(), commentVisibilityProtocolTransport{clientTransport, protocol}, nil) + require.NoError(t, err) + t.Cleanup(func() { _ = session.Close() }) + require.Equal(t, protocol, session.InitializeResult().ProtocolVersion) + return session + } return connectCommentVisibilityClient(t, server, protocol) } @@ -74,9 +86,6 @@ func TestPullRequestArtifactTools(t *testing.T) { assert.Equal(t, !readOnly, *tool.Tool.Annotations.DestructiveHint) schema := tool.Tool.InputSchema.(*jsonschema.Schema) required := []string{"owner", "repo", "pull_number", "method"} - if !readOnly { - required = append(required, "name") - } assert.ElementsMatch(t, required, schema.Required) } for _, tc := range []struct { @@ -129,7 +138,7 @@ func TestPullRequestArtifactRequests(t *testing.T) { }{ {name: "upsert create empty body", method: "upsert", verb: "PUT", args: map[string]any{"name": "report", "body": ""}, body: `{"body":""}`, status: 201, response: artifact}, {name: "upsert update with commit", method: "upsert", verb: "PUT", args: map[string]any{"name": "report", "body": "new", "commit_oid": "abc123"}, body: `{"body":"new","commit_oid":"abc123"}`, status: 200, response: artifact}, - {name: "delete", method: "delete", verb: "DELETE", args: map[string]any{"name": "report"}, status: 204}, + {name: "upsert with lossless key", method: "upsert", verb: "PUT", args: map[string]any{"name_key": "cmVwb3J0", "body": "new"}, body: `{"body":"new"}`, status: 200, response: artifact}, {name: "list default", method: "list", verb: "GET", query: "page=1&per_page=30", status: 200, response: "[" + artifact + "]"}, {name: "list current", method: "list", verb: "GET", args: map[string]any{"commit_oid": "current"}, query: "commit_oid=current&page=1&per_page=30", status: 200, response: "[" + artifact + "]"}, {name: "list all", method: "list", verb: "GET", args: map[string]any{"commit_oid": "all"}, query: "commit_oid=all&page=1&per_page=30", status: 200, response: "[" + artifact + "]"}, @@ -143,7 +152,7 @@ func TestPullRequestArtifactRequests(t *testing.T) { client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { calls++ w.Header().Set("Content-Type", "application/json") - if calls == 1 { + if r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/repos/") { assert.Equal(t, http.MethodGet, r.Method) assert.Equal(t, "/api/v3/repos/o/r", r.URL.Path) _, _ = w.Write([]byte(`{"id":42,"private":true}`)) @@ -182,12 +191,7 @@ func TestPullRequestArtifactRequests(t *testing.T) { } else { assert.Nil(t, result.StructuredContent) } - if tc.method == "delete" { - assert.JSONEq(t, `{"deleted":{"pull_number":12,"name":"report","message":"artifact deleted"}}`, text) - assert.NotContains(t, result.Meta, "ifc") - } else { - assert.JSONEq(t, mustMarshalJSON(t, ifc.PrivateTrusted()), mustMarshalJSON(t, result.Meta["ifc"])) - } + assert.JSONEq(t, mustMarshalJSON(t, ifc.PrivateTrusted()), mustMarshalJSON(t, result.Meta["ifc"])) switch tc.method { case "list": var output PullRequestArtifactReadOutput @@ -204,7 +208,8 @@ func TestPullRequestArtifactRequests(t *testing.T) { assert.Equal(t, 1, output.List.PerPage) } case "upsert": - assert.JSONEq(t, `{"artifact":`+artifact+`}`, text) + expected := strings.Replace(artifact, `"name":"report"`, `"name":"report","name_key":"cmVwb3J0"`, 1) + assert.JSONEq(t, `{"artifact":`+expected+`}`, text) } }) } @@ -218,7 +223,7 @@ func TestPullRequestArtifactEscapedNames(t *testing.T) { calls := 0 client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { calls++ - if calls == 1 { + if r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/repos/") { _, _ = w.Write([]byte(`{"id":42}`)) return } @@ -235,12 +240,13 @@ func TestPullRequestArtifactEscapedNames(t *testing.T) { args["body"] = "" } deps := BaseDeps{Client: client} - tool := pullRequestArtifactTestTool(method) - request := createMCPRequest(args) - result, err := tool.Handler(deps)(ContextWithDeps(context.Background(), deps), &request) - require.NoError(t, err) + result := invokePullRequestArtifactWithApproval(context.Background(), t, deps, args) require.False(t, result.IsError, mustMarshalJSON(t, result)) - assert.Equal(t, 2, calls) + expectedCalls := 2 + if method == "delete" { + expectedCalls++ + } + assert.Equal(t, expectedCalls, calls) if method == "upsert" { assert.Contains(t, getTextResult(t, result).Text, `"id":9007199254740993`) } @@ -285,6 +291,12 @@ func TestPullRequestArtifactInvalidInputs(t *testing.T) { {"backslash name", "delete", map[string]any{"name": `a\b`}}, {"delete body", "delete", map[string]any{"body": ""}}, {"delete commit", "delete", map[string]any{"commit_oid": "abc"}}, + {"both name and key", "upsert", map[string]any{"name_key": "cmVwb3J0", "body": ""}}, + {"invalid key", "upsert", map[string]any{"name": "", "name_key": "%", "body": ""}}, + {"noncanonical key", "upsert", map[string]any{"name": "", "name_key": "cmVwb3J0\n", "body": ""}}, + {"invalid UTF-8 key", "upsert", map[string]any{"name": "", "name_key": "_w", "body": ""}}, + {"slash key", "upsert", map[string]any{"name": "", "name_key": "YS9i", "body": ""}}, + {"traversal key", "delete", map[string]any{"name": "", "name_key": "Li4"}}, {"negative pull", "list", map[string]any{"pull_number": -1}}, {"missing pull", "list", map[string]any{"pull_number": 0}}, {"empty owner", "list", map[string]any{"owner": " "}}, @@ -349,10 +361,10 @@ func TestPullRequestArtifactFailures(t *testing.T) { for _, status := range []int{400, 401, 403, 404, 409, 422, 429, 500, 503} { t.Run(method+"/"+http.StatusText(status), func(t *testing.T) { calls := 0 - client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { calls++ w.Header().Set("Content-Type", "application/json") - if calls == 1 { + if r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/repos/") { _, _ = w.Write([]byte(`{"id":42}`)) return } @@ -363,7 +375,6 @@ func TestPullRequestArtifactFailures(t *testing.T) { _, _ = w.Write([]byte(`{"message":"artifact access failed"}`)) }) deps := BaseDeps{Client: client} - tool := pullRequestArtifactTestTool(method) args := map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": method} if method != "list" { args["name"] = "report" @@ -371,15 +382,17 @@ func TestPullRequestArtifactFailures(t *testing.T) { if method == "upsert" { args["body"] = "" } - request := createMCPRequest(args) - result, err := tool.Handler(deps)(ContextWithDeps(context.Background(), deps), &request) - require.NoError(t, err) + result := invokePullRequestArtifactWithApproval(context.Background(), t, deps, args) require.True(t, result.IsError) assert.Contains(t, getTextResult(t, result).Text, "artifact") if status == http.StatusTooManyRequests { assert.Contains(t, getTextResult(t, result).Text, "Retry after") } - assert.Equal(t, 2, calls, "errors must not cause retries or fallback requests") + expectedCalls := 2 + if method == "delete" { + expectedCalls++ + } + assert.Equal(t, expectedCalls, calls, "errors must not cause retries or fallback requests") }) } } @@ -444,7 +457,6 @@ func TestPullRequestArtifactRepositoryGate(t *testing.T) { }) deps := BaseDeps{Client: client} ctx := inventory.WithFeatureState(ContextWithDeps(context.Background(), deps), featureCheckerFor(FeatureFlagPullRequestArtifacts)) - tool := pullRequestArtifactTestTool(method) for _, repo := range []string{"enabled", "disabled", "enabled"} { args := map[string]any{"owner": "o", "repo": repo, "pull_number": 12, "method": method} if method != "list" { @@ -453,12 +465,14 @@ func TestPullRequestArtifactRepositoryGate(t *testing.T) { if method == "upsert" { args["body"] = "" } - request := createMCPRequest(args) - result, err := tool.Handler(deps)(ctx, &request) - require.NoError(t, err) + result := invokePullRequestArtifactWithApproval(ctx, t, deps, args) assert.Equal(t, repo == "disabled", result.IsError, mustMarshalJSON(t, result)) } - assert.Equal(t, 6, calls) + expectedCalls := 6 + if method == "delete" { + expectedCalls = 9 + } + assert.Equal(t, expectedCalls, calls) }) } } @@ -478,9 +492,9 @@ func TestPullRequestArtifactResponseValidation(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { calls := 0 - client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, _ *http.Request) { + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { calls++ - if calls == 1 { + if r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/repos/") { _, _ = w.Write([]byte(`{"id":42}`)) return } @@ -488,7 +502,6 @@ func TestPullRequestArtifactResponseValidation(t *testing.T) { _, _ = w.Write([]byte(tc.response)) }) deps := BaseDeps{Client: client} - tool := pullRequestArtifactTestTool(tc.method) args := map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": tc.method} if tc.method != "list" { args["name"] = "report" @@ -496,11 +509,13 @@ func TestPullRequestArtifactResponseValidation(t *testing.T) { if tc.method == "upsert" { args["body"] = "" } - request := createMCPRequest(args) - result, err := tool.Handler(deps)(ContextWithDeps(context.Background(), deps), &request) - require.NoError(t, err) + result := invokePullRequestArtifactWithApproval(context.Background(), t, deps, args) require.True(t, result.IsError) - assert.Equal(t, 2, calls) + expectedCalls := 2 + if tc.method == "delete" { + expectedCalls++ + } + assert.Equal(t, expectedCalls, calls) }) } } From d1e0e1bdc4057516702c6234a8c6593d8445a73d Mon Sep 17 00:00:00 2001 From: Tracy Lum <11878752+talum@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:23:03 +0000 Subject: [PATCH 3/5] Avoid assigning trust labels to pull request artifacts Remove repository-visibility-based IFC labeling from artifact results while preserving their content. Assert that public and private artifact outputs remain unlabeled. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: bdcada73-447e-43ff-8f05-84c14cb03336 --- pkg/github/pull_request_artifacts.go | 17 ++++------------- pkg/github/pull_request_artifacts_test.go | 5 ++--- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/pkg/github/pull_request_artifacts.go b/pkg/github/pull_request_artifacts.go index c1ac1feabf..094d604fd4 100644 --- a/pkg/github/pull_request_artifacts.go +++ b/pkg/github/pull_request_artifacts.go @@ -15,7 +15,6 @@ import ( "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/sanitize" "github.com/github/github-mcp-server/v2/pkg/scopes" @@ -104,7 +103,7 @@ func PullRequestArtifactRead(t translations.TranslationHelperFunc) inventory.Ser query.Set("commit_oid", input.CommitOID) } var artifacts []PullRequestArtifact - response, repository, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, "", http.MethodGet, query, nil, &artifacts, 0, http.StatusOK) + response, _, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, "", http.MethodGet, query, nil, &artifacts, 0, http.StatusOK) if failure != nil { return failure, nil, nil } @@ -120,7 +119,7 @@ func PullRequestArtifactRead(t translations.TranslationHelperFunc) inventory.Ser output := &PullRequestArtifactReadOutput{List: &ListPullRequestArtifactsOutput{ Artifacts: artifacts, Page: input.Page, PerPage: input.PerPage, NextPage: response.NextPage, }} - return pullRequestArtifactResult(ctx, deps, repository, output), output, nil + return MarshalledTextResult(output), output, nil }) } @@ -153,7 +152,7 @@ func PullRequestArtifactWrite(t translations.TranslationHelperFunc) inventory.Se CommitOID *string `json:"commit_oid,omitempty"` }{*input.Body, input.CommitOID} var artifact PullRequestArtifact - _, repository, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, input.Name, http.MethodPut, nil, body, &artifact, 0, http.StatusOK, http.StatusCreated) + _, _, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, input.Name, http.MethodPut, nil, body, &artifact, 0, http.StatusOK, http.StatusCreated) if failure != nil { return failure, nil, nil } @@ -165,7 +164,7 @@ func PullRequestArtifactWrite(t translations.TranslationHelperFunc) inventory.Se } sanitizePullRequestArtifact(&artifact) output := &PullRequestArtifactWriteOutput{Artifact: &artifact} - return pullRequestArtifactResult(ctx, deps, repository, output), output, nil + return MarshalledTextResult(output), output, nil case "delete": if input.Body != nil || input.CommitOID != nil { return utils.NewToolResultError("body and commit_oid are not supported for delete"), nil, nil @@ -366,11 +365,3 @@ func sanitizePullRequestArtifact(artifact *PullRequestArtifact) { artifact.Creator.Login = sanitize.PlainText(artifact.Creator.Login) } } - -func pullRequestArtifactResult(ctx context.Context, deps ToolDependencies, repository *gogithub.Repository, output any) *mcp.CallToolResult { - result := MarshalledTextResult(output) - if shouldAttachIFCLabel(ctx, deps, result) && repository.Private != nil { - setIFCLabel(result, ifc.LabelRepoUserContent(*repository.Private)) - } - return result -} diff --git a/pkg/github/pull_request_artifacts_test.go b/pkg/github/pull_request_artifacts_test.go index e62f5da3d1..4c032a2373 100644 --- a/pkg/github/pull_request_artifacts_test.go +++ b/pkg/github/pull_request_artifacts_test.go @@ -12,7 +12,6 @@ import ( "testing" "github.com/github/github-mcp-server/v2/internal/toolsnaps" - "github.com/github/github-mcp-server/v2/pkg/ifc" "github.com/github/github-mcp-server/v2/pkg/inventory" "github.com/github/github-mcp-server/v2/pkg/translations" gogithub "github.com/google/go-github/v92/github" @@ -191,7 +190,7 @@ func TestPullRequestArtifactRequests(t *testing.T) { } else { assert.Nil(t, result.StructuredContent) } - assert.JSONEq(t, mustMarshalJSON(t, ifc.PrivateTrusted()), mustMarshalJSON(t, result.Meta["ifc"])) + assert.NotContains(t, result.Meta, "ifc") switch tc.method { case "list": var output PullRequestArtifactReadOutput @@ -549,6 +548,6 @@ func TestPullRequestArtifactSanitization(t *testing.T) { assert.Equal(t, "abc123", *artifact.CommitOID) assert.Equal(t, "2026-11-13T00:00:00Z", *artifact.CreatedAt) assert.Equal(t, "2026-11-13T00:00:00Z", *artifact.UpdatedAt) - assert.JSONEq(t, mustMarshalJSON(t, ifc.PublicUntrusted()), mustMarshalJSON(t, result.Meta["ifc"])) + assert.NotContains(t, result.Meta, "ifc") assert.Equal(t, 2, calls) } From f0e30a39464724b4eba692062641f04468e38d7f Mon Sep 17 00:00:00 2001 From: Tracy Lum <11878752+talum@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:15:01 +0000 Subject: [PATCH 4/5] Preserve PR artifact confidentiality without trusting content Label artifact read and upsert results as untrusted with repository confidentiality when IFC labels are enabled. Reuse the repository lookup and conservatively treat unknown visibility as private. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: bdcada73-447e-43ff-8f05-84c14cb03336 --- pkg/github/pull_request_artifacts.go | 17 +++++-- pkg/github/pull_request_artifacts_test.go | 58 ++++++++++++++++++++++- 2 files changed, 69 insertions(+), 6 deletions(-) diff --git a/pkg/github/pull_request_artifacts.go b/pkg/github/pull_request_artifacts.go index 094d604fd4..3316567d4d 100644 --- a/pkg/github/pull_request_artifacts.go +++ b/pkg/github/pull_request_artifacts.go @@ -15,6 +15,7 @@ import ( "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/sanitize" "github.com/github/github-mcp-server/v2/pkg/scopes" @@ -103,7 +104,7 @@ func PullRequestArtifactRead(t translations.TranslationHelperFunc) inventory.Ser query.Set("commit_oid", input.CommitOID) } var artifacts []PullRequestArtifact - response, _, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, "", http.MethodGet, query, nil, &artifacts, 0, http.StatusOK) + response, repository, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, "", http.MethodGet, query, nil, &artifacts, 0, http.StatusOK) if failure != nil { return failure, nil, nil } @@ -119,7 +120,7 @@ func PullRequestArtifactRead(t translations.TranslationHelperFunc) inventory.Ser output := &PullRequestArtifactReadOutput{List: &ListPullRequestArtifactsOutput{ Artifacts: artifacts, Page: input.Page, PerPage: input.PerPage, NextPage: response.NextPage, }} - return MarshalledTextResult(output), output, nil + return pullRequestArtifactResult(ctx, deps, repository, output), output, nil }) } @@ -152,7 +153,7 @@ func PullRequestArtifactWrite(t translations.TranslationHelperFunc) inventory.Se CommitOID *string `json:"commit_oid,omitempty"` }{*input.Body, input.CommitOID} var artifact PullRequestArtifact - _, _, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, input.Name, http.MethodPut, nil, body, &artifact, 0, http.StatusOK, http.StatusCreated) + _, repository, failure := pullRequestArtifactRequest(ctx, deps, input.PullRequestArtifactCoordinates, input.Name, http.MethodPut, nil, body, &artifact, 0, http.StatusOK, http.StatusCreated) if failure != nil { return failure, nil, nil } @@ -164,7 +165,7 @@ func PullRequestArtifactWrite(t translations.TranslationHelperFunc) inventory.Se } sanitizePullRequestArtifact(&artifact) output := &PullRequestArtifactWriteOutput{Artifact: &artifact} - return MarshalledTextResult(output), output, nil + return pullRequestArtifactResult(ctx, deps, repository, output), output, nil case "delete": if input.Body != nil || input.CommitOID != nil { return utils.NewToolResultError("body and commit_oid are not supported for delete"), nil, nil @@ -365,3 +366,11 @@ func sanitizePullRequestArtifact(artifact *PullRequestArtifact) { artifact.Creator.Login = sanitize.PlainText(artifact.Creator.Login) } } + +func pullRequestArtifactResult(ctx context.Context, deps ToolDependencies, repository *gogithub.Repository, output any) *mcp.CallToolResult { + label := ifc.PrivateUntrusted() + if repository.Private != nil && !*repository.Private { + label = ifc.PublicUntrusted() + } + return attachStaticIFCLabel(ctx, deps, MarshalledTextResult(output), label) +} diff --git a/pkg/github/pull_request_artifacts_test.go b/pkg/github/pull_request_artifacts_test.go index 4c032a2373..7be7fbfa34 100644 --- a/pkg/github/pull_request_artifacts_test.go +++ b/pkg/github/pull_request_artifacts_test.go @@ -12,6 +12,7 @@ import ( "testing" "github.com/github/github-mcp-server/v2/internal/toolsnaps" + "github.com/github/github-mcp-server/v2/pkg/ifc" "github.com/github/github-mcp-server/v2/pkg/inventory" "github.com/github/github-mcp-server/v2/pkg/translations" gogithub "github.com/google/go-github/v92/github" @@ -190,7 +191,7 @@ func TestPullRequestArtifactRequests(t *testing.T) { } else { assert.Nil(t, result.StructuredContent) } - assert.NotContains(t, result.Meta, "ifc") + assert.JSONEq(t, mustMarshalJSON(t, ifc.PrivateUntrusted()), mustMarshalJSON(t, result.Meta["ifc"])) switch tc.method { case "list": var output PullRequestArtifactReadOutput @@ -548,6 +549,59 @@ func TestPullRequestArtifactSanitization(t *testing.T) { assert.Equal(t, "abc123", *artifact.CommitOID) assert.Equal(t, "2026-11-13T00:00:00Z", *artifact.CreatedAt) assert.Equal(t, "2026-11-13T00:00:00Z", *artifact.UpdatedAt) - assert.NotContains(t, result.Meta, "ifc") + assert.JSONEq(t, mustMarshalJSON(t, ifc.PublicUntrusted()), mustMarshalJSON(t, result.Meta["ifc"])) assert.Equal(t, 2, calls) } + +func TestPullRequestArtifactIFCLabels(t *testing.T) { + for _, method := range []string{"list", "upsert"} { + for _, visibility := range []struct { + name, repository string + label ifc.SecurityLabel + }{ + {"public", `{"id":42,"private":false}`, ifc.PublicUntrusted()}, + {"private", `{"id":42,"private":true}`, ifc.PrivateUntrusted()}, + {"unknown visibility", `{"id":42}`, ifc.PrivateUntrusted()}, + } { + for _, enabled := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%s/enabled=%t", method, visibility.name, enabled), func(t *testing.T) { + calls := 0 + client := pullRequestArtifactTestClient(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/api/v3/repos/o/r" { + _, _ = w.Write([]byte(visibility.repository)) + return + } + artifact := `{"id":1,"number":1,"name":"report","body":"artifact content"}` + if method == "list" { + artifact = "[" + artifact + "]" + } + _, _ = w.Write([]byte(artifact)) + }) + deps := BaseDeps{Client: client} + if enabled { + deps.featureChecker = featureCheckerFor(FeatureFlagIFCLabels) + } + session := pullRequestArtifactTestSession(t, deps, inventory.ProtocolVersionMultiRoundTrip) + args := map[string]any{"owner": "o", "repo": "r", "pull_number": 12, "method": method} + if method == "upsert" { + args["name"], args["body"] = "report", "artifact content" + } + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{ + Name: pullRequestArtifactTestTool(method).Tool.Name, Arguments: args, + }) + require.NoError(t, err) + require.False(t, result.IsError, mustMarshalJSON(t, result)) + if enabled { + assert.JSONEq(t, mustMarshalJSON(t, visibility.label), mustMarshalJSON(t, result.Meta["ifc"])) + } else { + assert.NotContains(t, result.Meta, "ifc") + } + assert.Contains(t, getTextResult(t, result).Text, "artifact content") + assert.Equal(t, 2, calls, "IFC labels reuse the existing repository lookup") + }) + } + } + } +} From 4b06fa0d2c5880834f56dbda8967427bd38189f4 Mon Sep 17 00:00:00 2001 From: Tracy Lum <11878752+talum@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:23:35 +0000 Subject: [PATCH 5/5] Update pull request artifacts feature flag documentation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 633fd653-7701-48a8-8eec-934b966469a3 --- docs/feature-flags.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/docs/feature-flags.md b/docs/feature-flags.md index bad51df827..bbfadbfb7f 100644 --- a/docs/feature-flags.md +++ b/docs/feature-flags.md @@ -156,14 +156,6 @@ Enable `--features=pull_request_artifacts` (or mode. Read-only mode exposes only the read tool. Both tools reject calls in lockdown mode. -The MCP exposure flag `pull_request_artifacts` is separate from GitHub's -`pull_request_artifacts_api` rollout flag. **The API checks the rollout flag -for the target repository, with organization context, on every operation.** -Enabling the MCP flag does not enable the API for a repository. The tools do -not substitute a per-user feature check or cache repository rollout decisions. -A 404 can mean a disabled rollout, missing resource, or insufficient access; -it is not interpreted as a definitive flag status. - All operations require `owner`, `repo`, and `pull_number`. The tools resolve the repository's numeric ID and use the configured authenticated GitHub client and API base URL. They declare `repo` in OAuth challenge metadata;