Skip to content

Add comprehensive documentation and examples for Pull Request resources #677

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -982,6 +982,116 @@ export GITHUB_MCP_TOOL_ADD_ISSUE_COMMENT_DESCRIPTION="an alternative description
</details>
<!-- END AUTOMATED TOOLS -->

## Resources

The GitHub MCP Server provides MCP resources that allow AI tools to access repository content as context. Resources use URI templates to specify what content to retrieve.

### Repository Content Resources

Access files and directories from repositories using these resource templates:

#### Main Branch Content
```
repo://{owner}/{repo}/contents{/path*}
```
Access files from the default branch of a repository.

**Example:**
```
repo://microsoft/vscode/contents/README.md
repo://facebook/react/contents/packages/react/src/React.js
```

#### Branch Content
```
repo://{owner}/{repo}/refs/heads/{branch}/contents{/path*}
```
Access files from a specific branch.

**Example:**
```
repo://microsoft/vscode/refs/heads/main/contents/src/vs/code/electron-main/main.ts
repo://facebook/react/refs/heads/canary/contents/package.json
```

#### Tag Content
```
repo://{owner}/{repo}/refs/tags/{tag}/contents{/path*}
```
Access files from a specific tag or release.

**Example:**
```
repo://microsoft/vscode/refs/tags/1.85.0/contents/CHANGELOG.md
repo://facebook/react/refs/tags/v18.2.0/contents/packages/react/package.json
```

#### Commit Content
```
repo://{owner}/{repo}/sha/{sha}/contents{/path*}
```
Access files from a specific commit.

**Example:**
```
repo://microsoft/vscode/sha/a1b2c3d4e5f6/contents/src/main.ts
repo://facebook/react/sha/abc123def456/contents/packages/react/index.js
```

#### Pull Request Content
```
repo://{owner}/{repo}/refs/pull/{prNumber}/head/contents{/path*}
```
Access files from a pull request's head branch. This is particularly useful for reviewing code changes, analyzing new features, or providing feedback on pull requests.

**Example:**
```
repo://microsoft/vscode/refs/pull/123/head/contents/src/vs/editor/editor.api.ts
repo://facebook/react/refs/pull/456/head/contents/packages/react-dom/src/client/ReactDOM.js
```

**Use Cases for Pull Request Resources:**
- **Code Review**: Access modified files to provide automated code review feedback
- **Documentation Analysis**: Review documentation changes in pull requests
- **Test Coverage**: Examine test files to understand coverage for new features
- **Configuration Changes**: Review changes to CI/CD workflows or configuration files
- **Impact Analysis**: Analyze how changes affect different parts of the codebase

### Resource Parameters

- **`owner`** (required): Repository owner (username or organization name)
- **`repo`** (required): Repository name
- **`path`** (optional): File or directory path within the repository
- Supports nested paths: `src/components/Button/Button.tsx`
- Supports files with special characters: `docs/how-to-use-@scoped-packages.md`
- Must be a file path (directories are not supported for content access)

### Supported File Types

Resources automatically detect file types and return appropriate content:

- **Text files**: `.md`, `.js`, `.ts`, `.py`, `.go`, `.java`, `.cpp`, etc. - returned as text
- **Configuration files**: `.json`, `.yaml`, `.toml`, `.xml`, etc. - returned as text
- **Binary files**: `.png`, `.jpg`, `.pdf`, `.zip`, etc. - returned as base64-encoded blobs

### Error Handling

Resources will return appropriate errors for:
- Repository not found or access denied
- Branch, tag, or commit not found
- Pull request not found or access denied
- File or path not found
- Invalid parameters

### Tips for Using Resources

1. **Be specific with paths**: Always provide the full path to the file you want
2. **Check permissions**: Ensure your GitHub token has access to the repository and content
3. **Handle different file types**: Text files return as `text`, binary files as base64 `blob`
4. **For Pull Requests**: The resource accesses the latest state of the PR's head branch

For detailed information about Pull Request resources, see [Pull Request Resources Documentation](docs/pr-resources.md).

### Additional Tools in Remote Github MCP Server

<details>
Expand Down
113 changes: 113 additions & 0 deletions docs/pr-resources.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Pull Request Resources

The GitHub MCP Server supports accessing files and content from Pull Requests (PRs) as MCP resources. This allows AI tools to read and analyze code changes in pull requests for various purposes like code review, documentation, and analysis.

## Resource URI Template

Pull Request resources use the following URI template:

```
repo://{owner}/{repo}/refs/pull/{prNumber}/head/contents{/path*}
```

## Parameters

- **`owner`** (required): The GitHub username or organization that owns the repository
- **`repo`** (required): The name of the repository
- **`prNumber`** (required): The pull request number (not the pull request ID)
- **`path`** (optional): The path to a specific file or directory within the pull request

## How It Works

When you request a PR resource, the server:

1. Fetches the pull request information from GitHub's API to get the latest commit SHA from the PR's head branch
2. Uses that commit SHA to retrieve the file content at that specific point in time
3. Returns the content as either text or binary (base64-encoded) depending on the file type

## Examples

### Basic Usage

Access the README file from PR #123:
```
repo://microsoft/vscode/refs/pull/123/head/contents/README.md
```

Access a specific file in a subdirectory:
```
repo://facebook/react/refs/pull/456/head/contents/packages/react/src/React.js
```

### Valid Path Values

The `path` parameter supports:

