Skip to content

feat: quick return tool-call request, send response via SSE in goroutine #163

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

CeerDecy
Copy link

@CeerDecy CeerDecy commented Apr 17, 2025

to solve the #162

the ToolCall request should return an HTTP 202 (Accepted) status code immediately, without waiting for handleMessage to complete.

like https://github.com/modelcontextprotocol/python-sdk src/mcp/server/sse.py 174

Summary by CodeRabbit

Summary by CodeRabbit

  • Refactor
    • Improved responsiveness by processing incoming messages asynchronously, allowing faster acknowledgment of requests.
    • Enhanced internal code formatting for better readability.
  • Tests
    • Unified SSE event reading with a new helper function for consistent test handling.
    • Adjusted JSON decoding in tests to parse from SSE event data for accuracy.

Copy link
Contributor

coderabbitai bot commented Apr 17, 2025

Walkthrough

The update refactors the message handling flow within the SSE server implementation. The handleMessage method now immediately responds to HTTP requests with a 202 Accepted status and processes incoming messages asynchronously in a separate goroutine. Any resulting responses are marshaled and queued for delivery over the established SSE connection, rather than being sent directly in the HTTP response. Additionally, minor formatting adjustments were made to the struct field alignment and code layout. The test code was refactored to unify SSE event reading via a new helper function and to decode JSON responses from SSE event data strings instead of directly from HTTP response bodies. No changes were made to public APIs or exported function signatures.

Changes

File(s) Change Summary
server/sse.go Refactored handleMessage to decouple HTTP response from message processing, enabling asynchronous handling; added logging for full event queue; adjusted struct field alignment and removed an extraneous blank line in handleSSE; imported log package.
server/sse_test.go Added readSeeEvent helper to unify reading SSE events from response bodies; replaced direct reads with this helper; adjusted JSON decoding to parse from SSE event data strings instead of HTTP response bodies; added debug print in multi-session test.

Possibly related PRs

  • Expose SSE server as HttpHandler #29: Added a new ServeHTTP method to SSEServer exposing it as an HTTP handler routing requests to handleMessage and other methods; related as it calls the refactored handleMessage.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
server/sse.go (2)

358-358: Consider adding documentation about the changed behavior.

This line explains the purpose, but consider updating function-level comments at line 324 to document the changed behavior that all responses are now sent via SSE rather than in the HTTP response.


375-377: Consider adding backpressure mechanism for queue full scenarios.

Currently, if the event queue is full, the message is silently dropped. Consider adding a backpressure mechanism or at minimum logging this situation to help diagnose issues.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 37ac814 and c886adb.

