Skip to content

Conversation

weibaohui
Copy link

@weibaohui weibaohui commented Apr 22, 2025

Summary by CodeRabbit

  • New Features

    • Added support for dynamic route parameters in SSE (Server-Sent Events) endpoint URLs, enabling more flexible and customizable SSE connections.
    • Introduced context-aware handling of route parameters for SSE sessions and message processing.
    • Provided an example demonstrating the use of custom SSE patterns and context functions.
  • Documentation

    • Example URLs and usage instructions are logged on server startup for easier testing and exploration.

在SSE会话中存储路由参数,并添加相关函数用于从上下文中获取路由参数。新增WithSSEPattern选项以支持带参数的SSE端点模式。这些更改使得SSE服务器能够处理包含动态路径参数的请求。
- 调整了SSEServer结构体字段的顺序,提高代码可读性
- 优化了ServeHTTP方法中的路径匹配逻辑,使其更加清晰
- 移除了冗余的上下文设置代码
- 添加了必要的空行以提升代码可读性
添加了一个新的示例代码文件 `main.go`,展示了如何使用自定义的SSE(Server-Sent Events)模式。该示例包括创建MCP服务器、注册工具、以及使用自定义路由模式和上下文函数启动SSE服务器
Copy link
Contributor

coderabbitai bot commented Apr 22, 2025

Walkthrough

This change introduces support for dynamic route parameter extraction in the Server-Sent Events (SSE) server implementation. It adds the ability to define SSE endpoint patterns with path parameters (such as /:channel/sse), parse those parameters from incoming request URLs, and inject them into the request context for use during SSE session handling and message processing. A new example demonstrates the usage of a custom SSE pattern and context function that logs and utilizes these route parameters. Several new context helper functions and option setters are added to facilitate this functionality.

Changes

File(s) Change Summary
examples/custom_sse_pattern/main.go New example program demonstrating custom SSE pattern usage, custom context function, and message handler with route parameter extraction.
server/sse.go Enhanced SSE server to support route parameter extraction from endpoint patterns, context injection, new helper functions for accessing route parameters, and new option for specifying SSE patterns.

Possibly related PRs

✨ 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 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.

@weibaohui weibaohui closed this Apr 22, 2025
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 (6)
server/sse.go (4)

43-56: Return a presence flag & protect against map mutation

GetRouteParam/GetRouteParams silently fall back to the zero value.
Returning a second bool makes call‑sites distinguish “missing” vs “empty string”.

Additionally, the map extracted from the context is shared; a careless caller could mutate it and create data races because the same instance is reused by multiple goroutines.

-func GetRouteParam(ctx context.Context, key string) string {
-    if params, ok := ctx.Value(RouteParamsKey{}).(RouteParams); ok {
-        return params[key]
-    }
-    return ""
+func GetRouteParam(ctx context.Context, key string) (string, bool) {
+    if params, ok := ctx.Value(routeParamsKey{}).(RouteParams); ok {
+        v, found := params[key]
+        return v, found
+    }
+    return "", false
 }

For GetRouteParams, consider returning a copy of the map:

out := make(RouteParams, len(params))
for k, v := range params { out[k] = v }
return out

That eliminates the possibility of concurrent writes on the same map.


273-274: Defensive‑copy route parameters when persisting them in the session

matchPath builds the params map and puts it into the request context.
handleSSE then stores the same reference inside sseSession.routeParams, and the
later HTTP POST (handleMessage) inserts it back into a new context.

If any middleware or handler mutates the map, a race occurs between the SSE goroutine and the message goroutine.

- routeParams:         GetRouteParams(r.Context()), // Store route parameters from context
+ routeParams: func() RouteParams {
+     src := GetRouteParams(r.Context())
+     dst := make(RouteParams, len(src))
+     for k, v := range src { dst[k] = v }
+     return dst
+ }(),

Do a similar clone before context.WithValue in handleMessage.

Also applies to: 383-390


540-563: matchPath is naïve – consider pre‑compiling once

strings.Split and allocations run on every request.
‐ No URL‑decoding of individual segments (e.g., %2F).
‐ It requires exact segment count (cannot support wildcards or trailing slashes).

If route patterns are static (set via WithSSEPattern at start‑up), compile them
to a *regexp.Regexp once and store in the SSEServer struct:

re := regexp.MustCompile(`^/api/(?P<channel>[^/]+)/sse$`)

Then use re.FindStringSubmatch and re.SubexpNames() for extraction – faster
and more flexible.


471-478: Minor: helper name & error message typo

GetUrlPathgetURLPath or GetURLPath for initialism correctness.

Also, the error message currently says failed to parse URL %s; consider quoting
with %q for readability.

examples/custom_sse_pattern/main.go (2)

22-33: Return an error when the required route param is absent

The handler treats a missing "channel" as success (error == nil) and sends a
text result saying failed. Returning an actual error (or JSON‑RPC error) lets
clients distinguish genuine failures.

-    if channel == "" {
-        return mcp.NewToolResultText("Failed to get channel parameter"), nil
-    }
+    if channel == "" {
+        return nil, fmt.Errorf("missing route parameter: channel")
+    }

This will propagate through HandleMessage as a proper JSON‑RPC error.


49-56: Hard‑coded port may clash in CI / local testing

Binding to :8080 can fail if the port is occupied.
Consider reading the port from an env‑var or CLI flag (e.g., PORT=8080 go run …).

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f39a43 and 7c7ae67.

📒 Files selected for processing (2)
  • examples/custom_sse_pattern/main.go (1 hunks)
  • server/sse.go (15 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
server/sse.go (3)
mcp/types.go (1)
  • Request (89-102)
server/server.go (1)
  • MCPServer (143-166)
examples/custom_context/main.go (1)
  • MCPServer (100-102)
🔇 Additional comments (1)
server/sse.go (1)

514-528: 404 behaviour may surprise when both WithSSEEndpoint and WithSSEPattern are set

The current logic:

  1. If a pattern is configured, try to match it.
  2. If it does not match, immediately return 404, even if the plain /sseEndpoint
    would have matched.

This effectively disables the plain endpoint whenever a pattern is supplied.

Verify that this is the intended precedence; otherwise, move the “default SSE
endpoint” check in front of the 404 or fall through to it.

Comment on lines +36 to +41
// RouteParamsKey is the key type for storing route parameters in context
type RouteParamsKey struct{}

// RouteParams stores path parameters
type RouteParams map[string]string

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid exporting RouteParamsKey and RouteParams unless they are part of the public API

Both symbols are exported, yet they are only consumed inside server package (and the example).
Un‑exporting prevents accidental key collisions across packages and keeps your API surface minimal.

-type RouteParamsKey struct{}
-type RouteParams map[string]string
+type routeParamsKey struct{}
+type RouteParams map[string]string // keep this exported only if other pkgs really need it

If RouteParams itself is also private to server, rename it similarly (type routeParams map[string]string).
Update the occurrences accordingly.

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.

1 participant