Skip to content

[SSE][OAuth] Add OAuth support to SSE client #340

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

Merged
merged 4 commits into from
Jun 5, 2025

Conversation

giridhar-murthy-glean
Copy link
Contributor

@giridhar-murthy-glean giridhar-murthy-glean commented May 27, 2025

Description

This PR adds OAuth support to SSE clients. This is necessary to deal with MCP servers that exhibit the behavior described in the backwards compatibility section of the spec:
https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#backwards-compatibility

Fixes #<issue_number> (if applicable)

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

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

    • Added OAuth authentication support for SSE-based clients, allowing secure streaming connections.
    • Introduced methods to check and access OAuth configuration status in SSE transports.
    • Added a new client for OAuth-secured SSE connections.
  • Bug Fixes

    • Ensured the "Bearer" token type is correctly capitalized in authorization headers for OAuth.
  • Tests

    • Added comprehensive tests for OAuth integration with SSE transports.
    • Updated tests to reflect OAuth option naming changes.
  • Chores

    • Enhanced the OAuth client example to automatically retry authorization when required.

Copy link
Contributor

coderabbitai bot commented May 27, 2025

"""

Walkthrough

This change adds OAuth authentication support to the SSE transport, introduces a new OAuth SSE client constructor, and updates the Streamable HTTP client to use a renamed OAuth option. It also adds comprehensive tests for SSE OAuth integration, normalizes the "Bearer" token type, and refactors OAuth client initialization and retry logic in the example client.

Changes

Files/Paths Change Summary
client/oauth.go Modified NewOAuthStreamableHttpClient to use WithHTTPOAuth; added NewOAuthSSEClient constructor.
client/transport/oauth.go Normalized "bearer" token type to "Bearer" in GetAuthorizationHeader.
client/transport/sse.go Added OAuth support to SSE transport: new field, option, error handling, and accessor methods.
client/transport/sse_oauth_test.go Added tests for SSE OAuth integration, error handling, and OAuth-enabled status detection.
client/transport/streamable_http.go Renamed WithOAuth to WithHTTPOAuth for Streamable HTTP client option function.
client/transport/streamable_http_oauth_test.go Updated tests to use WithHTTPOAuth instead of WithOAuth.
examples/oauth_client/main.go Refactored OAuth flow to centralize authorization and retry logic; added resource listing after init.

Possibly related PRs

  • mark3labs/mcp-go#296: Introduces and implements OAuth client setup, including the original NewOAuthStreamableHttpClient function, which is extended and modified in this PR.
  • mark3labs/mcp-go#168: Implements the initial Streamable-HTTP client; this PR extends it by adding OAuth support.

Suggested labels

type: enhancement, area: mcp spec

Suggested reviewers

  • pottekkat
  • robert-jackson-glean
    """

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 04418da and 02e142a.

📒 Files selected for processing (1)
  • client/transport/sse_oauth_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/transport/sse_oauth_test.go
✨ 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.

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

🔭 Outside diff range comments (1)
examples/oauth_client/main.go (1)

106-170: 🛠️ Refactor suggestion

Consider returning errors instead of calling log.Fatalf.

The function calls log.Fatalf on errors, making it impossible for callers to handle errors differently. Consider returning an error to make the function more flexible and testable.