📒 Files selected for processing (1)
  • server/sse.go (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
server/sse.go (1)
server/server.go (1)
  • MCPServer (143-166)
🔇 Additional comments (3)
server/sse.go (3)

56-64: Code formatting improvement looks good.

The alignment of struct fields improves readability and maintains consistent style.


161-166: Struct initialization formatting improvement looks good.

The alignment of initialization fields maintains better consistency with the struct definition.


361-379:

✅ Verification successful

Verify that goroutine cleanup is properly handled.

The goroutine spawned here will continue running until it processes the message and sends any response. Ensure that it will properly terminate even if the session is closed during processing.


🏁 Script executed:

#!/bin/bash
# Check if there's proper handling of session termination in other goroutines
grep -A 10 "case <-session.done" server/sse.go

Length of output: 1046


🏁 Script executed:

#!/bin/bash
# Locate definition(s) of HandleMessage to inspect its signature
rg -n "HandleMessage" -C 2

Length of output: 7050


🏁 Script executed:

#!/bin/bash
# Display the surrounding context of the goroutine to see where ctx comes from
sed -n '300,420p' server/sse.go

Length of output: 3549


No goroutine leak – single‐run worker auto‑terminates

The anonymous goroutine in handleMessage only processes one request then returns:

  • It calls s.server.HandleMessage(ctx, rawMessage) once.
  • After that, the select on session.eventQueue includes both <-session.done (skips queuing) and a default case, so it never blocks indefinitely.
  • Once that select completes, the function exits and the goroutine is freed.

Because it’s not a long‐lived loop, there’s no need for additional cleanup.

@CeerDecy
Copy link
Author

@ezynda3 Okay, done!

@CeerDecy CeerDecy requested a review from ezynda3 April 21, 2025 03:21
server/sse.go Outdated
if response != nil {
eventData, err := json.Marshal(response)
if err != nil {
s.writeJSONRPCError(w, nil, mcp.INTERNAL_ERROR, "Fail to marshal response")
Copy link
Contributor

Choose a reason for hiding this comment

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

Better to just log this as we have already sent a response and doesn't really make sense write anymore to the response...

Copy link
Author

Choose a reason for hiding this comment

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

@ezynda3 Maybe I should have to return this error to sse, otherwise the client might not know if the execution was successful?

@CeerDecy CeerDecy requested a review from ezynda3 April 24, 2025 01:34
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
server/sse.go (1)

373-373: Minor: Unnecessary use of fmt.Sprintf for static string.

The static analysis tool flagged that using fmt.Sprintf here is unnecessary since there are no format specifiers.

-				message = fmt.Sprintf("event: message\ndata: {\"error\": \"internal error\",\"jsonrpc\": \"2.0\", \"id\": null}\n\n")
+				message = "event: message\ndata: {\"error\": \"internal error\",\"jsonrpc\": \"2.0\", \"id\": null}\n\n"
🧰 Tools
🪛 golangci-lint (1.64.8)

373-373: S1039: unnecessary use of fmt.Sprintf

(gosimple)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5bd00ad and cde2b2a.

📒 Files selected for processing (2)
  • server/sse.go (5 hunks)
  • server/sse_test.go (6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
server/sse.go (2)
server/server.go (1)
  • MCPServer (143-166)
examples/custom_context/main.go (1)
  • MCPServer (100-102)
🪛 golangci-lint (1.64.8)
server/sse_test.go

197-197: testinggoroutine: call to (*testing.T).Fatalf from a non-test goroutine

(govet)

server/sse.go

373-373: S1039: unnecessary use of fmt.Sprintf

(gosimple)

🔇 Additional comments (7)
server/sse.go (4)

7-7: Good: Added log package import for error handling.

Adding the log package import is necessary for the new error logging implemented in the handleMessage function.


57-65: Improved struct field alignment for better readability.

The consistent alignment of struct fields makes the code more readable.


162-167: Improved constructor field alignment consistent with struct definition.

The alignment in the constructor now matches the struct definition style.


385-386: Good: Added logging for queue full condition.

Properly logging the condition where the event queue is full helps with monitoring and debugging.

server/sse_test.go (3)

751-758: Good: Helper function to reduce code duplication.

The new readSeeEvent helper function improves code maintainability by extracting the common pattern of reading SSE events.


625-634: Good: Updated test to handle asynchronous SSE responses.

The code correctly reads and parses the SSE event data to validate the response, aligning with the changes in the main code.


672-682: Good: Consistent handling of SSE events across tests.

The code applies the same pattern for reading and parsing SSE events, maintaining consistency across the test suite.

server/sse.go Outdated
Comment on lines 359 to 389
// quick return request, send 202 Accepted with no body, then deal the message and sent response via SSE
w.WriteHeader(http.StatusAccepted)

// Only send response if there is one (not for notifications)
if response != nil {
eventData, _ := json.Marshal(response)
go func() {
// Process message through MCPServer
response := s.server.HandleMessage(ctx, rawMessage)

// Queue the event for sending via SSE
select {
case session.eventQueue <- fmt.Sprintf("event: message\ndata: %s\n\n", eventData):
// Event queued successfully
case <-session.done:
// Session is closed, don't try to queue
default:
// Queue is full, could log this
}
// Only send response if there is one (not for notifications)
if response != nil {
var message string
eventData, err := json.Marshal(response)
if err != nil {
// If there is an error marshalling the response, send a generic error response
log.Printf("failed to marshal response: %v", err)
message = fmt.Sprintf("event: message\ndata: {\"error\": \"internal error\",\"jsonrpc\": \"2.0\", \"id\": null}\n\n")
return
}
message = fmt.Sprintf("event: message\ndata: %s\n\n", eventData)

// Send HTTP response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(response)
} else {
// For notifications, just send 202 Accepted with no body
w.WriteHeader(http.StatusAccepted)
}
// Queue the event for sending via SSE
select {
case session.eventQueue <- message:
// Event queued successfully
case <-session.done:
// Session is closed, don't try to queue
default:
// Queue is full, log this situation
log.Printf("Event queue full for session %s", sessionID)
}
}
}()
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Good implementation of asynchronous message processing and quick response.

This change effectively decouples the HTTP response from the message processing cycle, improving responsiveness by immediately returning 202 Accepted and handling the message asynchronously via SSE. The implementation follows a common pattern for async processing in API handlers.

However, there's an issue with the error handling for JSON marshaling:

-			message = fmt.Sprintf("event: message\ndata: {\"error\": \"internal error\",\"jsonrpc\": \"2.0\", \"id\": null}\n\n")
-			return
+			log.Printf("failed to marshal response: %v", err)
+			return

The error message string is created but never used since the function returns immediately after logging the error.


🏁 Script executed:

#!/bin/bash
# Check if there are any other places where JSON marshaling errors are handled consistently
grep -A 5 "json\.Marshal" server/sse.go

Length of output: 726


Ensure error SSE frames are queued before returning

In server/sse.go around the json.Marshal(response) error block (lines ~365–371), you build an error message but return immediately, so the client never receives it. Update the error path to enqueue that message just like the success case:

 if err != nil {
     log.Printf("failed to marshal response: %v", err)
-    message = fmt.Sprintf("event: message\ndata: {\"error\": \"internal error\",\"jsonrpc\": \"2.0\", \"id\": null}\n\n")
-    return
+    message = fmt.Sprintf("event: message\ndata: {\"error\": \"internal error\",\"jsonrpc\": \"2.0\", \"id\": null}\n\n")
+    select {
+    case session.eventQueue <- message:
+        // Error event queued
+    case <-session.done:
+        // Session closed
+    default:
+        log.Printf("Event queue full for session %s", sessionID)
+    }
+    return
 }

This guarantees that clients get an SSE error frame when marshaling fails.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// quick return request, send 202 Accepted with no body, then deal the message and sent response via SSE
w.WriteHeader(http.StatusAccepted)
// Only send response if there is one (not for notifications)
if response != nil {
eventData, _ := json.Marshal(response)
go func() {
// Process message through MCPServer
response := s.server.HandleMessage(ctx, rawMessage)
// Queue the event for sending via SSE
select {
case session.eventQueue <- fmt.Sprintf("event: message\ndata: %s\n\n", eventData):
// Event queued successfully
case <-session.done:
// Session is closed, don't try to queue
default:
// Queue is full, could log this
}
// Only send response if there is one (not for notifications)
if response != nil {
var message string
eventData, err := json.Marshal(response)
if err != nil {
// If there is an error marshalling the response, send a generic error response
log.Printf("failed to marshal response: %v", err)
message = fmt.Sprintf("event: message\ndata: {\"error\": \"internal error\",\"jsonrpc\": \"2.0\", \"id\": null}\n\n")
return
}
message = fmt.Sprintf("event: message\ndata: %s\n\n", eventData)
// Send HTTP response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(response)
} else {
// For notifications, just send 202 Accepted with no body
w.WriteHeader(http.StatusAccepted)
}
// Queue the event for sending via SSE
select {
case session.eventQueue <- message:
// Event queued successfully
case <-session.done:
// Session is closed, don't try to queue
default:
// Queue is full, log this situation
log.Printf("Event queue full for session %s", sessionID)
}
}
}()
// quick return request, send 202 Accepted with no body, then deal the message and send response via SSE
w.WriteHeader(http.StatusAccepted)
go func() {
// Process message through MCPServer
response := s.server.HandleMessage(ctx, rawMessage)
// Only send response if there is one (not for notifications)
if response != nil {
var message string
eventData, err := json.Marshal(response)
if err != nil {
// If there is an error marshalling the response, send a generic error response
log.Printf("failed to marshal response: %v", err)
message = fmt.Sprintf("event: message\ndata: {\"error\": \"internal error\",\"jsonrpc\": \"2.0\", \"id\": null}\n\n")
select {
case session.eventQueue <- message:
// Error event queued
case <-session.done:
// Session closed
default:
log.Printf("Event queue full for session %s", sessionID)
}
return
}
message = fmt.Sprintf("event: message\ndata: %s\n\n", eventData)
// Queue the event for sending via SSE
select {
case session.eventQueue <- message:
// Event queued successfully
case <-session.done:
// Session is closed, don't try to queue
default:
// Queue is full, log this situation
log.Printf("Event queue full for session %s", sessionID)
}
}
}()
🧰 Tools
🪛 golangci-lint (1.64.8)

373-373: S1039: unnecessary use of fmt.Sprintf

(gosimple)

Comment on lines +195 to +205
endpointEvent, err = readSeeEvent(sseResp)
if err != nil {
t.Fatalf("Failed to read SSE response: %v", err)
}
respFromSee := strings.TrimSpace(
strings.Split(strings.Split(endpointEvent, "data: ")[1], "\n")[0],
)

fmt.Printf("========> %v", respFromSee)
var response map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
if err := json.NewDecoder(strings.NewReader(respFromSee)).Decode(&response); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix: Testing function called from goroutine.

The static analysis tool flagged that t.Fatalf is being called from a non-test goroutine, which can lead to race conditions or panics in the test framework.

-					t.Fatalf("Failed to read SSE response: %v", err)
+					t.Errorf("Session %d: Failed to read SSE response: %v", sessionNum, err)
+					return

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 golangci-lint (1.64.8)

197-197: testinggoroutine: call to (*testing.T).Fatalf from a non-test goroutine

(govet)

@CeerDecy CeerDecy force-pushed the feature/request-timeout branch from cde2b2a to 73d36a9 Compare April 29, 2025 01:25
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
server/sse.go (1)

359-389: ⚠️ Potential issue

Critical error: Error message isn't being sent to the client when JSON marshaling fails.

The implementation successfully decouples the HTTP response from message processing, improving responsiveness by returning 202 Accepted immediately and processing messages asynchronously. However, there's a critical issue in the error handling path that needs to be fixed.

When JSON marshaling fails, you're creating an error message but returning from the goroutine immediately without sending it to the client. This means clients won't receive any notification when this error occurs.

if eventData, err := json.Marshal(response); err != nil {
    // If there is an error marshalling the response, send a generic error response
    log.Printf("failed to marshal response: %v", err)
    message = fmt.Sprintf("event: message\ndata: {\"error\": \"internal error\",\"jsonrpc\": \"2.0\", \"id\": null}\n\n")
-   return
+   // Queue the error event for sending via SSE
+   select {
+   case session.eventQueue <- message:
+       // Error event queued successfully
+   case <-session.done:
+       // Session is closed, don't try to queue
+   default:
+       // Queue is full, log this situation
+       log.Printf("Event queue full for session %s", sessionID)
+   }
+   return
} else {
    message = fmt.Sprintf("event: message\ndata: %s\n\n", eventData)
}

Also, as noted by the static analysis tool, the error message can be simplified:

-message = fmt.Sprintf("event: message\ndata: {\"error\": \"internal error\",\"jsonrpc\": \"2.0\", \"id\": null}\n\n")
+message = "event: message\ndata: {\"error\": \"internal error\",\"jsonrpc\": \"2.0\", \"id\": null}\n\n"
🧰 Tools
🪛 golangci-lint (1.64.8)

372-372: S1039: unnecessary use of fmt.Sprintf

(gosimple)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cde2b2a and 73d36a9.

📒 Files selected for processing (2)
  • server/sse.go (5 hunks)
  • server/sse_test.go (6 hunks)
🧰 Additional context used
🪛 golangci-lint (1.64.8)
server/sse_test.go

197-197: testinggoroutine: call to (*testing.T).Fatalf from a non-test goroutine

(govet)

server/sse.go

372-372: S1039: unnecessary use of fmt.Sprintf

(gosimple)

🔇 Additional comments (4)
server/sse.go (3)

7-7: Appropriate addition of the log package.

The log package is correctly imported to support the new logging functionality introduced in the handleMessage function.


57-65: Improved struct field alignment.

The struct fields have been reorganized with consistent alignment, improving code readability.


162-167: Consistent struct field formatting.

The struct field initialization formatting is now consistent with the struct declaration, enhancing maintainability.

server/sse_test.go (1)

751-758: Good implementation of helper function for reading SSE events.

The readSeeEvent function is a clean abstraction that centralizes the logic for reading from SSE response bodies, reducing code duplication across tests.

@@ -59,13 +59,10 @@ func TestSSEServer(t *testing.T) {
defer sseResp.Body.Close()

// Read the endpoint event
buf := make([]byte, 1024)
n, err := sseResp.Body.Read(buf)
endpointEvent, err := readSeeEvent(sseResp)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix test code to accommodate asynchronous response delivery.

The test code has been properly adapted to read and process responses from SSE events instead of directly from HTTP response bodies, which aligns with the server-side changes. However, there's a critical issue with using t.Fatalf in a goroutine.

Using t.Fatalf from a non-test goroutine (line 197) can cause race conditions or panics in the test framework. This was previously flagged in code reviews but hasn't been fixed.

endpointEvent, err = readSeeEvent(sseResp)
if err != nil {
-   t.Fatalf("Failed to read SSE response: %v", err)
+   t.Errorf("Session %d: Failed to read SSE response: %v", sessionNum, err)
+   return
}

Apply this fix to all instances of t.Fatalf used in goroutines in this file.

Also applies to: 195-204, 582-632, 672-682

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants