Skip to content

feat: add support for custom HTTP headers in client requests #546

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

matthisholleville
Copy link
Contributor

@matthisholleville matthisholleville commented Aug 13, 2025

Description

This update introduces the ability to include custom HTTP headers in requests sent from the client. This enhancement facilitates more flexible and secure communication with servers by allowing clients to pass additional information in the header of each request, such as simple authentication tokens or custom metadata.

Fixes #544

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • MCP spec compatibility implementation
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Code refactoring (no functional changes)
  • Performance improvement
  • Tests only (no functional changes)
  • Other (please describe):

Checklist

  • My code follows the code style of this project
  • I have performed a self-review of my own code
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the documentation accordingly

Additional Information

Summary by CodeRabbit

  • New Features

    • Per-request HTTP header support for all JSON-RPC calls.
    • Initialization now records server capabilities, applies protocol version to HTTP transports, and sends an “initialized” notification.
    • OAuth integration: automatically attaches Authorization headers; surfaces a specific error to trigger authentication when required.
  • Improvements

    • More resilient session handling: automatically clears session on 404 and reports termination.
    • Consistent header application alongside defaults (Content-Type, Accept, session, protocol version).
  • Tests

    • Added tests validating per-request header propagation and header echo behavior.

This update introduces the ability to include custom HTTP headers in requests sent from the client. This enhancement facilitates more flexible and secure communication with servers by allowing clients to pass additional information in the header of each request, such as authentication tokens or custom metadata. This feature is crucial for integrating with APIs that require specific headers for access control, content negotiation, or tracking purposes.

Signed-off-by: Matthis Holleville <[email protected]>
Copy link
Contributor

coderabbitai bot commented Aug 13, 2025

Walkthrough

Adds per-request HTTP header propagation through the client and StreamableHTTP transport by threading http.Header from Client.sendRequest into transport.JSONRPCRequest and applying it in HTTP requests. Updates call sites. Extends tests to assert header echoing. Also adds 404 session termination handling and OAuth authorization header retrieval in HTTP transport.

Changes

