Skip to content

fix: Always include SHA in get_file_contents responses (#595) #6

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

Closed
wants to merge 2 commits into from
Closed
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
65 changes: 9 additions & 56 deletions pkg/github/repositories.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package github

import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"

ghErrors "github.com/github/github-mcp-server/pkg/errors"
Expand Down Expand Up @@ -446,7 +444,7 @@ func CreateRepository(getClient GetClientFn, t translations.TranslationHelperFun
}

// GetFileContents creates a tool to get the contents of a file or directory from a GitHub repository.
func GetFileContents(getClient GetClientFn, getRawClient raw.GetRawClientFn, t translations.TranslationHelperFunc) (tool mcp.Tool, handler server.ToolHandlerFunc) {
func GetFileContents(getClient GetClientFn, _ raw.GetRawClientFn, t translations.TranslationHelperFunc) (tool mcp.Tool, handler server.ToolHandlerFunc) {
return mcp.NewTool("get_file_contents",
mcp.WithDescription(t("TOOL_GET_FILE_CONTENTS_DESCRIPTION", "Get the contents of a file or directory from a GitHub repository")),
mcp.WithToolAnnotation(mcp.ToolAnnotation{
Expand Down Expand Up @@ -505,62 +503,17 @@ func GetFileContents(getClient GetClientFn, getRawClient raw.GetRawClientFn, t t
}

// If the path is (most likely) not to be a directory, we will
// first try to get the raw content from the GitHub raw content API.
// try to get the content using the GitHub contents API to include SHA information.
if path != "" && !strings.HasSuffix(path, "/") {

rawClient, err := getRawClient(ctx)
if err != nil {
return mcp.NewToolResultError("failed to get GitHub raw content client"), nil
}
resp, err := rawClient.GetRawContent(ctx, owner, repo, path, rawOpts)
if err != nil {
return mcp.NewToolResultError("failed to get raw repository content"), nil
}
defer func() {
_ = resp.Body.Close()
}()

if resp.StatusCode == http.StatusOK {
// If the raw content is found, return it directly
body, err := io.ReadAll(resp.Body)
opts := &github.RepositoryContentGetOptions{Ref: ref}
fileContent, _, resp, err := client.Repositories.GetContents(ctx, owner, repo, path, opts)
if err == nil && resp.StatusCode == http.StatusOK && fileContent != nil {
defer func() { _ = resp.Body.Close() }()
r, err := json.Marshal(fileContent)
if err != nil {
return mcp.NewToolResultError("failed to read response body"), nil
}
contentType := resp.Header.Get("Content-Type")

var resourceURI string
switch {
case sha != "":
resourceURI, err = url.JoinPath("repo://", owner, repo, "sha", sha, "contents", path)
if err != nil {
return nil, fmt.Errorf("failed to create resource URI: %w", err)
}
case ref != "":
resourceURI, err = url.JoinPath("repo://", owner, repo, ref, "contents", path)
if err != nil {
return nil, fmt.Errorf("failed to create resource URI: %w", err)
}
default:
resourceURI, err = url.JoinPath("repo://", owner, repo, "contents", path)
if err != nil {
return nil, fmt.Errorf("failed to create resource URI: %w", err)
}
}

if strings.HasPrefix(contentType, "application") || strings.HasPrefix(contentType, "text") {
return mcp.NewToolResultResource("successfully downloaded text file", mcp.TextResourceContents{
URI: resourceURI,
Text: string(body),
MIMEType: contentType,
}), nil
return mcp.NewToolResultError("failed to marshal response"), nil
}

return mcp.NewToolResultResource("successfully downloaded binary file", mcp.BlobResourceContents{
URI: resourceURI,
Blob: base64.StdEncoding.EncodeToString(body),
MIMEType: contentType,
}), nil

return mcp.NewToolResultText(string(r)), nil
}
}

Expand Down
101 changes: 66 additions & 35 deletions pkg/github/repositories_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ func Test_GetFileContents(t *testing.T) {
assert.Contains(t, tool.InputSchema.Properties, "sha")
assert.ElementsMatch(t, tool.InputSchema.Required, []string{"owner", "repo"})

// Mock response for raw content
mockRawContent := []byte("# Test Repository\n\nThis is a test repository.")


// Setup mock directory content for success case
mockDirContent := []*github.RepositoryContent{
Expand Down Expand Up @@ -67,20 +66,31 @@ func Test_GetFileContents(t *testing.T) {
expectStatus int
}{
{
name: "successful text content fetch",
name: "successful file content fetch",
mockedClient: mock.NewMockedHTTPClient(
mock.WithRequestMatchHandler(
mock.GetReposGitRefByOwnerByRepoByRef,
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"ref": "refs/heads/main", "object": {"sha": ""}}`))
_, _ = w.Write([]byte(`{"ref": "refs/heads/main", "object": {"sha": "abc123"}}`))
}),
),
mock.WithRequestMatchHandler(
raw.GetRawReposContentsByOwnerByRepoByBranchByPath,
mock.GetReposContentsByOwnerByRepoByPath,
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/markdown")
_, _ = w.Write(mockRawContent)
w.WriteHeader(http.StatusOK)
fileContent := &github.RepositoryContent{
Type: github.Ptr("file"),
Name: github.Ptr("README.md"),
Path: github.Ptr("README.md"),
SHA: github.Ptr("abc123"),
Size: github.Ptr(42),
Content: github.Ptr(base64.StdEncoding.EncodeToString([]byte("# Test Repository\n\nThis is a test repository."))),
Encoding: github.Ptr("base64"),
HTMLURL: github.Ptr("https://github.com/owner/repo/blob/main/README.md"),
}
responseBody, _ := json.Marshal(fileContent)
_, _ = w.Write(responseBody)
}),
),
),
Expand All @@ -91,27 +101,43 @@ func Test_GetFileContents(t *testing.T) {
"ref": "refs/heads/main",
},
expectError: false,
expectedResult: mcp.TextResourceContents{
URI: "repo://owner/repo/refs/heads/main/contents/README.md",
Text: "# Test Repository\n\nThis is a test repository.",
MIMEType: "text/markdown",
expectedResult: &github.RepositoryContent{
Type: github.Ptr("file"),
Name: github.Ptr("README.md"),
Path: github.Ptr("README.md"),
SHA: github.Ptr("abc123"),
Size: github.Ptr(42),
Content: github.Ptr(base64.StdEncoding.EncodeToString([]byte("# Test Repository\n\nThis is a test repository."))),
Encoding: github.Ptr("base64"),
HTMLURL: github.Ptr("https://github.com/owner/repo/blob/main/README.md"),
},
},
{
name: "successful file blob content fetch",
name: "successful binary file content fetch",
mockedClient: mock.NewMockedHTTPClient(
mock.WithRequestMatchHandler(
mock.GetReposGitRefByOwnerByRepoByRef,
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"ref": "refs/heads/main", "object": {"sha": ""}}`))
_, _ = w.Write([]byte(`{"ref": "refs/heads/main", "object": {"sha": "def456"}}`))
}),
),
mock.WithRequestMatchHandler(
raw.GetRawReposContentsByOwnerByRepoByBranchByPath,
mock.GetReposContentsByOwnerByRepoByPath,
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(mockRawContent)
w.WriteHeader(http.StatusOK)
fileContent := &github.RepositoryContent{
Type: github.Ptr("file"),
Name: github.Ptr("test.png"),
Path: github.Ptr("test.png"),
SHA: github.Ptr("def456"),
Size: github.Ptr(1024),
Content: github.Ptr(base64.StdEncoding.EncodeToString([]byte("binary-image-content"))),
Encoding: github.Ptr("base64"),
HTMLURL: github.Ptr("https://github.com/owner/repo/blob/main/test.png"),
}
responseBody, _ := json.Marshal(fileContent)
_, _ = w.Write(responseBody)
}),
),
),
Expand All @@ -122,10 +148,15 @@ func Test_GetFileContents(t *testing.T) {
"ref": "refs/heads/main",
},
expectError: false,
expectedResult: mcp.BlobResourceContents{
URI: "repo://owner/repo/refs/heads/main/contents/test.png",
Blob: base64.StdEncoding.EncodeToString(mockRawContent),
MIMEType: "image/png",
expectedResult: &github.RepositoryContent{
Type: github.Ptr("file"),
Name: github.Ptr("test.png"),
Path: github.Ptr("test.png"),
SHA: github.Ptr("def456"),
Size: github.Ptr(1024),
Content: github.Ptr(base64.StdEncoding.EncodeToString([]byte("binary-image-content"))),
Encoding: github.Ptr("base64"),
HTMLURL: github.Ptr("https://github.com/owner/repo/blob/main/test.png"),
},
},
{
Expand All @@ -151,14 +182,7 @@ func Test_GetFileContents(t *testing.T) {
mockResponse(t, http.StatusOK, mockDirContent),
),
),
mock.WithRequestMatchHandler(
raw.GetRawReposContentsByOwnerByRepoByPath,
expectQueryParams(t, map[string]string{
"branch": "main",
}).andThen(
mockResponse(t, http.StatusNotFound, nil),
),
),

),
requestArgs: map[string]interface{}{
"owner": "owner",
Expand Down Expand Up @@ -186,7 +210,7 @@ func Test_GetFileContents(t *testing.T) {
}),
),
mock.WithRequestMatchHandler(
raw.GetRawReposContentsByOwnerByRepoByPath,
mock.GetReposGitTreesByOwnerByRepoByTreeSha,
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"message": "Not Found"}`))
Expand Down Expand Up @@ -227,12 +251,19 @@ func Test_GetFileContents(t *testing.T) {
require.NoError(t, err)
// Use the correct result helper based on the expected type
switch expected := tc.expectedResult.(type) {
case mcp.TextResourceContents:
textResource := getTextResourceResult(t, result)
assert.Equal(t, expected, textResource)
case mcp.BlobResourceContents:
blobResource := getBlobResourceResult(t, result)
assert.Equal(t, expected, blobResource)
case *github.RepositoryContent:
// File content fetch returns a text result (JSON object)
textContent := getTextResult(t, result)
var returnedContent github.RepositoryContent
err = json.Unmarshal([]byte(textContent.Text), &returnedContent)
require.NoError(t, err, "Failed to unmarshal file content result: %v", textContent.Text)
assert.Equal(t, *expected.Name, *returnedContent.Name)
assert.Equal(t, *expected.Path, *returnedContent.Path)
assert.Equal(t, *expected.Type, *returnedContent.Type)
assert.Equal(t, *expected.SHA, *returnedContent.SHA)
if expected.Content != nil && returnedContent.Content != nil {
assert.Equal(t, *expected.Content, *returnedContent.Content)
}
case []*github.RepositoryContent:
// Directory content fetch returns a text result (JSON array)
textContent := getTextResult(t, result)
Expand Down
Loading