Skip to content

feat(server/sse): Add support for dynamic base paths #214

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 1 commit into
base: main
Choose a base branch
from

Conversation

robert-jackson-glean
Copy link
Contributor

@robert-jackson-glean robert-jackson-glean commented Apr 27, 2025

This change introduces the ability to mount SSE endpoints at dynamic paths with variable segments (e.g., /api/{tenant}/sse) by adding a new WithDynamicBasePath option and related functionality. This enables advanced use cases such as multi-tenant architectures or integration with routers that support path parameters.

Key Features:

  • DynamicBasePathFunc: New function type and option (WithDynamicBasePath) to generate the SSE server's base path dynamically per request/session.
  • Flexible Routing: New SSEHandler() and MessageHandler() methods allow mounting handlers at arbitrary or dynamic paths using any router (e.g., net/http, chi, gorilla/mux).
  • Endpoint Generation: GetMessageEndpointForClient now supports both static and dynamic path modes, and correctly generates full URLs when configured.
  • Example: Added examples/dynamic_path/main.go demonstrating dynamic path mounting and usage.
mcpServer := mcp.NewMCPServer("dynamic-path-example", "1.0.0")
sseServer := mcp.NewSSEServer(
  mcpServer,
  mcp.WithDynamicBasePath(func(r *http.Request, sessionID string) string {
    tenant := r.PathValue("tenant")
    return "/api/" + tenant
  }),
  mcp.WithBaseURL("http://localhost:8080"),
)

mux := http.NewServeMux()
mux.Handle("/api/{tenant}/sse", sseServer.SSEHandler())
mux.Handle("/api/{tenant}/message", sseServer.MessageHandler())

This is an alternate to #121, the key differences are:

  1. The route parsing is independent of mcp-go and can be done by whatever system the host server already uses (e.g. net/http, gorilla/mux, chi, &c).
  2. This will work well along with Manage tools on a per session basis #179, using a custom session that can be aware of any custom route params and whatnot that might be needed throughout the rest of the system (e.g. in the tool handlers).

Summary by CodeRabbit

  • New Features

    • Added support for dynamic base paths in the SSE server, enabling per-request routing and multi-tenant scenarios.
    • Introduced new handlers for advanced dynamic routing configurations.
    • Provided a new example demonstrating dynamic base path handling with an HTTP server and echo tool.
  • Bug Fixes

    • Improved error handling to prevent incorrect usage when dynamic base paths are enabled.
  • Tests

    • Added comprehensive tests to verify dynamic base path functionality, URL construction, and correct error handling.

Copy link
Contributor

coderabbitai bot commented Apr 27, 2025

Walkthrough

This change introduces dynamic base path support for the SSE server in the mcp-go framework. A new mechanism allows the SSE server's base path to be computed per request using a user-defined function, facilitating multi-tenant or dynamically routed scenarios. The server exposes new handler methods for integration with HTTP routers, and enforces correct usage patterns by panicking if static methods are used in dynamic mode. The example and test suite are updated to demonstrate and verify dynamic path handling, including correct endpoint URL generation and error conditions.

Changes

Files/Paths Change Summary
examples/dynamic_path/main.go Added a new example program showing how to set up an HTTP server with dynamic base path handling for SSE, including dynamic routing based on a tenant path segment.
server/sse.go Extended SSE server to support dynamic base path computation via a user-provided function, added new handler methods (SSEHandler, MessageHandler) for router integration, updated endpoint URL generation to use dynamic base paths, and enforced correct usage with panics for incompatible methods (ServeHTTP, CompleteSseEndpoint, CompleteMessageEndpoint).
server/sse_test.go Added tests covering dynamic base path scenarios, endpoint URL correctness, error conditions for improper usage, and integration with router-based mounting; improved SSE event reading logic in tests for complete event capture.

Possibly related PRs

  • mark3labs/mcp-go#29: Originally introduced the ServeHTTP method for the SSE server; this PR directly modifies and extends that method to support dynamic base paths.