- **Single files**: `README.md`, `package.json`, `src/index.js`
- **Nested files**: `src/components/Button/Button.tsx`, `docs/api/authentication.md`
- **Files with special characters**: `docs/how-to-use-@scoped-packages.md`
- **Files in any directory depth**: `very/deep/nested/directory/structure/file.txt`

### Supported File Types

The server automatically detects file types and returns appropriate content:

- **Text files** (`.md`, `.js`, `.py`, `.go`, etc.): Returned as text with proper MIME type
- **Binary files** (`.png`, `.jpg`, `.pdf`, etc.): Returned as base64-encoded blobs
- **Configuration files** (`.json`, `.yaml`, `.toml`, etc.): Returned as text with appropriate MIME type

## Use Cases

### Code Review
```
repo://owner/repo/refs/pull/789/head/contents/src/new-feature.js
```
Access the implementation of a new feature to provide code review feedback.

### Documentation Analysis
```
repo://owner/repo/refs/pull/234/head/contents/docs/api-changes.md
```
Review documentation changes in a pull request.

### Test Coverage
```
repo://owner/repo/refs/pull/567/head/contents/tests/new-feature.test.js
```
Examine test files to understand test coverage for new features.

### Configuration Changes
```
repo://owner/repo/refs/pull/890/head/contents/.github/workflows/ci.yml
```
Review changes to CI/CD workflows or other configuration files.

## Error Handling

The server will return appropriate errors for common scenarios:

- **Pull request not found**: If the PR number doesn't exist
- **File not found**: If the specified path doesn't exist in the PR
- **Invalid PR number**: If the PR number is not a valid integer
- **Access denied**: If the GitHub token doesn't have permission to access the PR or repository

## Limitations

- **Directories are not supported**: You can only access individual files, not directory listings
- **Private repositories**: Require appropriate GitHub token permissions
- **Large files**: Very large files may hit GitHub API limits
- **Binary files**: Returned as base64-encoded content which may be large

## Related Resources

- [Repository Resources](../README.md#tools) - For accessing files from the main branch
- [Branch Resources](../README.md#tools) - For accessing files from specific branches
- [Tag Resources](../README.md#tools) - For accessing files from specific tags
- [Commit Resources](../README.md#tools) - For accessing files from specific commits

## Tips

1. **Use specific paths**: Always specify the full path to the file you want to access
2. **Check PR status**: Ensure the PR is still open and accessible before attempting to access resources
3. **Handle errors gracefully**: Always implement proper error handling for resource access
4. **Consider file size**: Be mindful of large files that may impact performance
68 changes: 68 additions & 0 deletions pkg/github/repository_resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,68 @@ func Test_repositoryResourceContentsHandler(t *testing.T) {
URI: "",
}},
},
{
name: "successful text content fetch (pr with path)",
mockedClient: mock.NewMockedHTTPClient(
mock.WithRequestMatchHandler(
mock.GetReposPullsByOwnerByRepoByPullNumber,
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, err := w.Write([]byte(`{"head": {"sha": "def456"}}`))
require.NoError(t, err)
}),
),
mock.WithRequestMatchHandler(
raw.GetRawReposContentsByOwnerByRepoBySHAByPath,
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/javascript")
_, err := w.Write([]byte("console.log('Hello from PR');"))
require.NoError(t, err)
}),
),
),
requestArgs: map[string]any{
"owner": []string{"owner"},
"repo": []string{"repo"},
"path": []string{"src", "main.js"},
"prNumber": []string{"123"},
},
expectedResult: []mcp.TextResourceContents{{
Text: "console.log('Hello from PR');",
MIMEType: "application/javascript",
URI: "",
}},
},
{
name: "pr not found error",
mockedClient: mock.NewMockedHTTPClient(
mock.WithRequestMatchHandler(
mock.GetReposPullsByOwnerByRepoByPullNumber,
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"message": "Not Found"}`))
}),
),
),
requestArgs: map[string]any{
"owner": []string{"owner"},
"repo": []string{"repo"},
"path": []string{"README.md"},
"prNumber": []string{"999"},
},
expectError: "failed to get pull request",
},
{
name: "invalid pr number",
mockedClient: mock.NewMockedHTTPClient(),
requestArgs: map[string]any{
"owner": []string{"owner"},
"repo": []string{"repo"},
"path": []string{"README.md"},
"prNumber": []string{"invalid"},
},
expectError: "invalid pull request number",
},
{
name: "content fetch fails",
mockedClient: mock.NewMockedHTTPClient(
Expand Down Expand Up @@ -278,3 +340,9 @@ func Test_GetRepositoryResourceTagContent(t *testing.T) {
tmpl, _ := GetRepositoryResourceTagContent(nil, stubGetRawClientFn(mockRawClient), translations.NullTranslationHelper)
require.Equal(t, "repo://{owner}/{repo}/refs/tags/{tag}/contents{/path*}", tmpl.URITemplate.Raw())
}

func Test_GetRepositoryResourcePrContent(t *testing.T) {
mockRawClient := raw.NewClient(github.NewClient(nil), &url.URL{})
tmpl, _ := GetRepositoryResourcePrContent(nil, stubGetRawClientFn(mockRawClient), translations.NullTranslationHelper)
require.Equal(t, "repo://{owner}/{repo}/refs/pull/{prNumber}/head/contents{/path*}", tmpl.URITemplate.Raw())
}
Loading