github-mcp-server
github-mcp-server copied to clipboard
Fix panic when fetching resources fails due to network error
Summary
Fixes a panic that occurs when fetching repository resource content fails due to a network error (e.g., connection timeout, DNS failure).
Problem
In RepositoryResourceContentsHandler, the code called defer resp.Body.Close() before checking if GetRawContent returned an error:
resp, err := rawClient.GetRawContent(ctx, owner, repo, path, rawOpts)
defer func() {
_ = resp.Body.Close()
}()
// If the raw content is not found...
switch {
case err != nil:
return nil, fmt.Errorf("failed to get raw content: %w", err)
When a network error occurs, resp is nil, causing a panic when the deferred function tries to access resp.Body.
Solution
Move the error check before the defer statement:
resp, err := rawClient.GetRawContent(ctx, owner, repo, path, rawOpts)
if err != nil {
return nil, fmt.Errorf("failed to get raw content: %w", err)
}
defer func() {
_ = resp.Body.Close()
}()
Testing
Added Test_repositoryResourceContentsHandler_NetworkError which uses a custom errorTransport that always returns an error. This test ensures the handler gracefully handles network errors without panicking.
$ go test ./pkg/github/... -run "Test_repositoryResource" -v
=== RUN Test_repositoryResourceContentsHandler
...
--- PASS: Test_repositoryResourceContentsHandler (0.01s)
=== RUN Test_repositoryResourceContentsHandler_NetworkError
--- PASS: Test_repositoryResourceContentsHandler_NetworkError (0.00s)
PASS
Checklist
- [x]
script/lintpasses - [x]
script/testpasses - [x] Added test for the fix