📜 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 a643f22 and 86cebe8.

📒 Files selected for processing (3)
  • examples/dynamic_path/main.go (1 hunks)
  • server/sse.go (9 hunks)
  • server/sse_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/dynamic_path/main.go
  • server/sse_test.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
server/sse.go (1)
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
🔇 Additional comments (8)
server/sse.go (8)

36-41: Well-designed API for dynamic path support

The new DynamicBasePathFunc type is well-documented and provides a clean interface for dynamic path generation. The function signature includes both the request and sessionID, giving implementers the flexibility they need to extract path parameters or other routing information.


124-136: Excellent path sanitization implementation

I appreciate the robust path sanitization in WithDynamicBasePath that ensures paths have a leading slash and no trailing slash. This prevents double slashes in URL construction and aligns with the prior learning feedback on this PR.


362-374: LGTM: Elegant handling of both static and dynamic paths

The updated GetMessageEndpointForClient method provides a clean interface that works transparently with both static and dynamic path modes. The implementation is straightforward but effective.


485-488: Good fail-fast approach with clear error message

The panic with a specific error message provides immediate feedback to developers who might be mixing incompatible modes of operation. This helps prevent subtle errors and guides users toward the correct usage patterns.


501-503: Consistent error handling across static methods

The error message is consistent with the pattern established in CompleteSseEndpoint, maintaining a cohesive developer experience.


515-542: Well-documented SSEHandler with clear examples

The new SSEHandler method has excellent documentation that clearly explains its purpose and provides a concrete example of usage with dynamic paths. The IMPORTANT notice about requiring WithDynamicBasePath is particularly helpful for preventing incorrect configurations.


544-571: Consistent documentation between handler methods

The MessageHandler documentation follows the same pattern as SSEHandler, providing a consistent developer experience. The example showing both handlers being used together is particularly helpful.


575-577: Clear enforcement of separation between static and dynamic modes

The panic in ServeHTTP completes the enforcement of separation between static and dynamic path usage modes, ensuring that users follow the correct patterns depending on their chosen configuration.

✨ 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: 4

🧹 Nitpick comments (7)
examples/dynamic_path/main.go (2)

26-35: Avoid hard-coding the outbound baseURL – derive it from the chosen listen address instead

WithBaseURL("http://localhost:8080") will break if the user changes the -addr flag (:9090, 0.0.0.0:8081, etc.).
Deriving the value once the flag is parsed prevents “wrong endpoint” bugs in copy-pasted examples.

-    server.WithBaseURL("http://localhost:8080"),
+    server.WithBaseURL(fmt.Sprintf("http://localhost%s", addr)),

(If TLS might be enabled in the future, you could inspect addr or add a separate -base-url flag.)


38-40: Router pattern requires Go 1.22 – add a build tag or explicit comment

ServeMux patterns that contain {tenant} only compile/run on Go 1.22+.
A short doc-comment or a //go:build go1.22 guard will save users on earlier versions from a confusing 404.

server/sse.go (3)

331-333: Ensure the initial endpoint event always ends with \n\n

fmt.Fprintf(w, "event: endpoint\ndata: %s\r\n\r\n", endpoint) mixes \r\n and \n.
For consistency with the rest of the stream (eventQueue uses \n\n), prefer \n\n. No functional bug but helps downstream parsers.

- fmt.Fprintf(w, "event: endpoint\ndata: %s\r\n\r\n", endpoint)
+ fmt.Fprintf(w, "event: endpoint\ndata: %s\n\n", endpoint)

478-483: Return errors instead of panicking for library callers

panic here abruptly terminates the program if library users accidentally call the wrong helper.
A safer API is to return an explicit error so callers can decide.

