Skip to content

fix java mcp message endpoint #75

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

Merged
merged 3 commits into from
Apr 3, 2025
Merged

Conversation

a67793581
Copy link
Contributor

@a67793581 a67793581 commented Mar 26, 2025

Because the implementation of java mcp sdk does not handle the problem of messageEndpoint returning CompleteMessageEndpoint URI when splicing messageEndpoint and base URL, it simply splices, resulting in the phenomenon of http://localhost/mcphttp://localhost/mcp/message.
In order to be compatible with it, I added a new parameter and kept the original logic unchanged to avoid affecting users who are already using it.

Here are the references:

https://github.com/modelcontextprotocol/java-sdk/releases/tag/v0.8.1

public Mono<Void> sendMessage(McpSchema.JSONRPCMessage message) {
    if (this.isClosing) {
        return Mono.empty();
    } else {
        try {
            if (!this.closeLatch.await(10L, TimeUnit.SECONDS)) {
                return Mono.error(new McpError("Failed to wait for the message endpoint"));
            }
        } catch (InterruptedException var5) {
            return Mono.error(new McpError("Failed to wait for the message endpoint"));
        }

        String endpoint = (String)this.messageEndpoint.get();
        if (endpoint == null) {
            return Mono.error(new McpError("No message endpoint available"));
        } else {
            try {
                String jsonText = this.objectMapper.writeValueAsString(message);
                HttpRequest request = HttpRequest.newBuilder().uri(URI.create(this.baseUri + endpoint)).header("Content-Type", "application/json").POST(BodyPublishers.ofString(jsonText)).build();
                return Mono.fromFuture(this.httpClient.sendAsync(request, BodyHandlers.discarding()).thenAccept((response) -> {
                    if (response.statusCode() != 200 && response.statusCode() != 201 && response.statusCode() != 202 && response.statusCode() != 206) {
                        logger.error("Error sending message: {}", response.statusCode());
                    }

                }));
            } catch (IOException var6) {
                return !this.isClosing ? Mono.error(new RuntimeException("Failed to serialize message", var6)) : Mono.empty();
            }
        }
    }
}

Summary by CodeRabbit

  • New Features
    • Enhanced server event handling with a flexible configuration option that now toggles between complete and standard message endpoints.
    • This update delivers more consistent and reliable server responses during event initialization and message processing.
  • Tests
    • Introduced new test cases to validate the behavior of the SSE endpoint and the configuration of the message endpoint URL, ensuring expected responses and functionality.

Copy link
Contributor

coderabbitai bot commented Mar 26, 2025

Walkthrough

The pull request introduces a new boolean field, useFullURLForMessageEndpoint, to the SSEServer struct, along with a configuration function WithUseFullURLForMessageEndpoint. The handleSSE method is modified to generate the message endpoint based on this field's value. Additionally, new test cases are added in server/sse_test.go to validate the behavior of the SSE endpoint, ensuring correct HTTP response codes and proper integration of the new configuration parameter.

Changes

Files Change Summary
server/sse.go, server/sse_test.go - Added a new boolean field useFullURLForMessageEndpoint to the SSEServer struct and the WithUseFullURLForMessageEndpoint configuration function.
- Updated the handleSSE method to conditionally select between CompleteMessageEndpoint() and a custom message endpoint based on the flag.
- Introduced new test cases to validate this behavior.

Possibly related PRs

  • fix SSEOption #63: The changes in this PR are related to modifications in the SSEServer struct and its methods, particularly the CompleteMessageEndpoint method.
  • Expose SSE server as HttpHandler #29: The changes in this PR enhance the SSEServer by adding the ServeHTTP method, which is directly related to the new boolean field and methods for handling message endpoints introduced in the main PR.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 38225de and c6f4e76.

