Skip to content

HTTP Headers Support for SSE MCP Client at Start #122

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

Conversation

k33g
Copy link

@k33g k33g commented Apr 8, 2025

Overview

This change implements custom HTTP headers support for the SSE MCP Client into the Start method of the SSE client, particularly useful for authentication scenarios with bearer token.

Changes Made

  • Added ability to set custom HTTP headers when creating a new SSE MCP Client
  • Implementation through a simple map of string key-value pairs

Example Usage

To create a client with authentication:

mcpClient, err := client.NewSSEMCPClient(
    baseURL + "/sse",
    client.WithHeaders(map[string]string{
        "Authorization": "Bearer " + bearerToken,
    }),
)

Benefits

  • Simple Implementation
  • Flexibility: Supports any custom HTTP headers, not just authentication

Use Cases

  • Bearer token authentication
  • API key authentication
  • Custom headers for proxies
  • Session tracking
  • Client identification

This change makes the SSE MCP Client more versatile by supporting authenticated connections while maintaining a clean and simple API.

Summary by CodeRabbit

  • New Features
    • Improved the server connection process by enabling the use of custom HTTP headers during setup, allowing for enhanced and more flexible interactions with the server.
    • Added a method to set custom HTTP headers for all requests made by the client.

Copy link
Contributor

coderabbitai bot commented Apr 8, 2025

Walkthrough

This pull request introduces a new method WithHeaders in the SSEMCPClient struct, enabling the configuration of custom HTTP headers for all client requests. A new field headers map[string]string is added to the struct, and the existing methods Start, sendRequest, and Initialize are modified to include logic for applying these custom headers while ensuring that standard headers are not overridden. Documentation comments have also been added to clarify the method's purpose and usage.

Changes

File(s) Change Summary
client/sse.go Added a new method WithHeaders(headers map[string]string) ClientOption and a new field headers map[string]string in SSEMCPClient. Updated Start, sendRequest, and Initialize methods to utilize the headers map for custom HTTP headers.

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 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 a2d8ace and da33720.

📒 Files selected for processing (1)
  • client/sse.go (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/sse.go

🪧 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

🔭 Outside diff range comments (1)
client/sse.go (1)

388-406: ⚠️ Potential issue

Missing custom headers in the initialized notification request.

While custom headers are applied in the Start method and sendRequest method, they're not being applied to the notification request in the Initialize method. If authentication headers are required for all requests to the server, this omission could cause the notification to fail.

Apply this diff to fix the issue:

 req.Header.Set("Content-Type", "application/json")
+// set custom http headers
+for k, v := range c.headers {
+    req.Header.Set(k, v)
+}
 
 resp, err := c.httpClient.Do(req)
🧹 Nitpick comments (2)
client/sse.go (2)

44-48: Function looks good but could benefit from a doc comment.

The implementation of WithHeaders follows the functional options pattern correctly. Consider adding a doc comment describing its purpose and usage examples.

+// WithHeaders sets custom HTTP headers that will be included in all requests made by the client.
+// This is particularly useful for authentication (e.g., bearer tokens, API keys) and other 
+// custom header requirements.
 func WithHeaders(headers map[string]string) ClientOption {
     return func(sc *SSEMCPClient) {
         sc.headers = headers
     }
 }

97-100: Consider adding header conflict protection.

Currently, users can override standard headers like "Accept" or "Content-Type" through the custom headers map. This provides flexibility but could also lead to unexpected behavior if standard headers are accidentally overridden.

Consider implementing a safeguard against overriding critical headers:

 // set custom http headers
 for k, v := range c.headers {
+    // Skip standard headers that should not be overridden
+    switch k {
+    case "Accept", "Cache-Control", "Connection", "Content-Type":
+        continue
+    }
     req.Header.Set(k, v)
 }

Alternatively, you could emit a warning log when a standard header is being overridden if you prefer to maintain the flexibility.

Also applies to: 310-312

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a0e968a and 6d0b954.

📒 Files selected for processing (1)
  • client/sse.go (1 hunks)
🔇 Additional comments (3)
client/sse.go (3)

38-38: Excellent addition of headers field to support custom HTTP headers.

The addition of the headers field to the SSEMCPClient struct provides a clean way to store and utilize custom HTTP headers, particularly useful for authentication scenarios as mentioned in the PR objectives.


71-71: Good practice initializing the headers map.

Initializing the headers map in the constructor prevents nil map panics when attempting to add headers later.


97-100: Implementation for setting custom headers looks good.

The loop properly adds all custom headers to the request, which fulfills the main objective of this PR.

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 (2)
client/sse.go (2)

1-611: Add a usage example in the package documentation.

The PR objectives mention the use case of bearer token authentication, but there's no example in the code comments showing how to use this feature.

Consider adding an example at the package level documentation:

// Example:
//
//  // Create a client with authentication headers
//  client, err := NewSSEMCPClient(
//      "https://mcp.example.com",
//      WithHeaders(map[string]string{
//          "Authorization": "Bearer your-token-here",
//      }),
//  )

74-74: Use consistent comment formatting for custom headers sections.

The comments for setting custom headers use slightly different formats across the codebase. Standardizing these comments would improve readability and maintainability.

Standardize comments to this format throughout the code:

-	// set custom http headers
+	// Set custom HTTP headers

Also applies to: 101-102, 318-319, 412-413

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6d0b954 and a2d8ace.

📒 Files selected for processing (1)
  • client/sse.go (4 hunks)
🔇 Additional comments (5)
client/sse.go (5)

38-38: Good addition of the headers field to the struct.

The addition of the headers field to the SSEMCPClient struct enables the client to store custom HTTP headers, which is essential for the authentication feature described in the PR objectives.


44-51: Well-documented method for setting custom headers.

The WithHeaders function implementation follows the existing functional options pattern and has clear documentation that explains its purpose for authentication scenarios.


74-74: Proper initialization of the headers map.

Initializing the headers map in the constructor ensures it's never nil, preventing potential nil pointer dereferences when iterating over the map.


100-108: Good implementation of custom headers with proper safeguards.

The implementation correctly applies custom headers while protecting standard headers that should not be overridden. This preserves the expected behavior of the SSE connection.


318-325: Consistent header handling in sendRequest method.

The implementation in the sendRequest method follows the same pattern as in the Start method, ensuring that standard headers are not overridden.

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