-func (s *SSEServer) CompleteSseEndpoint() string {
-    if s.dynamicBasePathFunc != nil {
-        panic("CompleteSseEndpoint cannot be used with WithDynamicBasePath. Use dynamic path logic in your router.")
-    }
-    return s.baseURL + s.basePath + s.sseEndpoint
-}
+func (s *SSEServer) CompleteSseEndpoint() (string, error) {
+    if s.dynamicBasePathFunc != nil {
+        return "", fmt.Errorf("CompleteSseEndpoint cannot be used together with WithDynamicBasePath")
+    }
+    return s.baseURL + s.basePath + s.sseEndpoint, nil
+}

(Change callers accordingly.)
Panics are still appropriate inside tests, but exported APIs should favour explicit errors.


567-569: ServeHTTP panic could be downgraded to 500 for robustness

If someone accidentally wires the whole server under a dynamic path, the entire process panics. Returning http.StatusInternalServerError (or a log + 500) avoids bringing down shared servers.

server/sse_test.go (2)

946-968: SSEHandlerRequiresDynamicBasePath silently ignores earlier panic expectation

The first two calls (_ = sseServer.SSEHandler()) should be wrapped in require.NotPanics to document the intention; otherwise a panic would skip the rest of the test and the later recover logic never triggers, leading to false positives.


1009-1044: Duplicate code for static vs dynamic endpoint assertions – factor helper

Four almost-identical blocks differ only by constructor options. Extracting a table-driven sub-test improves readability and future maintenance.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 33c98f1 and 887b314.

📒 Files selected for processing (3)
  • examples/dynamic_path/main.go (1 hunks)
  • server/sse.go (9 hunks)
  • server/sse_test.go (1 hunks)

@robert-jackson-glean robert-jackson-glean force-pushed the rwjblue/push-ysoppsqxnkmy branch from 887b314 to 15e1a5e Compare April 28, 2025 00:10
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

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

453-469: Improved SSE frame reading with buffered reader loop

Excellent change that addresses the previous review feedback about potential truncation issues. Using a buffered reader loop ensures the complete SSE frame is captured reliably, even on slower systems where the frame might be split across multiple TCP packets.

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

982-1020: Replace simple buffer read with buffered reader for consistency

While this test case correctly verifies dynamic base path with full URL configuration, it uses a simple buffered read instead of the more robust buffered reader loop introduced earlier in the file.

Consider replacing the simple buffer read with a buffered reader loop for consistency and to prevent potential SSE frame truncation issues:

-		buf := make([]byte, 1024)
-		n, err := resp.Body.Read(buf)
-		if err != nil {
-			t.Fatalf("Failed to read SSE response: %v", err)
-		}
-		endpointEvent := string(buf[:n])
+		reader := bufio.NewReader(resp.Body)
+		var endpointEvent strings.Builder
+		for {
+			line, err := reader.ReadString('\n')
+			if err != nil {
+				t.Fatalf("Failed to read SSE response: %v", err)
+			}
+			endpointEvent.WriteString(line)
+			if line == "\n" || line == "\r\n" {
+				break // End of SSE frame
+			}
+		}
+		endpointEventStr := endpointEvent.String()

Then update the subsequent code to use endpointEventStr instead of endpointEvent.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 887b314 and 15e1a5e.

📒 Files selected for processing (3)
  • examples/dynamic_path/main.go (1 hunks)
  • server/sse.go (9 hunks)
  • server/sse_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/dynamic_path/main.go
  • server/sse.go
🔇 Additional comments (4)
server/sse_test.go (4)

865-957: Well-structured test for dynamic path mounting

This test case thoroughly verifies the new dynamic base path functionality, correctly testing both the SSE endpoint connection and JSON-RPC message communication with tenant-specific paths.

Note that the test uses Go 1.22+ PathValue() function, which should be mentioned in documentation as a dependency requirement.


958-980: Important safety check for dynamic path configuration

Good test ensuring that the API enforces correct usage patterns - SSEHandler and MessageHandler work correctly in both modes, while ServeHTTP properly panics when configured with dynamic paths to prevent misuse.


1022-1057: Comprehensive URL generation test for all configuration combinations

