Skip to content

Commit cb96df8

Browse files
Add comprehensive documentation and test coverage for PR resources
Co-authored-by: IrynaKulakova <52420926+IrynaKulakova@users.noreply.github.com>
1 parent 7e6c3d0 commit cb96df8

File tree

3 files changed

+291
-0
lines changed

3 files changed

+291
-0
lines changed

README.md

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -982,6 +982,116 @@ export GITHUB_MCP_TOOL_ADD_ISSUE_COMMENT_DESCRIPTION="an alternative description
982982
</details>
983983
<!-- END AUTOMATED TOOLS -->
984984

985+
## Resources
986+
987+
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.
988+
989+
### Repository Content Resources
990+
991+
Access files and directories from repositories using these resource templates:
992+
993+
#### Main Branch Content
994+
```
995+
repo://{owner}/{repo}/contents{/path*}
996+
```
997+
Access files from the default branch of a repository.
998+
999+
**Example:**
1000+
```
1001+
repo://microsoft/vscode/contents/README.md
1002+
repo://facebook/react/contents/packages/react/src/React.js
1003+
```
1004+
1005+
#### Branch Content
1006+
```
1007+
repo://{owner}/{repo}/refs/heads/{branch}/contents{/path*}
1008+
```
1009+
Access files from a specific branch.
1010+
1011+
**Example:**
1012+
```
1013+
repo://microsoft/vscode/refs/heads/main/contents/src/vs/code/electron-main/main.ts
1014+
repo://facebook/react/refs/heads/canary/contents/package.json
1015+
```
1016+
1017+
#### Tag Content
1018+
```
1019+
repo://{owner}/{repo}/refs/tags/{tag}/contents{/path*}
1020+
```
1021+
Access files from a specific tag or release.
1022+
1023+
**Example:**
1024+
```
1025+
repo://microsoft/vscode/refs/tags/1.85.0/contents/CHANGELOG.md
1026+
repo://facebook/react/refs/tags/v18.2.0/contents/packages/react/package.json
1027+
```
1028+
1029+
#### Commit Content
1030+
```
1031+
repo://{owner}/{repo}/sha/{sha}/contents{/path*}
1032+
```
1033+
Access files from a specific commit.
1034+
1035+
**Example:**
1036+
```
1037+
repo://microsoft/vscode/sha/a1b2c3d4e5f6/contents/src/main.ts
1038+
repo://facebook/react/sha/abc123def456/contents/packages/react/index.js
1039+
```
1040+
1041+
#### Pull Request Content
1042+
```
1043+
repo://{owner}/{repo}/refs/pull/{prNumber}/head/contents{/path*}
1044+
```
1045+
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.
1046+
1047+
**Example:**
1048+
```
1049+
repo://microsoft/vscode/refs/pull/123/head/contents/src/vs/editor/editor.api.ts
1050+
repo://facebook/react/refs/pull/456/head/contents/packages/react-dom/src/client/ReactDOM.js
1051+
```
1052+
1053+
**Use Cases for Pull Request Resources:**
1054+
- **Code Review**: Access modified files to provide automated code review feedback
1055+
- **Documentation Analysis**: Review documentation changes in pull requests
1056+
- **Test Coverage**: Examine test files to understand coverage for new features
1057+
- **Configuration Changes**: Review changes to CI/CD workflows or configuration files
1058+
- **Impact Analysis**: Analyze how changes affect different parts of the codebase
1059+
1060+
### Resource Parameters
1061+
1062+
- **`owner`** (required): Repository owner (username or organization name)
1063+
- **`repo`** (required): Repository name
1064+
- **`path`** (optional): File or directory path within the repository
1065+
- Supports nested paths: `src/components/Button/Button.tsx`
1066+
- Supports files with special characters: `docs/how-to-use-@scoped-packages.md`
1067+
- Must be a file path (directories are not supported for content access)
1068+
1069+
### Supported File Types
1070+
1071+
Resources automatically detect file types and return appropriate content:
1072+
1073+
- **Text files**: `.md`, `.js`, `.ts`, `.py`, `.go`, `.java`, `.cpp`, etc. - returned as text
1074+
- **Configuration files**: `.json`, `.yaml`, `.toml`, `.xml`, etc. - returned as text
1075+
- **Binary files**: `.png`, `.jpg`, `.pdf`, `.zip`, etc. - returned as base64-encoded blobs
1076+
1077+
### Error Handling
1078+
1079+
Resources will return appropriate errors for:
1080+
- Repository not found or access denied
1081+
- Branch, tag, or commit not found
1082+
- Pull request not found or access denied
1083+
- File or path not found
1084+
- Invalid parameters
1085+
1086+
### Tips for Using Resources
1087+
1088+
1. **Be specific with paths**: Always provide the full path to the file you want
1089+
2. **Check permissions**: Ensure your GitHub token has access to the repository and content
1090+
3. **Handle different file types**: Text files return as `text`, binary files as base64 `blob`
1091+
4. **For Pull Requests**: The resource accesses the latest state of the PR's head branch
1092+
1093+
For detailed information about Pull Request resources, see [Pull Request Resources Documentation](docs/pr-resources.md).
1094+
9851095
### Additional Tools in Remote Github MCP Server
9861096

