Skip to content

feat: add hooks for sse client #221

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
Open

Conversation

tk103331
Copy link

@tk103331 tk103331 commented Apr 28, 2025

add hooks for sse client:

// OnBeforeRequestFunc is called before sending the request, with context.
type OnBeforeRequestFunc func(ctx context.Context, req *http.Request)

// OnAfterResponseFunc is called after receiving the response, with context. (Regardless of error, when err is not nil resp may be nil.) The req parameter is included.
type OnAfterResponseFunc func(ctx context.Context, req *http.Request, resp *http.Response, err error)

// SSEHooks supports multiple before and after processing functions.
type SSEHooks struct {
	OnBeforeRequest []OnBeforeRequestFunc
	OnAfterResponse []OnAfterResponseFunc
}

Copy link
Contributor

coderabbitai bot commented Apr 28, 2025

Walkthrough

This change introduces a hook mechanism to the SSE transport client, enabling custom functions to be executed before sending HTTP requests and after receiving HTTP responses. Two new function types, OnBeforeRequestFunc and OnAfterResponseFunc, are defined for these hooks. A new SSEHooks struct holds slices of these functions, and the SSE client struct is updated to include these hooks. A new client option, WithSSEHooks, allows registration of hooks. The SendRequest and SendNotification methods are updated to invoke the hooks at the appropriate points in the request/response lifecycle.

Changes

File(s) Change Summary
client/transport/sse.go Added hook mechanism with OnBeforeRequestFunc and OnAfterResponseFunc types, SSEHooks struct, hooks field in SSE, WithSSEHooks client option, and hook invocation in request/response methods.
✨ 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: 0

♻️ Duplicate comments (1)
client/transport/sse.go (1)

396-401: Same potential issue with hook invocation timing.

Similar to the SendRequest method, the OnAfterResponse hooks in SendNotification are invoked before checking the error from the HTTP request. As mentioned earlier, verify if this is the desired behavior.

🧹 Nitpick comments (3)
client/transport/sse.go (3)

77-83: Initialize hooks field in constructor.

While the code will work as is, it's a good practice to initialize the hooks field with empty slices to avoid potential nil pointer issues if hooks are accessed before being set.

smc := &SSE{
	baseURL:      parsedURL,
	httpClient:   &http.Client{},
	responses:    make(map[int64]chan *JSONRPCResponse),
	endpointChan: make(chan struct{}),
	headers:      make(map[string]string),
+	hooks:        SSEHooks{
+		OnBeforeRequest: []OnBeforeRequestFunc{},
+		OnAfterResponse: []OnAfterResponseFunc{},
+	},
}

20-401: Consider adding utility methods for individual hook registration.

The current implementation only allows setting all hooks at once with WithSSEHooks. Consider adding utility methods for adding individual hooks without replacing the entire set, which would provide more flexibility.

// Add a single OnBeforeRequest hook
func WithSSEBeforeRequestHook(hook OnBeforeRequestFunc) ClientOption {
	return func(sc *SSE) {
		sc.hooks.OnBeforeRequest = append(sc.hooks.OnBeforeRequest, hook)
	}
}

// Add a single OnAfterResponse hook
func WithSSEAfterResponseHook(hook OnAfterResponseFunc) ClientOption {
	return func(sc *SSE) {
		sc.hooks.OnAfterResponse = append(sc.hooks.OnAfterResponse, hook)
	}
}

20-401: Consider adding example usage in the package documentation.

Since this is a significant new feature, it would be helpful to include example usage in the package documentation or in code comments to guide users on how to effectively use the hooks.

You could add a package-level example or document with sample code showing how to use the hooks for common use cases such as logging, metrics collection, or authentication.

📜 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 7162a07.

📒 Files selected for processing (1)
  • client/transport/sse.go (6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
client/transport/sse.go (2)
mcp/types.go (1)
  • Request (103-116)
client/client.go (1)
  • ClientOption (27-27)
🔇 Additional comments (7)
client/transport/sse.go (7)

20-24: Good function type definitions with clear documentation.

The new hook function types are well-defined with appropriate parameters and concise documentation. The comment for OnAfterResponseFunc correctly notes that when err is not nil, resp may be nil, which is important for proper error handling in the hooks.


26-30: Well-structured hook container allowing multiple hooks.

The SSEHooks struct design is clean and allows for registering multiple hooks of each type, which provides flexibility for composing different hook behaviors.


47-47: Appropriate field addition to SSE struct.

The hooks field is properly added to the existing struct without disrupting the existing functionality.


62-67: Clear option function for setting hooks.

The WithSSEHooks function follows the established client option pattern in the codebase, and the comment clearly indicates that it replaces any existing hooks.


285-290: Well-implemented pre-request hook invocation.

The OnBeforeRequest hooks are properly invoked with nil checks before sending the HTTP request. The sequential invocation allows for multiple hooks to process or modify the request.


306-311: Hook invocation location for OnAfterResponse might need adjustment.

The OnAfterResponse hooks are invoked before checking the error from the HTTP request. This means that if the HTTP request fails, the hooks will see an error but still run before the function returns. Consider if this is the desired behavior, as it might be cleaner to place the hook invocation after the error check.

Please verify that this is the desired behavior for the OnAfterResponse hooks. If you want the hooks to be called regardless of errors (which seems to be the case based on the function signature that includes an error parameter), then the current implementation is correct. If you want to skip hook invocation on errors, consider moving the hook invocation after the error check.


387-392: Consistent hook implementation in SendNotification.

The OnBeforeRequest hooks implementation in SendNotification matches the one in SendRequest, maintaining consistency across the codebase.

@dugenkui03
Copy link
Contributor

hi, @tk103331 @ezynda3

  1. there is already a MCP Client, how about adding this hook to MCP Client, all the client could use hooks
  2. do you think defining an interface is a better idea, then you could implement differently for different way, such as log hook, monitor hook. idea like [proposal] Optimize hooks #159

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