Great test case that verifies the URL generation logic for all combinations of static vs dynamic paths, with and without base URL, and with full URL usage enabled or disabled. This ensures consistent behavior across all configuration patterns.


1059-1070: Important API contract enforcement

Good test verifying that CompleteSseEndpoint correctly panics when used with dynamic base paths, enforcing the API contract and preventing misuse.

@robert-jackson-glean robert-jackson-glean force-pushed the rwjblue/push-ysoppsqxnkmy branch from 15e1a5e to 252d7d8 Compare April 28, 2025 00: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: 0

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

368-371: Potential edge case in path concatenation

While path sanitization in WithDynamicBasePath prevents most issues, the direct concatenation of basePath + s.messageEndpoint might still produce unexpected results if s.messageEndpoint doesn't begin with a slash.

Consider using a more robust path joining approach:

-	endpointPath := basePath + s.messageEndpoint
+	// Ensure messageEndpoint starts with a slash for proper concatenation
+	messageEndpoint := s.messageEndpoint
+	if !strings.HasPrefix(messageEndpoint, "/") {
+		messageEndpoint = "/" + messageEndpoint
+	}
+	endpointPath := basePath + messageEndpoint
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 15e1a5e and 252d7d8.

📒 Files selected for processing (3)
  • examples/dynamic_path/main.go (1 hunks)
  • server/sse.go (9 hunks)
  • server/sse_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/dynamic_path/main.go
  • server/sse_test.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
server/sse.go (1)
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
🔇 Additional comments (9)
server/sse.go (9)

36-41: Well-defined type for dynamic base path handling

The new DynamicBasePathFunc type is clearly documented and serves an important purpose in enabling multi-tenant and dynamic routing scenarios.


79-80: LGTM - Clear field documentation

The field comment clearly explains the purpose of this function pointer for determining dynamic base paths.


120-136: Good implementation with path sanitization

The implementation of WithDynamicBasePath is robust with proper path sanitization that ensures consistent path formats (adding leading slash when missing and removing trailing slashes). This prevents URL construction issues.


359-374: Clean implementation of dynamic path support in endpoint generation

The updated GetMessageEndpointForClient method properly handles both static and dynamic base paths with a clear implementation. The method intelligently applies the dynamic base path function when available.


485-488: Good defensive programming with clear error guidance

The panic with a clear error message helps prevent misuse of the API by enforcing the correct usage pattern when using dynamic base paths.


501-503: Consistent API enforcement pattern

Consistent with the implementation in CompleteSseEndpoint, ensuring that these methods can't be misused with dynamic base paths.


515-571: Excellent handler abstractions with comprehensive documentation

The new SSEHandler and MessageHandler methods are well-designed and thoroughly documented with example usage. They provide clean abstractions for integrating with various HTTP routers and supporting dynamic path segments.


575-577: Strong API consistency enforcement

The panic in ServeHTTP properly prevents API misuse and clearly guides users toward the correct approach for dynamic path scenarios.


339-340: LGTM - Updated handleSSE to support dynamic paths

Properly updated to pass the request to GetMessageEndpointForClient, enabling dynamic base path resolution.

@robert-jackson-glean robert-jackson-glean force-pushed the rwjblue/push-ysoppsqxnkmy branch from 252d7d8 to a643f22 Compare April 28, 2025 00:37
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)

364-366: Consider additional validation for dynamic path usage