Cohort / File(s) Summary of Changes
Client request plumbing
client/client.go
Update sendRequest signature to accept http.Header and embed into transport.JSONRPCRequest; pass headers from all call sites (Initialize, Ping, ReadResource, Subscribe, Unsubscribe, GetPrompt, CallTool, SetLevel, Complete, listByPage).
Transport interface
client/transport/interface.go
Add Header http.Header field (json:"-") to JSONRPCRequest to carry per-request headers without serializing them.
StreamableHTTP transport
client/transport/streamable_http.go
Extend sendHTTP to accept per-request headers and apply them before defaults; SendRequest forwards request.Header. Add OAuth Authorization header handling and specific error surfacing; clear session and return ErrSessionTerminated on 404. Adjust related call sites to pass nil where applicable.
Transport tests
client/transport/streamable_http_test.go
Add debug/echo_header RPC and test to verify per-request headers are echoed; include headers in existing echo response for assertions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Allow specifying headers per request via Client.sendRequest and propagate to HTTP transport (#544)
Ensure headers are not serialized into JSON-RPC payload (#544)
Ability to set headers specifically for CallTool requests (#544)
Tests verifying per-request headers are applied/received by server (#544)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Add OAuth authorization header retrieval and OAuthAuthorizationRequiredError handling in sendHTTP (client/transport/streamable_http.go, function sendHTTP) OAuth flow changes are not part of enabling per-request custom headers and are unrelated to #544’s scope.
Clear session and return ErrSessionTerminated on HTTP 404 responses (client/transport/streamable_http.go, function sendHTTP) Session termination behavior is orthogonal to per-request header support and not mentioned in #544.

Possibly related PRs

Suggested reviewers

  • ezynda3
  • rwjblue-glean
  • pottekkat
  • dugenkui03
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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: 1

🧹 Nitpick comments (3)
client/transport/streamable_http_test.go (1)

133-133: Fix typo in comment.

There's a typo in the comment.

-			// Echo back the request headersas the response result
+			// Echo back the request headers as the response result
client/client.go (1)

134-134: Consider documenting the header parameter.

The new header parameter in sendRequest would benefit from documentation explaining its purpose and usage, especially since this is a key part of the per-request header feature.

Add a comment to the parameter in the function signature:

 func (c *Client) sendRequest(
 	ctx context.Context,
 	method string,
 	params any,
-	header http.Header,
+	header http.Header, // Custom HTTP headers to include in this request
 ) (*json.RawMessage, error) {
client/transport/streamable_http.go (1)

373-385: OAuth error handling could be more consistent.

The OAuth authorization error is checked twice - once as a string comparison and once returning the same error type. This could be simplified for better maintainability.

 	// Add OAuth authorization if configured
 	if c.oauthHandler != nil {
 		authHeader, err := c.oauthHandler.GetAuthorizationHeader(ctx)
 		if err != nil {
-			// If we get an authorization error, return a specific error that can be handled by the client
-			if err.Error() == "no valid token available, authorization required" {
+			// If we get an authorization error, check if it's the specific OAuth error
+			if errors.Is(err, ErrOAuthAuthorizationRequired) {
 				return nil, &OAuthAuthorizationRequiredError{
 					Handler: c.oauthHandler,
 				}
 			}
 			return nil, fmt.Errorf("failed to get authorization header: %w", err)
 		}
 		req.Header.Set("Authorization", authHeader)
 	}

This assumes that GetAuthorizationHeader would return ErrOAuthAuthorizationRequired directly instead of a string-based error.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f16336 and 5a8cd65.

📒 Files selected for processing (4)
  • client/client.go (11 hunks)
  • client/transport/interface.go (2 hunks)
  • client/transport/streamable_http.go (9 hunks)
  • client/transport/streamable_http_test.go (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
client/transport/streamable_http_test.go (3)
client/transport/interface.go (1)
  • JSONRPCRequest (58-64)
mcp/types.go (3)
  • JSONRPCRequest (325-330)
  • NewRequestId (259-261)
  • Params (177-177)
testdata/mockstdio_server.go (1)
  • JSONRPCRequest (13-18)
client/client.go (1)
mcp/types.go (4)
  • Params (177-177)
  • UnsubscribeRequest (635-639)
  • CompleteRequest (1021-1025)
  • CompleteResult (1038-1050)
🔇 Additional comments (4)
client/transport/interface.go (1)

63-63: LGTM! The Header field addition enables per-request header customization.

The addition of the Header field with json:"-" tag is appropriate as it allows per-request headers to be passed through the transport layer without affecting the JSON-RPC payload serialization.

client/transport/streamable_http_test.go (1)

237-269: LGTM! Comprehensive test for per-request header propagation.

The test properly validates that custom headers are sent and received by the server, confirming the header propagation feature works as expected.

client/client.go (1)

185-185: LGTM! Consistent header propagation across all client methods.

The header parameter is correctly propagated from all public methods through sendRequest to the transport layer. Methods that don't have headers in their request structures appropriately pass nil.

Also applies to: 230-230, 311-311, 323-323, 331-331, 375-375, 423-423, 435-435, 443-443, 520-520

client/transport/streamable_http.go (1)

399-403: Good addition of 404 session termination handling.

The automatic session cleanup on 404 responses is a useful feature that helps maintain consistency when the server indicates the session no longer exists.

Comment on lines +350 to +354
// request headers
if header != nil {
req.Header = header
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Header assignment may not preserve all default headers.

When a custom header is provided, the code replaces the entire req.Header with the provided header. This could potentially lose important default headers that http.NewRequestWithContext sets up (like Host, User-Agent, etc.).

Consider merging headers instead of replacing:

-	// request headers
-	if header != nil {
-		req.Header = header
-	}
-
+	// Merge custom headers if provided
+	if header != nil {
+		for key, values := range header {
+			for _, value := range values {
+				req.Header.Add(key, value)
+			}
+		}
+	}

Alternatively, if the intention is to allow complete header control, consider cloning the header first to avoid modifying the original:

-	// request headers
-	if header != nil {
-		req.Header = header
-	}
-
+	// Use custom headers if provided
+	if header != nil {
+		req.Header = header.Clone()
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// request headers
if header != nil {
req.Header = header
}
// Merge custom headers if provided
if header != nil {
for key, values := range header {
for _, value := range values {
req.Header.Add(key, value)
}
}
}
🤖 Prompt for AI Agents
In client/transport/streamable_http.go around lines 350 to 354, the code
replaces req.Header with the provided header which can discard default headers;
instead merge the provided header into the existing req.Header (iterating keys
and appending values) so you preserve defaults like Host and User-Agent, or if
full control was intended, first clone the provided header and assign the clone
to req.Header to avoid mutating the caller's header; implement one of these two
approaches and ensure you append values rather than overwrite per header key.

@matthisholleville
Copy link
Contributor Author

cc. @ezynda3

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: Possibility to specify headers when calling a CallTool
1 participant