-func maybeAuthorize(err error) {
+func maybeAuthorize(err error) error {
 	// Check if we need OAuth authorization
 	if client.IsOAuthAuthorizationRequiredError(err) {
 		fmt.Println("OAuth authorization required. Starting authorization flow...")

 		// Get the OAuth handler from the error
 		oauthHandler := client.GetOAuthHandler(err)

 		// Start a local server to handle the OAuth callback
 		callbackChan := make(chan map[string]string)
 		server := startCallbackServer(callbackChan)
 		defer server.Close()

 		// Generate PKCE code verifier and challenge
 		codeVerifier, err := client.GenerateCodeVerifier()
 		if err != nil {
-			log.Fatalf("Failed to generate code verifier: %v", err)
+			return fmt.Errorf("failed to generate code verifier: %w", err)
 		}
 		codeChallenge := client.GenerateCodeChallenge(codeVerifier)

 		// Generate state parameter
 		state, err := client.GenerateState()
 		if err != nil {
-			log.Fatalf("Failed to generate state: %v", err)
+			return fmt.Errorf("failed to generate state: %w", err)
 		}

 		err = oauthHandler.RegisterClient(context.Background(), "mcp-go-oauth-example")
 		if err != nil {
-			log.Fatalf("Failed to register client: %v", err)
+			return fmt.Errorf("failed to register client: %w", err)
 		}

 		// Get the authorization URL
 		authURL, err := oauthHandler.GetAuthorizationURL(context.Background(), state, codeChallenge)
 		if err != nil {
-			log.Fatalf("Failed to get authorization URL: %v", err)
+			return fmt.Errorf("failed to get authorization URL: %w", err)
 		}

 		// Open the browser to the authorization URL
 		fmt.Printf("Opening browser to: %s\n", authURL)
 		openBrowser(authURL)

 		// Wait for the callback
 		fmt.Println("Waiting for authorization callback...")
 		params := <-callbackChan

 		// Verify state parameter
 		if params["state"] != state {
-			log.Fatalf("State mismatch: expected %s, got %s", state, params["state"])
+			return fmt.Errorf("state mismatch: expected %s, got %s", state, params["state"])
 		}

 		// Exchange the authorization code for a token
 		code := params["code"]
 		if code == "" {
-			log.Fatalf("No authorization code received")
+			return fmt.Errorf("no authorization code received")
 		}

 		fmt.Println("Exchanging authorization code for token...")
 		err = oauthHandler.ProcessAuthorizationResponse(context.Background(), code, state, codeVerifier)
 		if err != nil {
-			log.Fatalf("Failed to process authorization response: %v", err)
+			return fmt.Errorf("failed to process authorization response: %w", err)
 		}

 		fmt.Println("Authorization successful!")
+		return nil
 	}
+	return err
 }

Then update the callers:

-		maybeAuthorize(err)
+		if err := maybeAuthorize(err); err != nil {
+			log.Fatalf("Failed to authorize: %v", err)
+		}
🧹 Nitpick comments (3)
client/transport/oauth.go (1)

140-146: Good defensive programming for token type normalization.

The normalization of lowercase "bearer" to "Bearer" improves compatibility with OAuth implementations that may return inconsistent casing. This follows the OAuth 2.0 specification which uses "Bearer" with a capital B.

Consider making this more comprehensive by handling other potential variations:

 // Some auth implementations are strict about token type
 tokenType := token.TokenType
-if tokenType == "bearer" {
-	tokenType = "Bearer"
-}
+if strings.ToLower(tokenType) == "bearer" {
+	tokenType = "Bearer"
+}

This would handle variations like "BEARER", "Bearer", "bearer", etc.

client/oauth.go (1)

38-39: Fix the function documentation.

The comment incorrectly describes this as a "streamable-http-based" client when it should be "SSE-based".

-// NewOAuthStreamableHttpClient creates a new streamable-http-based MCP client with OAuth support.
+// NewOAuthSSEClient creates a new SSE-based MCP client with OAuth support.
examples/oauth_client/main.go (1)

69-88: Consider refactoring to reduce code duplication.

The InitializeRequest structure is duplicated. Consider extracting it to a variable to improve maintainability.

-	result, err := c.Initialize(context.Background(), mcp.InitializeRequest{
-		Params: struct {
-			ProtocolVersion string                 `json:"protocolVersion"`
-			Capabilities    mcp.ClientCapabilities `json:"capabilities"`
-			ClientInfo      mcp.Implementation     `json:"clientInfo"`
-		}{
-			ProtocolVersion: mcp.LATEST_PROTOCOL_VERSION,
-			ClientInfo: mcp.Implementation{
-				Name:    "mcp-go-oauth-example",
-				Version: "0.1.0",
-			},
-		},
-	})
+	initRequest := mcp.InitializeRequest{
+		Params: struct {
+			ProtocolVersion string                 `json:"protocolVersion"`
+			Capabilities    mcp.ClientCapabilities `json:"capabilities"`
+			ClientInfo      mcp.Implementation     `json:"clientInfo"`
+		}{
+			ProtocolVersion: mcp.LATEST_PROTOCOL_VERSION,
+			ClientInfo: mcp.Implementation{
+				Name:    "mcp-go-oauth-example",
+				Version: "0.1.0",
+			},
+		},
+	}
+	
+	result, err := c.Initialize(context.Background(), initRequest)

 	if err != nil {
 		maybeAuthorize(err)
-		result, err = c.Initialize(context.Background(), mcp.InitializeRequest{
-			Params: struct {
-				ProtocolVersion string                 `json:"protocolVersion"`
-				Capabilities    mcp.ClientCapabilities `json:"capabilities"`
-				ClientInfo      mcp.Implementation     `json:"clientInfo"`
-			}{
-				ProtocolVersion: mcp.LATEST_PROTOCOL_VERSION,
-				ClientInfo: mcp.Implementation{
-					Name:    "mcp-go-oauth-example",
-					Version: "0.1.0",
-				},
-			},
-		})
+		result, err = c.Initialize(context.Background(), initRequest)
 		if err != nil {
 			log.Fatalf("Failed to initialize client: %v", err)
 		}
 	}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 243a292 and 1f54976.

📒 Files selected for processing (7)
  • client/oauth.go (2 hunks)
  • client/transport/oauth.go (1 hunks)
  • client/transport/sse.go (10 hunks)
  • client/transport/sse_oauth_test.go (1 hunks)
  • client/transport/streamable_http.go (1 hunks)
  • client/transport/streamable_http_oauth_test.go (3 hunks)
  • examples/oauth_client/main.go (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
client/transport/streamable_http.go (2)
client/oauth.go (1)
  • OAuthConfig (11-11)
client/transport/oauth.go (1)
  • OAuthConfig (18-34)
client/transport/streamable_http_oauth_test.go (3)
client/transport/streamable_http.go (2)
  • NewStreamableHTTP (84-110)
  • WithHTTPOAuth (44-48)
client/oauth.go (1)
  • OAuthConfig (11-11)
client/transport/oauth.go (1)
  • OAuthConfig (18-34)
examples/oauth_client/main.go (1)
mcp/types.go (6)
  • InitializeRequest (389-398)
  • Params (154-154)
  • ClientCapabilities (427-437)
  • Implementation (468-471)
  • LATEST_PROTOCOL_VERSION (99-99)
  • ListResourcesRequest (526-528)
client/oauth.go (4)
client/transport/streamable_http.go (1)
  • WithHTTPOAuth (44-48)
client/transport/oauth.go (1)
  • OAuthConfig (18-34)
client/transport/sse.go (3)
  • ClientOption (45-45)
  • WithOAuth (65-69)
  • NewSSE (73-99)
client/client.go (2)
  • Client (16-25)
  • NewClient (44-54)
client/transport/sse.go (4)
client/transport/oauth.go (3)
  • OAuthHandler (111-119)
  • OAuthConfig (18-34)
  • NewOAuthHandler (122-131)
client/oauth.go (3)
  • OAuthConfig (11-11)
  • OAuthAuthorizationRequiredError (61-61)
  • GetOAuthHandler (70-76)
client/client.go (1)
  • ClientOption (27-27)
client/transport/streamable_http.go (2)
  • OAuthAuthorizationRequiredError (162-164)
  • ErrOAuthAuthorizationRequired (159-159)
🔇 Additional comments (13)
client/transport/streamable_http.go (1)

43-44: Good naming improvement for API clarity.

Renaming WithOAuth to WithHTTPOAuth clearly distinguishes this option from the SSE transport's OAuth option, improving the API's usability and reducing potential confusion.

client/transport/streamable_http_oauth_test.go (1)

76-76: Test updates correctly reflect the API changes.

All test function calls have been properly updated to use WithHTTPOAuth instead of WithOAuth, maintaining consistency with the renamed function in the implementation.

Also applies to: 166-166, 207-207

client/oauth.go (2)

29-29: Correctly updated to use the renamed function.

The update to transport.WithHTTPOAuth is consistent with the function rename in the transport layer.


40-49: Well-implemented SSE OAuth client constructor.

The new function follows the same pattern as the HTTP OAuth client, with proper error handling and consistent API design. The use of transport.WithOAuth (for SSE) vs transport.WithHTTPOAuth (for HTTP) maintains clear separation between the two transport types.

examples/oauth_client/main.go (3)

46-50: LGTM! Clean retry pattern for OAuth authorization.

The retry logic correctly handles the OAuth authorization flow by calling maybeAuthorize and retrying the Start operation.


89-104: Good addition to demonstrate successful OAuth flow.

The resource listing effectively shows that the client is properly authenticated and can make API calls.


132-136: Verify if client registration is always required.

The code unconditionally calls RegisterClient, which might fail if:

  1. The client is already registered
  2. The server doesn't support dynamic client registration

Consider checking if registration is needed or handling registration errors more gracefully.

client/transport/sse.go (5)

8-8: LGTM! Clean OAuth integration.

The addition of the errors import and oauthHandler field properly sets up OAuth support for the SSE transport.

Also applies to: 41-43


65-70: LGTM! Well-structured client option.

The WithOAuth option follows the established pattern and properly initializes the OAuth handler.


91-97: LGTM! Proper OAuth metadata discovery setup.

The code correctly extracts the base URL and sets it for OAuth metadata discovery.


154-161: LGTM! Consistent 401 error handling.

The code properly handles 401 Unauthorized responses by returning OAuthAuthorizationRequiredError across all methods.

Also applies to: 377-384, 478-485


506-515: LGTM! Useful OAuth status accessors.

The GetOAuthHandler and IsOAuthEnabled methods provide clean access to OAuth configuration status.

client/transport/sse_oauth_test.go (1)

1-238: Excellent test coverage for OAuth functionality!

The tests comprehensively cover:

  • OAuth authorization flow with retry logic
  • 401 Unauthorized error handling
  • OAuth enablement status checking
  • Authorization header verification

The test structure is clean and follows Go testing best practices.

Copy link
Collaborator

@pottekkat pottekkat left a comment

Choose a reason for hiding this comment

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

Thank you. I will wait for others to review this as well and then merge.

@rwjblue-glean rwjblue-glean merged commit 774b17b into mark3labs:main Jun 5, 2025
4 checks passed
@rwjblue-glean
Copy link
Collaborator

Thank you @giridhar-murthy-glean!

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.

4 participants