@modelcontextprotocol/sdk
    Preparing search index...

    Function withOAuth

    • Creates a fetch wrapper that handles OAuth authentication automatically.

      This wrapper will:

      • Add Authorization headers with access tokens
      • Handle 401 responses by attempting re-authentication
      • Retry the original request after successful auth
      • Handle OAuth errors appropriately (InvalidClientError, etc.)

      The baseUrl parameter is optional and defaults to using the domain from the request URL. However, you should explicitly provide baseUrl when:

      • Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com)
      • Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /)
      • The OAuth server is on a different domain than your API requests
      • You want to ensure consistent OAuth behavior regardless of request URLs

      For MCP transports, set baseUrl to the same URL you pass to the transport constructor.

      Note: This wrapper is designed for general-purpose fetch operations. MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling and should not need this wrapper.

      Parameters

      • provider: OAuthClientProvider

        OAuth client provider for authentication

      • OptionalbaseUrl: string | URL

        Base URL for OAuth server discovery (defaults to request URL domain)

      Returns Middleware

      A fetch middleware function