Skip to content
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

Add support for retrieving GitHub Issue Comments #106

Merged
merged 4 commits into from
Apr 7, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,12 @@ export GITHUB_MCP_TOOL_ADD_ISSUE_COMMENT_DESCRIPTION="an alternative description
- `repo`: Repository name (string, required)
- `issue_number`: Issue number (number, required)

- **get_issue_comments** - Get comments for a GitHub issue

- `owner`: Repository owner (string, required)
- `repo`: Repository name (string, required)
- `issue_number`: Issue number (number, required)

- **create_issue** - Create a new issue in a GitHub repository

- `owner`: Repository owner (string, required)
Expand Down
1 change: 1 addition & 0 deletions cmd/mcpcurl/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ Available Commands:
fork_repository Fork a GitHub repository to your account or specified organization
get_file_contents Get the contents of a file or directory from a GitHub repository
get_issue Get details of a specific issue in a GitHub repository.
get_issue_comments Get comments for a GitHub issue
list_commits Get list of commits of a branch in a GitHub repository
list_issues List issues in a GitHub repository with filtering options
push_files Push multiple files to a GitHub repository in a single commit
Expand Down
60 changes: 60 additions & 0 deletions pkg/github/issues.go
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,66 @@ func updateIssue(client *github.Client, t translations.TranslationHelperFunc) (t
}
}

// getIssueComments creates a tool to get comments for a GitHub issue.
func getIssueComments(client *github.Client, t translations.TranslationHelperFunc) (tool mcp.Tool, handler server.ToolHandlerFunc) {
return mcp.NewTool("get_issue_comments",
mcp.WithDescription(t("TOOL_GET_ISSUE_COMMENTS_DESCRIPTION", "Get comments for a GitHub issue")),
mcp.WithString("owner",
mcp.Required(),
mcp.Description("Repository owner"),
),
mcp.WithString("repo",
mcp.Required(),
mcp.Description("Repository name"),
),
mcp.WithNumber("issue_number",
mcp.Required(),
mcp.Description("Issue number"),
),
),
func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
owner, err := requiredParam[string](request, "owner")
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
repo, err := requiredParam[string](request, "repo")
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
issueNumber, err := requiredInt(request, "issue_number")
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}

opts := &github.IssueListCommentsOptions{
ListOptions: github.ListOptions{
PerPage: 100,
},
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, let's add proper support for pagination. That is, let's make the tool take page, and perPage. Take a look at listCommits if you want to see an example.

To be consistent, use 30 as the default page size.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤦 Great catch - I added pagination with a default perPage of 30, and added tests for it!


comments, resp, err := client.Issues.ListComments(ctx, owner, repo, issueNumber, opts)
if err != nil {
return nil, fmt.Errorf("failed to get issue comments: %w", err)
}
defer func() { _ = resp.Body.Close() }()

if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
return mcp.NewToolResultError(fmt.Sprintf("failed to get issue comments: %s", string(body))), nil
}

r, err := json.Marshal(comments)
if err != nil {
return nil, fmt.Errorf("failed to marshal response: %w", err)
}

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

// parseISOTimestamp parses an ISO 8601 timestamp string into a time.Time object.
// Returns the parsed time or an error if parsing fails.
// Example formats supported: "2023-01-15T14:30:00Z", "2023-01-15"
Expand Down
109 changes: 109 additions & 0 deletions pkg/github/issues_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -984,3 +984,112 @@ func Test_ParseISOTimestamp(t *testing.T) {
})
}
}

func Test_GetIssueComments(t *testing.T) {
// Verify tool definition once
mockClient := github.NewClient(nil)
tool, _ := getIssueComments(mockClient, translations.NullTranslationHelper)

assert.Equal(t, "get_issue_comments", tool.Name)
assert.NotEmpty(t, tool.Description)
assert.Contains(t, tool.InputSchema.Properties, "owner")
assert.Contains(t, tool.InputSchema.Properties, "repo")
assert.Contains(t, tool.InputSchema.Properties, "issue_number")
assert.ElementsMatch(t, tool.InputSchema.Required, []string{"owner", "repo", "issue_number"})

// Setup mock comments for success case
mockComments := []*github.IssueComment{
{
ID: github.Ptr(int64(123)),
Body: github.Ptr("This is the first comment"),
User: &github.User{
Login: github.Ptr("user1"),
},
CreatedAt: &github.Timestamp{Time: time.Now().Add(-time.Hour * 24)},
},
{
ID: github.Ptr(int64(456)),
Body: github.Ptr("This is the second comment"),
User: &github.User{
Login: github.Ptr("user2"),
},
CreatedAt: &github.Timestamp{Time: time.Now().Add(-time.Hour)},
},
}

tests := []struct {
name string
mockedClient *http.Client
requestArgs map[string]interface{}
expectError bool
expectedComments []*github.IssueComment
expectedErrMsg string
}{
{
name: "successful comments retrieval",
mockedClient: mock.NewMockedHTTPClient(
mock.WithRequestMatch(
mock.GetReposIssuesCommentsByOwnerByRepoByIssueNumber,
mockComments,
),
),
requestArgs: map[string]interface{}{
"owner": "owner",
"repo": "repo",
"issue_number": float64(42),
},
expectError: false,
expectedComments: mockComments,
},
{
name: "issue not found",
mockedClient: mock.NewMockedHTTPClient(
mock.WithRequestMatchHandler(
mock.GetReposIssuesCommentsByOwnerByRepoByIssueNumber,
mockResponse(t, http.StatusNotFound, `{"message": "Issue not found"}`),
),
),
requestArgs: map[string]interface{}{
"owner": "owner",
"repo": "repo",
"issue_number": float64(999),
},
expectError: true,
expectedErrMsg: "failed to get issue comments",
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Setup client with mock
client := github.NewClient(tc.mockedClient)
_, handler := getIssueComments(client, translations.NullTranslationHelper)

// Create call request
request := createMCPRequest(tc.requestArgs)

// Call handler
result, err := handler(context.Background(), request)

// Verify results
if tc.expectError {
require.Error(t, err)
assert.Contains(t, err.Error(), tc.expectedErrMsg)
return
}

require.NoError(t, err)
textContent := getTextResult(t, result)

// Unmarshal and verify the result
var returnedComments []*github.IssueComment
err = json.Unmarshal([]byte(textContent.Text), &returnedComments)
require.NoError(t, err)
assert.Equal(t, len(tc.expectedComments), len(returnedComments))
if len(returnedComments) > 0 {
assert.Equal(t, *tc.expectedComments[0].Body, *returnedComments[0].Body)
assert.Equal(t, *tc.expectedComments[0].User.Login, *returnedComments[0].User.Login)
}
})
}
}
1 change: 1 addition & 0 deletions pkg/github/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func NewServer(client *github.Client, readOnly bool, t translations.TranslationH
s.AddTool(getIssue(client, t))
s.AddTool(searchIssues(client, t))
s.AddTool(listIssues(client, t))
s.AddTool(getIssueComments(client, t))
if !readOnly {
s.AddTool(createIssue(client, t))
s.AddTool(addIssueComment(client, t))
Expand Down