9871097
<details>

docs/pr-resources.md

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
# Pull Request Resources
2+
3+
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.
4+
5+
## Resource URI Template
6+
7+
Pull Request resources use the following URI template:
8+
9+
```
10+
repo://{owner}/{repo}/refs/pull/{prNumber}/head/contents{/path*}
11+
```
12+
13+
## Parameters
14+
15+
- **`owner`** (required): The GitHub username or organization that owns the repository
16+
- **`repo`** (required): The name of the repository
17+
- **`prNumber`** (required): The pull request number (not the pull request ID)
18+
- **`path`** (optional): The path to a specific file or directory within the pull request
19+
20+
## How It Works
21+
22+
When you request a PR resource, the server:
23+
24+
1. Fetches the pull request information from GitHub's API to get the latest commit SHA from the PR's head branch
25+
2. Uses that commit SHA to retrieve the file content at that specific point in time
26+
3. Returns the content as either text or binary (base64-encoded) depending on the file type
27+
28+
## Examples
29+
30+
### Basic Usage
31+
32+
Access the README file from PR #123:
33+
```
34+
repo://microsoft/vscode/refs/pull/123/head/contents/README.md
35+
```
36+
37+
Access a specific file in a subdirectory:
38+
```
39+
repo://facebook/react/refs/pull/456/head/contents/packages/react/src/React.js
40+
```
41+
42+
### Valid Path Values
43+
44+
The `path` parameter supports:
45+
46+
- **Single files**: `README.md`, `package.json`, `src/index.js`
47+
- **Nested files**: `src/components/Button/Button.tsx`, `docs/api/authentication.md`
48+
- **Files with special characters**: `docs/how-to-use-@scoped-packages.md`
49+
- **Files in any directory depth**: `very/deep/nested/directory/structure/file.txt`
50+
51+
### Supported File Types
52+
53+
The server automatically detects file types and returns appropriate content:
54+
55+
- **Text files** (`.md`, `.js`, `.py`, `.go`, etc.): Returned as text with proper MIME type
56+
- **Binary files** (`.png`, `.jpg`, `.pdf`, etc.): Returned as base64-encoded blobs
57+
- **Configuration files** (`.json`, `.yaml`, `.toml`, etc.): Returned as text with appropriate MIME type
58+
59+
## Use Cases
60+
61+
### Code Review
62+
```
63+
repo://owner/repo/refs/pull/789/head/contents/src/new-feature.js
64+
```
65+
Access the implementation of a new feature to provide code review feedback.
66+
67+
### Documentation Analysis
68+
```
69+
repo://owner/repo/refs/pull/234/head/contents/docs/api-changes.md
70+
```
71+
Review documentation changes in a pull request.
72+
73+
### Test Coverage
74+
```
75+
repo://owner/repo/refs/pull/567/head/contents/tests/new-feature.test.js
76+
```
77+
Examine test files to understand test coverage for new features.
78+
79+
### Configuration Changes
80+
```
81+
repo://owner/repo/refs/pull/890/head/contents/.github/workflows/ci.yml
82+
```
83+
Review changes to CI/CD workflows or other configuration files.
84+
85+
## Error Handling
86+
87+
The server will return appropriate errors for common scenarios:
88+
89+
- **Pull request not found**: If the PR number doesn't exist
90+
- **File not found**: If the specified path doesn't exist in the PR
91+
- **Invalid PR number**: If the PR number is not a valid integer
92+
- **Access denied**: If the GitHub token doesn't have permission to access the PR or repository
93+
94+
## Limitations
95+
96+
- **Directories are not supported**: You can only access individual files, not directory listings
97+
- **Private repositories**: Require appropriate GitHub token permissions
98+
- **Large files**: Very large files may hit GitHub API limits
99+
- **Binary files**: Returned as base64-encoded content which may be large
100+
101+
## Related Resources
102+
103+
- [Repository Resources](../README.md#tools) - For accessing files from the main branch
104+
- [Branch Resources](../README.md#tools) - For accessing files from specific branches
105+
- [Tag Resources](../README.md#tools) - For accessing files from specific tags
106+
- [Commit Resources](../README.md#tools) - For accessing files from specific commits
107+
108+
## Tips
109+
110+
1. **Use specific paths**: Always specify the full path to the file you want to access
111+
2. **Check PR status**: Ensure the PR is still open and accessible before attempting to access resources
112+
3. **Handle errors gracefully**: Always implement proper error handling for resource access
113+
4. **Consider file size**: Be mindful of large files that may impact performance

pkg/github/repository_resource_test.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,68 @@ func Test_repositoryResourceContentsHandler(t *testing.T) {
207207
URI: "",
208208
}},
209209
},
210+
{
211+
name: "successful text content fetch (pr with path)",
212+
mockedClient: mock.NewMockedHTTPClient(
213+
mock.WithRequestMatchHandler(
214+
mock.GetReposPullsByOwnerByRepoByPullNumber,
215+
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
216+
w.Header().Set("Content-Type", "application/json")
217+
_, err := w.Write([]byte(`{"head": {"sha": "def456"}}`))
218+
require.NoError(t, err)
219+
}),
220+
),
221+
mock.WithRequestMatchHandler(
222+
raw.GetRawReposContentsByOwnerByRepoBySHAByPath,
223+
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
224+
w.Header().Set("Content-Type", "application/javascript")
225+
_, err := w.Write([]byte("console.log('Hello from PR');"))
226+
require.NoError(t, err)
227+
}),
228+
),
229+
),
230+
requestArgs: map[string]any{
231+
"owner": []string{"owner"},
232+
"repo": []string{"repo"},
233+
"path": []string{"src", "main.js"},
234+
"prNumber": []string{"123"},
235+
},
236+
expectedResult: []mcp.TextResourceContents{{
237+
Text: "console.log('Hello from PR');",
238+
MIMEType: "application/javascript",
239+
URI: "",
240+
}},
241+
},
242+
{
243+
name: "pr not found error",
244+
mockedClient: mock.NewMockedHTTPClient(
245+
mock.WithRequestMatchHandler(
246+
mock.GetReposPullsByOwnerByRepoByPullNumber,
247+
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
248+
w.WriteHeader(http.StatusNotFound)
249+
_, _ = w.Write([]byte(`{"message": "Not Found"}`))
250+
}),
251+
),
252+
),
253+
requestArgs: map[string]any{
254+
"owner": []string{"owner"},
255+
"repo": []string{"repo"},
256+
"path": []string{"README.md"},
257+
"prNumber": []string{"999"},
258+
},
259+
expectError: "failed to get pull request",
260+
},
261+
{
262+
name: "invalid pr number",
263+
mockedClient: mock.NewMockedHTTPClient(),
264+
requestArgs: map[string]any{
265+
"owner": []string{"owner"},
266+
"repo": []string{"repo"},
267+
"path": []string{"README.md"},
268+
"prNumber": []string{"invalid"},
269+
},
270+
expectError: "invalid pull request number",
271+
},
210272
{
211273
name: "content fetch fails",
212274
mockedClient: mock.NewMockedHTTPClient(
@@ -278,3 +340,9 @@ func Test_GetRepositoryResourceTagContent(t *testing.T) {
278340
tmpl, _ := GetRepositoryResourceTagContent(nil, stubGetRawClientFn(mockRawClient), translations.NullTranslationHelper)
279341
require.Equal(t, "repo://{owner}/{repo}/refs/tags/{tag}/contents{/path*}", tmpl.URITemplate.Raw())
280342
}
343+
344+
func Test_GetRepositoryResourcePrContent(t *testing.T) {
345+
mockRawClient := raw.NewClient(github.NewClient(nil), &url.URL{})
346+
tmpl, _ := GetRepositoryResourcePrContent(nil, stubGetRawClientFn(mockRawClient), translations.NullTranslationHelper)
347+
require.Equal(t, "repo://{owner}/{repo}/refs/pull/{prNumber}/head/contents{/path*}", tmpl.URITemplate.Raw())
348+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy