Skip to content
Merged
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
23 changes: 23 additions & 0 deletions .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: golangci-lint
on:
push:
branches:
- main
pull_request:

permissions:
contents: read

jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: stable
- name: golangci-lint
uses: golangci/golangci-lint-action@v8
with:
version: v2.1
6 changes: 6 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
version: "2"
linters:
exclusions:
presets:
- std-error-handling
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This avoids false positives on .Close() and other common cases.


21 changes: 15 additions & 6 deletions client/transport/streamable_http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,14 @@ func startMockStreamableHTTPServer() (string, func()) {
w.Header().Set("Mcp-Session-Id", sessionID)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(map[string]any{
if err := json.NewEncoder(w).Encode(map[string]any{
"jsonrpc": "2.0",
"id": request["id"],
"result": "initialized",
})
}); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}

case "debug/echo":
// Check session ID
Expand All @@ -62,11 +65,14 @@ func startMockStreamableHTTPServer() (string, func()) {
// Echo back the request as the response result
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]any{
if err := json.NewEncoder(w).Encode(map[string]any{
"jsonrpc": "2.0",
"id": request["id"],
"result": request,
})
}); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}

case "debug/echo_notification":
// Check session ID
Expand Down Expand Up @@ -104,14 +110,17 @@ func startMockStreamableHTTPServer() (string, func()) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
data, _ := json.Marshal(request)
json.NewEncoder(w).Encode(map[string]any{
if err := json.NewEncoder(w).Encode(map[string]any{
"jsonrpc": "2.0",
"id": request["id"],
"error": map[string]any{
"code": -1,
"message": string(data),
},
})
}); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
}
})

Expand Down
2 changes: 1 addition & 1 deletion examples/custom_context/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func NewMCPServer() *MCPServer {
func (s *MCPServer) ServeSSE(addr string) *server.SSEServer {
return server.NewSSEServer(s.server,
server.WithBaseURL(fmt.Sprintf("http://%s", addr)),
server.WithSSEContextFunc(authFromRequest),
server.WithHTTPContextFunc(authFromRequest),
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Deprecated, examples should always use the recommended way.

)
}

Expand Down
5 changes: 4 additions & 1 deletion examples/everything/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ func handleLongRunningOperationTool(
for i := 1; i < int(steps)+1; i++ {
time.Sleep(time.Duration(stepDuration * float64(time.Second)))
if progressToken != nil {
server.SendNotificationToClient(
err := server.SendNotificationToClient(
ctx,
"notifications/progress",
map[string]any{
Expand All @@ -402,6 +402,9 @@ func handleLongRunningOperationTool(
"message": fmt.Sprintf("Server progress %v%%", int(float64(i)*100/steps)),
},
)
if err != nil {
return nil, fmt.Errorf("failed to send notification: %w", err)
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion mcp/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ type URITemplate struct {
}

func (t *URITemplate) MarshalJSON() ([]byte, error) {
return json.Marshal(t.Template.Raw())
return json.Marshal(t.Raw())
}

func (t *URITemplate) UnmarshalJSON(data []byte) error {
Expand Down
2 changes: 1 addition & 1 deletion server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ func TestMCPServer_Tools(t *testing.T) {
"id": 1,
"method": "tools/list"
}`))
tt.validate(t, notifications, toolsList.(mcp.JSONRPCMessage))
tt.validate(t, notifications, toolsList)
})
}
}
Expand Down
3 changes: 2 additions & 1 deletion server/session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,8 @@ func TestMCPServer_NotificationChannelBlocked(t *testing.T) {
require.NoError(t, err)

// Fill the buffer first to ensure it gets blocked
server.SendNotificationToSpecificClient(session.SessionID(), "first-message", nil)
err = server.SendNotificationToSpecificClient(session.SessionID(), "first-message", nil)
require.NoError(t, err)

// This will cause the buffer to block
err = server.SendNotificationToSpecificClient(session.SessionID(), "blocked-message", nil)
Expand Down
23 changes: 19 additions & 4 deletions server/sse.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ func WithSSEEndpoint(endpoint string) SSEOption {
// WithSSEContextFunc sets a function that will be called to customise the context
// to the server using the incoming request.
//
// Deprecated: Use WithContextFunc instead. This will be removed in a future version.
// Deprecated: Use WithHTTPContextFunc instead. This will be removed in a future version.
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Ref: #253

//
//go:deprecated
func WithSSEContextFunc(fn SSEContextFunc) SSEOption {
Expand Down Expand Up @@ -297,7 +297,11 @@ func (s *SSEServer) handleSSE(w http.ResponseWriter, r *http.Request) {
defer s.sessions.Delete(sessionID)

if err := s.server.RegisterSession(r.Context(), session); err != nil {
http.Error(w, fmt.Sprintf("Session registration failed: %v", err), http.StatusInternalServerError)
http.Error(
w,
fmt.Sprintf("Session registration failed: %v", err),
http.StatusInternalServerError,
)
return
}
defer s.server.UnregisterSession(r.Context(), sessionID)
Expand Down Expand Up @@ -480,7 +484,14 @@ func (s *SSEServer) writeJSONRPCError(
response := createErrorResponse(id, code, message)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(response)
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(
w,
fmt.Sprintf("Failed to encode response: %v", err),
http.StatusInternalServerError,
)
return
}
}

// SendEventToSession sends an event to a specific SSE session identified by sessionID.
Expand Down Expand Up @@ -621,7 +632,11 @@ func (s *SSEServer) MessageHandler() http.Handler {
// ServeHTTP implements the http.Handler interface.
func (s *SSEServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if s.dynamicBasePathFunc != nil {
http.Error(w, (&ErrDynamicPathConfig{Method: "ServeHTTP"}).Error(), http.StatusInternalServerError)
http.Error(
w,
(&ErrDynamicPathConfig{Method: "ServeHTTP"}).Error(),
http.StatusInternalServerError,
)
return
}
path := r.URL.Path
Expand Down
3 changes: 2 additions & 1 deletion server/sse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ func TestSSEServer(t *testing.T) {

if sseServer == nil {
t.Error("SSEServer should not be nil")
return
Copy link
Contributor

@coderabbitai coderabbitai bot May 13, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Added critical early return to prevent nil dereference.

This change adds a necessary return statement after detecting that sseServer is nil, which prevents potential nil pointer dereference errors in subsequent test assertions.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes, thanks to the linter in the CI, we won't miss such issues in the future.

Copy link
Contributor

Choose a reason for hiding this comment

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

@pottekkat Absolutely! Integrating golangci-lint into your CI pipeline is a great move that will help catch these kinds of issues automatically before they make it into the codebase. Early detection of potential nil dereferences and similar bugs will save debugging time and improve code quality. Looking forward to seeing the linter in action across the project!


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

}
if sseServer.server == nil {
t.Error("MCPServer should not be nil")
Expand Down Expand Up @@ -1247,7 +1248,7 @@ func TestSSEServer(t *testing.T) {
WithHooks(&Hooks{
OnAfterInitialize: []OnAfterInitializeFunc{
func(ctx context.Context, id any, message *mcp.InitializeRequest, result *mcp.InitializeResult) {
result.Result.Meta = map[string]any{"invalid": func() {}} // marshal will fail
result.Meta = map[string]any{"invalid": func() {}} // marshal will fail
Copy link
Contributor

@coderabbitai coderabbitai bot May 13, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fixed test marshal error simulation.

The assignment now correctly sets result.Meta directly instead of using an incorrect nested field reference (result.Result.Meta), properly simulating a marshal failure in the test.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

🚀

Copy link
Contributor

Choose a reason for hiding this comment

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

@pottekkat Thanks for confirming! The fix ensures that your test correctly simulates a JSON marshal error by directly setting result.Meta instead of the non-existent nested field. This makes the test more accurate and reliable. 👍

},
},
}),
Expand Down