📒 Files selected for processing (1)
  • server/sse.go (5 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
server/sse.go (2)
server/server.go (1)
  • MCPServer (138-152)
examples/custom_context/main.go (1)
  • MCPServer (100-102)
🔇 Additional comments (5)
server/sse.go (5)

59-59: Good addition of a configurable flag for URL handling

This new boolean field gives clients control over how the message endpoint URL is constructed, addressing the malformed URL issue mentioned in the PR objectives while maintaining backward compatibility.


110-117: Well-documented configuration option

The function is well-documented with clear explanation of the purpose and use case. The comment effectively communicates when to set this option to false, specifically for clients that handle URL concatenation themselves.


147-147: Good default for backward compatibility

Setting useFullURLForMessageEndpoint to true by default ensures backward compatibility for existing users while allowing new users to opt into the fixed behavior.


259-259: Appropriate refactoring of endpoint URL generation

The change properly delegates message endpoint URL construction to the new GetMessageEndpointForClient method, making the code more maintainable and centralizing the URL generation logic.


276-284:

❓ Verification inconclusive

Well-implemented endpoint URL generation

This new method encapsulates the logic for constructing the message endpoint URL based on configuration. The implementation correctly handles both full URL and path-only cases, fixing the issue with malformed URLs while maintaining the session ID parameter.

Consider adding a brief test to verify that the endpoint URL is correctly formatted in both configurations.


🏁 Script executed:

#!/bin/bash
# Check if tests for this new functionality exist
rg -A 5 "useFullURLForMessageEndpoint" --type go server/sse_test.go

Length of output: 1187


Endpoint URL Generation: Well Implemented, with a Suggestion for Expanded Testing

The logic in server/sse.go correctly constructs the endpoint URL based on the configuration, ensuring that the session ID is appended appropriately. The tests in server/sse_test.go already verify the useFullURLForMessageEndpoint flag; however, there isn’t a dedicated test confirming that the final URL string returned by GetMessageEndpointForClient is formatted as expected in both configuration cases.

Please consider adding a test case (or cases) that:

  • Calls GetMessageEndpointForClient with a sample session ID when useFullURLForMessageEndpoint is both true and false.
  • Asserts that the returned URL string matches the expected format, including the proper endpoint structure and query parameter.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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: 0

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

110-115: Enhance documentation for the WithIsCompleteMessageEndpoint function.

The current comment is brief and doesn't fully explain the purpose of this configuration option. Consider adding more context about why this option exists and when it should be used.

-// WithIsCompleteMessageEndpoint sets the flag for whether the endpoint is for complete messages or not
+// WithIsCompleteMessageEndpoint controls whether the SSE server returns a complete URL (including baseURL) 
+// or just the path portion for the message endpoint. Set to false when clients will concatenate
+// the baseURL themselves to avoid malformed URLs like "http://localhost/mcphttp://localhost/mcp/message".

256-260: Well-implemented conditional logic for message endpoint construction.

The implementation correctly uses either the complete URL or just the path based on the isCompleteMessageEndpoint flag. This effectively addresses the issue with Java MCP SDK creating malformed URLs.

Consider adding a brief comment to explain the purpose of this conditional logic:

 messageEndpoint := s.messageEndpoint
+// Use either just the path or the complete URL based on configuration.
+// This prevents issues with clients that concatenate the base URL themselves.
 if s.isCompleteMessageEndpoint {
     messageEndpoint = s.CompleteMessageEndpoint()
 }
 messageEndpoint = fmt.Sprintf("%s?sessionId=%s", messageEndpoint, sessionID)

58-60: Consider a more descriptive field name.

While isCompleteMessageEndpoint works, a more descriptive name like useFullURLForMessageEndpoint might better communicate its purpose, as it controls whether to use the full URL (including base URL) or just the path portion.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d3dc35c and 14151a0.

📒 Files selected for processing (2)
  • server/sse.go (4 hunks)
  • server/sse_test.go (3 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
server/sse.go (2)
server/server.go (1)
  • MCPServer (138-152)
examples/custom_context/main.go (1)
  • MCPServer (100-102)
🔇 Additional comments (4)
server/sse_test.go (2)

421-494: Good implementation of test case for the new isCompleteMessageEndpoint behavior.

This test case effectively verifies the behavior when isCompleteMessageEndpoint is set to false. The test properly configures the server, makes the SSE connection, and then verifies that the message URL starts with the expected message endpoint. It also correctly demonstrates how to use the message URL by prepending the base URL when making the POST request.


699-723: Well-done consistency check for the new configuration option.

The addition of isCompleteMessageEndpoint to the random options test ensures that this new configuration option is properly applied and maintains consistency when used alongside other options. This helps prevent regressions when multiple configuration options are used together.

server/sse.go (2)

59-59: Appropriate addition of isCompleteMessageEndpoint field to the SSEServer struct.

The new field addresses the issue mentioned in the PR objectives where the Java MCP SDK was creating malformed URLs by concatenating the base URL with a message endpoint that already included a full URL.


145-145: Good default value for backward compatibility.

Setting isCompleteMessageEndpoint to true by default ensures backward compatibility with existing clients, which is important for a fix like this.

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: 0

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

257-263: Correct implementation of the URL generation logic

The conditional logic correctly implements the feature toggle, using either the complete URL or just the path based on the configuration. This effectively solves the issue mentioned in the PR objectives where Java clients were experiencing malformed URLs.

Consider creating a helper method that encapsulates this logic, such as GetMessageEndpointForClient(sessionID string) string, which could be reused elsewhere if needed.

+// GetMessageEndpointForClient returns the appropriate message endpoint URL with session ID
+// based on the useFullURLForMessageEndpoint configuration.
+func (s *SSEServer) GetMessageEndpointForClient(sessionID string) string {
+    messageEndpoint := s.messageEndpoint
+    if s.useFullURLForMessageEndpoint {
+        messageEndpoint = s.CompleteMessageEndpoint()
+    }
+    return fmt.Sprintf("%s?sessionId=%s", messageEndpoint, sessionID)
+}

And then update the handleSSE method to use it:

-// Use either just the path or the complete URL based on configuration.
-// This prevents issues with clients that concatenate the base URL themselves.
-messageEndpoint := s.messageEndpoint
-if s.useFullURLForMessageEndpoint {
-    messageEndpoint = s.CompleteMessageEndpoint()
-}
-messageEndpoint = fmt.Sprintf("%s?sessionId=%s", messageEndpoint, sessionID)
+messageEndpoint := s.GetMessageEndpointForClient(sessionID)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 14151a0 and 38225de.

📒 Files selected for processing (2)
  • server/sse.go (4 hunks)
  • server/sse_test.go (3 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
server/sse_test.go (2)
server/server.go (1)
  • NewMCPServer (326-352)
server/sse.go (3)
  • NewSSEServer (142-156)
  • SSEOption (67-67)
  • WithUseFullURLForMessageEndpoint (113-117)
🔇 Additional comments (5)
server/sse.go (3)

59-59: Good addition of the useFullURLForMessageEndpoint field

This new field provides a clean solution to the Java MCP SDK issue mentioned in the PR objectives, allowing clients to control whether they receive a full URL or just the path.


110-117: Well-documented configuration option

The comment clearly explains the purpose of this option and provides a good example of the issue it solves. The implementation follows the same pattern as other SSEOption functions, maintaining consistency.


147-147: Appropriate default value for backward compatibility

Setting useFullURLForMessageEndpoint to true by default ensures backward compatibility with existing clients, which is a good approach for introducing this new parameter.

server/sse_test.go (2)

421-494: Good test coverage for the new feature

The test case effectively validates the behavior when useFullURLForMessageEndpoint is set to false. It properly checks that:

  1. The SSE connection works
  2. The message endpoint URL is correctly formatted without the full URL
  3. The client can successfully post to the endpoint by concatenating the base URL

This test ensures the feature works as expected for Java MCP SDK users.


699-700: Comprehensive test for option consistency

The existing test for SSEOption consistency has been appropriately updated to include the new option. This ensures that the option behaves correctly when applied multiple times in different orders.

Also applies to: 705-705, 721-723

@ezynda3 ezynda3 merged commit 6d840a4 into mark3labs:main Apr 3, 2025
2 checks passed
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