Skip to content

feat: Add GetHeader() Support for SSE Transport Sessions (ClientSession) #444

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

Sanskarzz
Copy link

@Sanskarzz Sanskarzz commented Jun 24, 2025

Description

The MCP-Go library's SSE transport was missing the ability to access HTTP headers from client requests. While the ClientSession interface defined a GetHeader() method, none of the session implementations actually implemented it.

Fixes #443

Type of Change

  • New feature (non-breaking change that adds functionality)

Previously: Developers could only access session ID in hooks

hooks := &server.Hooks{
    OnRegisterSession: []server.OnRegisterSessionHookFunc{
        func(ctx context.Context, session server.ClientSession) {
            sessionID := session.SessionID() //  This worked
            headers := session.GetHeader()   //  This caused compilation errors
        },
    },
}

Now: Just like we can get sessionID using hooks, we can get headers as well!

hooks := &server.Hooks{
    OnRegisterSession: []server.OnRegisterSessionHookFunc{
        func(ctx context.Context, session server.ClientSession) {
            sessionID := session.SessionID() //  Session ID (existing)
            headers := session.GetHeader()   // HTTP Headers (NEW!)
            
            // Access specific headers
            userAgent := headers.Get("User-Agent")
            authorization := headers.Get("Authorization") 
            customHeader := headers.Get("X-Custom-Header")
            
            log.Printf("Session %s from %s", sessionID, userAgent)
        },
    },
}

MCP Spec Compliance

  • This PR implements a feature defined in the MCP specification
  • Link to relevant spec section: Link text
  • Implementation follows the specification exactly

Additional Information

Summary by CodeRabbit

  • New Features
    • Sessions now retain and provide access to the HTTP headers from the initial client request, enabling improved visibility of request metadata for supported session types.
  • Bug Fixes
    • No user-facing bug fixes included in this update.
  • Tests
    • Updated test session types to support the new header retrieval functionality for consistency with production code.

Copy link
Contributor

coderabbitai bot commented Jun 24, 2025

Walkthrough

The changes introduce a new GetHeader() method to the ClientSession interface and implement it across all session types, including SSE and HTTP streamable sessions. The SSE and HTTP session implementations now store and return the initial HTTP request headers, while other session types return empty headers. Test session types are updated accordingly.

Changes

Files/Paths Change Summary
server/session.go Added GetHeader() method to ClientSession interface.
server/sse.go Added headers field and GetHeader() method to sseSession; headers are cloned from incoming request.
server/streamable_http.go Added headers field and GetHeader() to streamableHttpSession; constructors updated for headers.
server/stdio.go Added GetHeader() method to stdioSession returning empty headers.
server/server_test.go Added GetHeader() to fakeSession in tests, returns empty headers.
server/session_test.go Added GetHeader() to all test session client types, returns empty headers.

Assessment against linked issues

Objective Addressed Explanation
Add GetHeader() method to ClientSession interface and implement in SSE transport (#443)
Ensure SSE session stores and returns HTTP headers from initial client request (#443)
Update test session types to implement GetHeader() (#443)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found. All modifications are directly related to implementing the GetHeader() method and updating relevant session types and tests as required by the linked issue.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 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 8f5b048 and b0ff703.

📒 Files selected for processing (6)
  • server/server_test.go (2 hunks)
  • server/session.go (2 hunks)
  • server/session_test.go (5 hunks)
  • server/sse.go (3 hunks)
  • server/stdio.go (2 hunks)
  • server/streamable_http.go (3 hunks)
🔇 Additional comments (16)
server/server_test.go (2)

9-9: LGTM: Appropriate import addition.

The net/http import is correctly added to support the http.Header type used in the new GetHeader() method.


526-529: LGTM: Clean test implementation.

The GetHeader() method implementation for the test session is appropriate. Returning an empty http.Header is correct for test scenarios where actual HTTP headers are not relevant, and the comment clearly explains this behavior.

server/stdio.go (2)

10-10: LGTM: Necessary import for GetHeader() method.

The net/http import is correctly added to support the http.Header return type.


104-107: LGTM: Appropriate implementation for stdio transport.

The GetHeader() method correctly returns an empty http.Header for stdio sessions. This is the right approach since stdio transport doesn't involve HTTP and therefore has no headers. The comment clearly explains this behavior.

server/session.go (2)

6-6: LGTM: Required import for interface extension.

The net/http import is necessary to support the new GetHeader() method that returns http.Header.


21-22: LGTM: Well-designed interface extension.

The addition of GetHeader() http.Header to the ClientSession interface is well-implemented:

  • Clear method signature that returns the header map directly
  • Good documentation explaining it returns headers from the initial request
  • Enables consistent header access across all session types

Note that this is a breaking change to the interface, but all implementations in this PR properly implement the method.

server/sse.go (3)

33-33: LGTM: Clean field addition for header storage.

The headers http.Header field appropriately stores HTTP headers from the initial SSE connection request, enabling later access via the GetHeader() method.


112-114: LGTM: Simple and correct implementation.

The GetHeader() method correctly returns the stored headers. This provides access to the initial HTTP request headers as required by the interface.


361-361: LGTM: Excellent use of header cloning.

Using r.Header.Clone() is the best practice here. It creates a safe copy of the headers, preventing potential issues if the original header map is modified elsewhere. This ensures the session has a stable view of the initial request headers.

server/session_test.go (2)

7-7: LGTM: Proper import addition

The net/http import is correctly added to support the http.Header type used in the new GetHeader() method implementations.


46-49: LGTM: Consistent GetHeader() implementations across test session types

All test session implementations correctly implement the GetHeader() method by returning empty headers with clear explanatory comments. This is the appropriate behavior for test sessions that don't represent actual HTTP connections.

The implementation is consistent across all session types:

  • sessionTestClient
  • sessionTestClientWithTools
  • sessionTestClientWithClientInfo
  • sessionTestClientWithLogging

Also applies to: 109-112, 151-154, 191-194

server/streamable_http.go (5)

552-552: LGTM: Appropriate field addition for header storage

The headers http.Header field is correctly added to store HTTP headers from the initial client request, enabling access to headers like "User-Agent", "Authorization", and custom headers as mentioned in the PR objectives.


560-562: LGTM: Backward compatibility maintained

The existing constructor properly initializes empty headers for ephemeral sessions (POST requests), maintaining backward compatibility while supporting the new header functionality.


564-571: LGTM: Secure header handling with proper cloning

The new constructor correctly clones the incoming headers using headers.Clone(), which prevents unintended mutations and ensures each session has its own copy of the headers. This is a security best practice when storing references to external data.


368-368: LGTM: Proper integration of header-aware session creation

The handleGet method correctly uses the new newStreamableHttpSessionWithHeaders constructor, passing the request headers from the initial HTTP request. This ensures that persistent sessions (GET requests for SSE) have access to the original HTTP headers.


609-611: LGTM: Simple and thread-safe header access

The GetHeader() method implementation is straightforward and thread-safe. Since headers are only set during session construction and never modified afterward, returning the stored headers directly is safe and efficient.

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.

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.

feature: Add support GetHeader() Method in SSE Transport Sessions (ClientSession)
1 participant