mcp-go icon indicating copy to clipboard operation
mcp-go copied to clipboard

feat(sse): Add support for dynamic route parameters in SSE server

Open anhao opened this issue 8 months ago β€’ 9 comments

Description

This PR adds support for dynamic route parameters in the SSE server, similar to the routing parameters in the Gin framework. This enhancement allows users to define custom route patterns with parameters (e.g., /:channel/sse) and access these parameters in their message handlers.

Changes

  • Added WithSSEPattern option to configure custom route patterns
  • Implemented route parameter parsing and matching logic
  • Added route parameters context handling in SSE sessions
  • Added support for accessing route parameters in message handlers
  • Added comprehensive test cases for route parameter functionality

Example Usage

// Create SSE server with custom route pattern
sseServer := server.NewSSEServer(mcpServer,
    server.WithSSEPattern("/:channel/sse"),
    server.WithSSEContextFunc(customContextFunc),
)

// Access route parameters in message handlers
func messageHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
    channel := server.GetRouteParam(ctx, "channel")
    // Use the channel parameter...
}

Summary by CodeRabbit

  • New Features

    • Introduced a server-sent events system with dynamic route matching that extracts URL parameters, enhancing real-time messaging and connection logging.
    • Implemented custom context handling for SSE connections, allowing improved message processing based on route parameters.
  • Tests

    • Added a test case to verify handling of custom route parameters, ensuring accurate responses and error handling in the SSE server.

anhao avatar Apr 08 '25 03:04 anhao

"""

Walkthrough

This pull request introduces a new example and updates the SSE server. A new Go file implements an SSE server using the MCP framework with custom connection context handling and a message handler. Enhancements in the server allow extraction and utilization of route parameters via a new pattern matching mechanism. A corresponding test case validates the dynamic routing functionality by checking proper parameter extraction and message processing.

Changes

File Change Summary
examples/custom_sse_pattern/main.go New file implementing an SSE server using the MCP framework. Introduces customContextFunc, messageHandler, and main to log connection details, extract parameters, and register a tool for message sending.
server/sse.go Added support for route parameters with new types (RouteParams, RouteParamsKey) and functions (GetRouteParam, GetRouteParams, WithSSEPattern). Modified methods (handleSSE, handleMessage, ServeHTTP) to incorporate pattern matching and dynamic route handling using a new helper function matchPath.
server/sse_test.go Added a new test "Can handle custom route parameters" validating SSE server's dynamic route parameter extraction, connection establishment, message endpoint retrieval, and tool invocation using route parameters.

Possibly related PRs

  • mark3labs/mcp-go#32: Extends SSE server's context customization with dynamic route parameter extraction and injection, building on the context callback mechanism introduced in this PR.
  • mark3labs/mcp-go#29: Adds a basic ServeHTTP method for fixed SSE and message paths; the current PR builds significantly on this foundation by adding dynamic routing and context enhancements. """

πŸ“œ 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 81724597a8e3ed61bfa68fea0fc29fb7911acd96 and 9266ee5576f4c4c15f01858569f9a3cf7c2f86b4.

πŸ“’ Files selected for processing (1)
  • server/sse.go (10 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/sse.go
✨ 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.

coderabbitai[bot] avatar Apr 08 '25 03:04 coderabbitai[bot]

@ezynda3 Hi! My PR is ready for merge and all checks have passed. Could you please review and merge it into the main branch if everything looks good? Thank you! πŸ™

anhao avatar Apr 10 '25 13:04 anhao

I really need this feature.

weibaohui avatar Apr 11 '25 17:04 weibaohui

I really need this feature.

+1

viky88 avatar Apr 21 '25 09:04 viky88

+1 This will be awesome and works as expected. Lets resolve the conflicts, whenever you get time. @anhao

karngyan avatar Apr 22 '25 17:04 karngyan

+1 This will be awesome and works as expected. Lets resolve the conflicts, whenever you get time. @anhao

Thank you, I have resolved the conflict. Could you please check it?

anhao avatar Apr 27 '25 01:04 anhao

I took a crack at an alternative implementation fro allowing the server to be mounted at dynamic paths over in https://github.com/mark3labs/mcp-go/pull/214, 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. It will work alongside the changes in #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)

@anhao - What do you think?

rwjblue-glean avatar Apr 27 '25 22:04 rwjblue-glean

I took a crack at an alternative implementation fro allowing the server to be mounted at dynamic paths over in #214, 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. It will work alongside the changes in 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)

@anhao - What do you think?

@robert-jackson-glean Sounds good to me! The approach is more flexible . Happy to see it implemented. πŸ‘

anhao avatar Apr 28 '25 03:04 anhao

Just to close the loop here, #214 has landed and is released now. Folks should take a look!

rwjblue-glean avatar May 02 '25 12:05 rwjblue-glean