While you check if dynamicBasePathFunc is non-nil, there's no validation that the returned path is non-empty. An empty path could lead to URL construction issues.

 if s.dynamicBasePathFunc != nil {
     basePath = s.dynamicBasePathFunc(r, sessionID)
+    if basePath == "" {
+        // Log warning or use default
+        basePath = "/"
+    }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 252d7d8 and a643f22.

📒 Files selected for processing (3)
  • examples/dynamic_path/main.go (1 hunks)
  • server/sse.go (9 hunks)
  • server/sse_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/dynamic_path/main.go
  • server/sse_test.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
server/sse.go (1)
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
🔇 Additional comments (8)
server/sse.go (8)

36-41: Well-documented type for dynamic base path generation

Good definition with clear documentation explaining the purpose and expected behavior of the function type.


79-81: Clean field addition with descriptive comment

The new field for storing the dynamic base path function is well-commented and properly placed in the struct.


120-136: Excellent path sanitization implementation

The implementation correctly normalizes paths by ensuring they start with a slash and don't end with one, preventing potential URL construction issues. This is consistent with the learning from a previous review about preventing double slashes.


359-374: Clean implementation of dynamic endpoint generation

The method correctly handles both static and dynamic paths, with proper fallback and consistent URL construction. The implementation is straightforward and maintains backward compatibility.


485-489: Good enforcement of usage patterns

Appropriate panic messages when attempting to use static methods with dynamic paths, guiding users toward the correct pattern. This helps prevent subtle bugs that could arise from mixing the two approaches.

Also applies to: 501-504


515-542: Well-documented handler for SSE endpoint

The SSEHandler method has excellent documentation with clear examples that show how to use it with dynamic paths. The examples are particularly helpful for showing the integration with routers.


544-571: Well-documented handler for message endpoint

Similar to the SSE handler, the documentation is thorough with relevant examples. The consistent approach between both handlers makes the API intuitive to use.


575-577: Clear enforcement of the correct usage pattern

The panic message explicitly directs users to the appropriate methods for dynamic path scenarios, preventing misuse of the API.

This change introduces the ability to mount SSE endpoints at dynamic
paths with variable segments (e.g., `/api/{tenant}/sse`) by adding a new
`WithDynamicBasePath` option and related functionality. This enables
advanced use cases such as multi-tenant architectures or integration
with routers that support path parameters.

Key Features:

* DynamicBasePathFunc: New function type and option
  (WithDynamicBasePath) to generate the SSE server's base path
  dynamically per request/session.
* Flexible Routing: New SSEHandler() and MessageHandler() methods allow
  mounting handlers at arbitrary or dynamic paths using any router
  (e.g., net/http, chi, gorilla/mux).
* Endpoint Generation: GetMessageEndpointForClient now supports both
  static and dynamic path modes, and correctly generates full URLs when
  configured.
* Example: Added examples/dynamic_path/main.go demonstrating dynamic
  path mounting and usage.

```go
mcpServer := mcp.NewMCPServer("dynamic-path-example", "1.0.0")
sseServer := mcp.NewSSEServer(
  mcpServer,
  mcp.WithDynamicBasePath(func(r *http.Request, sessionID string) string {
    tenant := r.PathValue("tenant")
    return "/api/" + tenant
  }),
  mcp.WithBaseURL("http://localhost:8080"),
)

mux := http.NewServeMux()
mux.Handle("/api/{tenant}/sse", sseServer.SSEHandler())
mux.Handle("/api/{tenant}/message", sseServer.MessageHandler())
```
@robert-jackson-glean robert-jackson-glean force-pushed the rwjblue/push-ysoppsqxnkmy branch from a643f22 to 86cebe8 Compare April 28, 2025 01:20
@@ -447,6 +483,9 @@ func (s *SSEServer) GetUrlPath(input string) (string, error) {
}

func (s *SSEServer) CompleteSseEndpoint() string {
if s.dynamicBasePathFunc != nil {
panic("CompleteSseEndpoint cannot be used with WithDynamicBasePath. Use dynamic path logic in your router.")

Choose a reason for hiding this comment

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

Curious what the runtime implications of a panic are here. Specifically, if the DynamicBasePathFunc is not implemented correctly (e.g., returning invalid paths or omitting required segments), it could lead to broken endpoints or runtime errors. Do we think that's the correct approach?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good point! The spirit of what I'm going for here is basically to error early and loudly if you've misconfigured things with this new feature, but I totally agree that intentionally panicking may not be the best approach for consumers.

I'll update each of the panic scenarios that I added to instead follow the standard go error pattern.

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