Skip to content

Feature: Add OAuth 2.1 Authentication for Remote Servers #71

Closed

Description

@integry

Epic: Enhanced Authentication and Security

This is the first issue in a series to enhance the security and authentication capabilities of the MCP Test client. The overall goal is to provide robust support for modern authentication standards, ensuring secure and seamless interaction with a wider range of MCP servers.

Stage: 1 of 2 (Current)

  • Done: The client currently only supports unauthenticated connections.
  • This Issue: Implement the foundational OAuth 2.1 Authorization Code Grant with PKCE flow.
  • Remaining: Future issues will build on this to add features like token refresh, secure token storage, and session management.

Task: Implement OAuth 2.1 Authentication

This task involves adding support for OAuth 2.1 to the MCP client, allowing users to connect to secure, remote MCP servers that require authentication. The implementation should follow the best practices outlined in the Model Context Protocol specification, including the mandatory use of the Authorization Code Grant with PKCE.

Context

As the MCP ecosystem matures, an increasing number of servers will require authentication to protect resources and user data. To maintain its utility as a universal testing tool, the MCP Test client must support the protocol's standardized authentication mechanism. This involves not only implementing the OAuth flow but also providing a clear user interface for initiating and managing authenticated sessions. The client should be able to dynamically discover a server's authentication endpoints and, ideally, handle client registration programmatically, embodying the "zero-configuration" spirit of MCP.

Implementation Steps

  1. UI Enhancements in ConnectionPanel.tsx:

    • Add a checkbox to allow users to manually enable OAuth for a connection.
    • This provides a clear, user-driven way to initiate the authentication flow and serves as a manual override for servers that may not correctly advertise their security requirements via a 401 response.
  2. State Management in useConnection.ts:

    • Introduce new state variables to manage the OAuth flow, including isAuthFlowActive, accessToken, and refreshToken.
    • Implement logic to securely store and retrieve tokens, preferably using session storage for this initial implementation.
  3. OAuth Flow Logic in useConnection.ts:

    • Modify the handleConnect function to check if OAuth is enabled.
    • If OAuth is enabled, the client should attempt to discover the server's OAuth endpoints (as per RFC 8414). For this initial implementation, we can derive the endpoints from the server URL as a fallback.
    • Implement the PKCE challenge generation.
    • Redirect the user to the authorization server's authorization_endpoint.
  4. Create OAuth Callback Handler:

    • Create a new component, OAuthCallback.tsx, to handle the redirect from the authorization server.
    • This component will be responsible for exchanging the authorization code for an access token and storing it.
    • Add a new route in App.tsx for this component.
  5. Authenticated Requests:

    • Modify the client's request-making logic to include the Authorization: Bearer {access_token} header on all MCP requests when an access token is available.

Acceptance Criteria

  • A user can connect to an OAuth-enabled MCP server.
  • The client correctly performs the OAuth Authorization Code Grant with PKCE flow.
  • Authenticated requests include the correct Authorization header.
  • The UI clearly indicates when a connection is authenticated.

Activity

  1. integry commented on Jul 30, 2025

    @integry
    OwnerAuthor

    Suggested Implementation

    Here is a breakdown of the code changes required to implement OAuth 2.1 support.

    1. Update src/components/ConnectionPanel.tsx

    Add a checkbox for the user to manually initiate the OAuth flow.

    // src/components/ConnectionPanel.tsx
    
    import React, { useState, useEffect } from 'react';
    // ... other imports
    
    interface ConnectionPanelProps {
      // ... other props
      useOAuth: boolean;
      setUseOAuth: (useOAuth: boolean) => void;
    }
    
    const ConnectionPanel: React.FC<ConnectionPanelProps> = ({
      // ... other props
      useOAuth,
      setUseOAuth,
    }) => {
      // ... existing code
    
      return (
        <div className={`card mb-3 ${isConnected ? 'border-success' : ''}`}>
          {/* ... existing card header */}
          <div className="card-body">
            <div className="mb-3">
              {/* ... existing server URL input */}
            </div>
            <div className="form-check mb-3">
              <input
                className="form-check-input"
                type="checkbox"
                id="useOAuthCheck"
                checked={useOAuth}
                onChange={(e) => setUseOAuth(e.target.checked)}
                disabled={isConnecting || isConnected}
              />
              <label className="form-check-label" htmlFor="useOAuthCheck">
                Use OAuth Authentication
              </label>
            </div>
            {/* ... existing connection error card */}
          </div>
        </div>
      );
    };
    
    export default ConnectionPanel;

    2. Update src/hooks/useConnection.ts

    This is where the bulk of the logic will reside. We'll add state for OAuth and modify the handleConnect function.

    // src/hooks/useConnection.ts
    
    // ... other imports
    import pkceChallenge from 'pkce-challenge';
    
    export const useConnection = (addLogEntry: (entryData: Omit<LogEntry, 'timestamp'>) => void) => {
      // ... existing state
      const [useOAuth, setUseOAuth] = useState(false);
      const [accessToken, setAccessToken] = useState<string | null>(null);
    
      // ... existing functions
    
      const handleConnect = useCallback(async (
        // ... existing params
      ) => {
        // ... existing code
    
        if (useOAuth) {
          // Initiate OAuth flow
          const { code_verifier, code_challenge } = pkceChallenge();
          sessionStorage.setItem('pkce_code_verifier', code_verifier);
    
          const authUrl = new URL(`${targetUrl}/oauth/authorize`);
          authUrl.searchParams.set('response_type', 'code');
          authUrl.searchParams.set('client_id', 'mcptest-client'); // This should be dynamic in a real app
          authUrl.searchParams.set('redirect_uri', `${window.location.origin}/oauth/callback`);
          authUrl.searchParams.set('code_challenge', code_challenge);
          authUrl.searchParams.set('code_challenge_method', 'S256');
          authUrl.searchParams.set('scope', 'openid profile email');
    
          window.location.href = authUrl.toString();
          return;
        }
    
        // ... existing connection logic for non-OAuth
      }, [serverUrl, isConnecting, connectionStatus, addLogEntry, cleanupConnection, useOAuth]);
    
      return {
        // ... existing exports
        useOAuth,
        setUseOAuth,
        accessToken,
      };
    };

    3. Create src/components/OAuthCallback.tsx

    This new component will handle the redirect from the authorization server.

    // src/components/OAuthCallback.tsx
    
    import React, { useEffect } from 'react';
    import { useLocation, useNavigate } from 'react-router-dom';
    
    const OAuthCallback: React.FC = () => {
      const location = useLocation();
      const navigate = useNavigate();
    
      useEffect(() => {
        const handleOAuthCallback = async () => {
          const params = new URLSearchParams(location.search);
          const code = params.get('code');
          const codeVerifier = sessionStorage.getItem('pkce_code_verifier');
    
          if (code && codeVerifier) {
            try {
              const tokenResponse = await fetch('/oauth/token', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                  grant_type: 'authorization_code',
                  code,
                  redirect_uri: `${window.location.origin}/oauth/callback`,
                  client_id: 'mcptest-client',
                  code_verifier: codeVerifier,
                }),
              });
    
              if (tokenResponse.ok) {
                const { access_token } = await tokenResponse.json();
                sessionStorage.setItem('oauth_access_token', access_token);
                sessionStorage.removeItem('pkce_code_verifier');
                navigate('/'); // Redirect to home page
              } else {
                console.error('Failed to exchange authorization code for token');
                navigate('/');
              }
            } catch (error) {
              console.error('Error during token exchange:', error);
              navigate('/');
            }
          }
        };
    
        handleOAuthCallback();
      }, [location, navigate]);
    
      return <div>Processing authentication...</div>;
    };
    
    export default OAuthCallback;

    4. Update src/App.tsx

    Add a new route for the OAuthCallback component.

    // src/App.tsx
    
    // ... other imports
    import OAuthCallback from './components/OAuthCallback';
    import { Routes, Route } from 'react-router-dom';
    
    function App() {
      // ... existing code
    
      return (
        <div className="container-fluid vh-100 d-flex flex-column p-0">
          {/* ... existing layout */}
          <Routes>
            <Route path="/oauth/callback" element={<OAuthCallback />} />
            {/* Other routes */}
          </Routes>
        </div>
      );
    }

    This implementation provides a solid foundation for OAuth 2.1 support in the MCP client. Future work will involve enhancing token management, implementing automatic token refresh, and improving the user experience around authenticated sessions.

  2. integry commented on Jul 30, 2025

    @integry
    OwnerAuthor

    Here is some general context for Oauth in MCP:

    Implementing Secure Authentication in a Model Context Protocol Client for Arbitrary Remote Servers

    The MCP Authentication Mandate: A Framework for Zero-Configuration Interoperability

    The Model Context Protocol (MCP) represents a fundamental shift in how artificial intelligence systems interact with external data and tools. To achieve its vision of a vast, interoperable ecosystem, MCP standardizes not only the data exchange format but also, critically, the mechanism for authentication and authorization. This standardized approach is a deliberate design choice that moves beyond the fragmented landscape of bespoke integrations, enabling a new class of AI clients capable of securely connecting to any compliant server with minimal configuration.

    The Problem with Bespoke Integrations in AI Ecosystems

    Before the introduction of the Model Context Protocol in November 2024, connecting an AI model or agent to an external tool—such as a CRM, database, or code repository—required custom, one-off integration code. This approach created a brittle and non-scalable ecosystem plagued by information silos and legacy system compatibility issues. Each new integration demanded that developers handle a unique authentication method, be it API keys, custom bearer tokens, or other proprietary schemes. This forced client application developers, such as those building AI-powered IDEs or chat interfaces, to manage a complex and insecure web of credentials, hindering the development of truly versatile and context-aware AI agents.

    MCP's Solution: A Prescriptive OAuth 2.1 Profile

    The core of MCP's solution to this fragmentation is not merely the adoption of OAuth, but the mandating of a specific, prescriptive profile of the OAuth 2.1 framework. This is a significant departure from more flexible standards like OpenAPI, which permit developers to choose from a variety of authentication mechanisms. While flexibility is advantageous in other contexts, MCP's primary goal is to enable any client to connect to any server seamlessly, much like a web browser connects to any website. This requires a single, reliable, and predictable authentication path.

    This prescriptive approach ensures that a sophisticated client application, such as Cursor or Claude Desktop, can connect to a new, previously unknown MCP server without requiring manual setup or custom code. The MCP specification explicitly requires OAuth 2.1, which codifies the latest security best practices from the Internet Engineering Task Force (IETF), including the mandatory use of Proof Key for Code Exchange (PKCE) for all clients. This decision to enforce a strict standard is the cornerstone of the protocol's "plug-and-play" vision.

    Core Principles: User Consent, Security Boundaries, and Dynamic Connectivity

    The MCP authentication framework is built on three foundational principles that govern the interaction between users, clients, and servers.

    • User Consent and Control: A central tenet of both MCP and the underlying OAuth 2.1 protocol is that the user, as the Resource Owner, must explicitly grant permission for any data access or action. The MCP client acts as a delegate on behalf of the user, and this delegation must be transparent, informed, and auditable. The protocol's security guidelines stipulate that client applications must provide clear user interfaces for reviewing and authorizing all activities, ensuring the user retains ultimate control.

    • Security Boundaries: The MCP architecture, which consists of a Host application managing multiple Clients connected to various Servers, is designed to enforce strict isolation. Authentication is key to maintaining these boundaries. For example, a token granting access to a GitHub MCP server cannot be used to access a Slack MCP server. Each server connection is a distinct, sandboxed session, and the Host is responsible for aggregating context and controlling cross-server interactions, preventing one tool from illicitly accessing the context of another.

    • Dynamic Connectivity: The ultimate goal of "zero-configuration" or "plug-and-play" connectivity is made technically feasible by leveraging modern, and often less common, extensions to the OAuth framework. Specifically, MCP's authentication model relies on OAuth 2.0 Authorization Server Metadata (RFC 8414) for automated discovery of a server's authentication endpoints and OAuth 2.0 Dynamic Client Registration Protocol (RFC 7591) for programmatic, on-the-fly client registration. These two specifications are the technical bedrock that allows a client to onboard with an arbitrary server without a developer needing to manually copy and paste credentials from a web portal.

    The decision to mandate a strict authentication profile is thus not a mere security feature; it is the primary enabler of MCP's core value proposition. The protocol's ambition to create a permissioned, interoperable ecosystem for AI agents—analogous to what HTTP, HTML, and DNS did for the web—is predicated on this standardized handshake. It transforms the fundamental development question from "How do I connect my app to this specific tool?" to "How do I make my app speak the universal language of MCP authentication?"

    The Transport Layer: Where Authentication Meets the Protocol

    The Model Context Protocol is designed to be transport-agnostic, but for remote communication, it standardizes on a modern, flexible mechanism known as "Streamable HTTP." This transport layer defines how clients and servers exchange JSON-RPC messages and, crucially, how the authentication process is initiated. An MCP client built for interoperability must understand both this modern transport and its legacy predecessor to connect to any arbitrary server.

    Analysis of the Modern "Streamable HTTP" Transport

    The MCP specification, beginning with the 2025-03-26 revision, formalizes the "Streamable HTTP" transport for remote server communication. This architecture represents a significant improvement over the previous model, simplifying implementation and enhancing compatibility with modern web infrastructure.

    The core of this transport is a single HTTP endpoint that supports both POST requests (for client-to-server messages) and GET requests (for initiating server-to-client message streams). When a client sends a

    POST request containing a JSON-RPC message, the server has the flexibility to respond with either a single application/json object or to upgrade the connection to a text/event-stream (Server-Sent Events, or SSE) for streaming multiple responses or notifications. This adaptability allows a single endpoint to support both simple, stateless request-response interactions and more complex, stateful, real-time communication.

    This evolution from the older, two-endpoint system was a necessary step to enable robust, scalable, and stateless remote servers, which are critical for a mature ecosystem. The legacy transport's stateful, dual-channel nature was a bottleneck for public, cloud-hosted MCP servers. Streamable HTTP aligns the protocol with standard web service patterns, making it easier to deploy, scale, and secure behind common infrastructure like load balancers and API gateways.

    A critical security warning accompanies this transport: servers MUST validate the Origin header on incoming requests to prevent DNS rebinding attacks, and they SHOULD implement proper authentication for all connections.

    Handling Legacy: The Deprecated HTTP+SSE Transport

    For backward compatibility with servers running older versions of the protocol (specifically 2024-11-05), a client must also be prepared to handle the legacy HTTP+SSE transport. This older mechanism is distinguished by its use of two separate endpoints:

    1. An SSE endpoint (e.g., /sse), to which the client makes a GET request to establish a long-lived connection for receiving messages from the server.

    2. A separate messaging endpoint (e.g., /messages), to which the client sends POST requests containing its JSON-RPC messages.

    A key behavior of this legacy transport is that upon connecting to the /sse endpoint, the server's first message is an endpoint event. This event contains the URI that the client must use for all its subsequent POST requests. A client can use the presence of this initial

    endpoint event as a reliable signal that it is communicating with a server using the legacy transport model.

    Integrating the Authorization Header and Handling 401 Unauthorized Responses

    Regardless of the transport version, authenticated requests to an MCP server are made by including a standard Authorization header with a Bearer token obtained via the OAuth flow: Authorization: Bearer {access_token}.

    The critical link between the MCP transport layer and the OAuth authentication framework is the server's response to an unauthenticated request. When a client attempts to access a protected resource without a valid token, the MCP server MUST respond with an HTTP 401 Unauthorized status code.

    For servers compliant with the latest specifications (protocol version 2025-06-18 and later), this 401 response is not just an error; it is the trigger for the entire dynamic authentication process. The response MUST include a WWW-Authenticate header that points the client to the server's OAuth 2.0 Protected Resource Metadata URL, as defined in RFC 9728. This header acts as the starting pistol, directing the client to begin the automated OAuth discovery and authorization sequence.

    Feature Streamable HTTP (Protocol >= 2025-03-26) Legacy HTTP+SSE (Protocol 2024-11-05)
    Endpoint(s) Single endpoint (e.g., /mcp) supporting POST and GET. Two separate endpoints: one for SSE (GET) and one for messages (POST).
    Connection Initiation Client sends a POST or GET to the single endpoint. A POST can be upgraded to an SSE stream by the server. Client connects to the SSE endpoint first, receives an endpoint event, then uses that URI for POST requests.
    Client-to-Server POST request to the single endpoint. POST request to the message endpoint URI provided by the server.
    Server-to-Client Can be a single JSON response to a POST or a stream of events via SSE on either a POST or GET connection. All server messages are sent over the initial, long-lived SSE connection.
    Authentication Trigger 401 Unauthorized response with a WWW-Authenticate header pointing to resource metadata. 401 Unauthorized response. The client must fall back to deriving the auth server URL from the MCP server URL.
    Export to Sheets

    Advanced Security Postures and Ecosystem Considerations

    Beyond the core authentication flow, a comprehensive understanding of the MCP security model involves recognizing more advanced authorization patterns and the broader principles governing the ecosystem. These concepts provide context for building truly secure, robust, and auditable agentic applications.

    Understanding Delegated Authorization and Third-Party Auth Servers

    The MCP specification accommodates a sophisticated pattern known as delegated authorization, where an MCP server can act as an OAuth client to another, third-party authorization server, such as Google, Microsoft, or GitHub.

    In this "double-hop" flow, the MCP server orchestrates the entire process :

    1. The user is redirected from the MCP client to the MCP server, which then redirects them to the third-party identity provider (e.g., Google's login page).

    2. The user authenticates with the third-party service and grants it permission to share information with the MCP server.

    3. The MCP server receives an authorization code or token from the third-party provider.

    4. The MCP server then issues its own, separate access token to the MCP client. This new token is bound to the user's session with the third-party service.

    While the majority of this complexity resides on the server side, a client developer should be aware of this pattern. It explains why, when connecting to a specific tool's MCP server, the user might be presented with a familiar login screen from a major identity provider.

    The Five Layers of Identity in MCP: Agent, Delegator, and Consent

    Building secure agentic systems requires thinking beyond simple token exchange. A more complete security model for MCP involves at least five distinct layers of identity and authorization, each with its own policy surface :

    1. Agent Identity: The AI agent or MCP client itself may possess a distinct, traceable identity, separate from the user's.

    2. Delegator Authentication: The human user (the delegator) must authenticate themselves to the system. This is the standard login process.

    3. Consent from Delegator to Agent: This is a separate, explicit step where the user defines what the agent is allowed to do on their behalf, under what conditions, and with what constraints. This goes beyond simple OAuth scopes.

    4. Access to MCP Server: The agent must authenticate to the MCP server to gain access to its tools and resources. This is the primary focus of the OAuth flow detailed in this report.

    5. Access to Upstream Services: The MCP server itself may need to authenticate to backend APIs (e.g., a database or a third-party API like Gmail).

    The OAuth 2.1 flow described herein primarily addresses layers 2, 3, and 4. A mature, production-grade agentic system must consider policies and controls at all five layers.

    Adhering to OAuth 2.1 Best Current Practices (RFC 9700)

    Finally, all implementations should be guided by the industry consensus on OAuth 2.0 Security Best Current Practices, as codified in BCP 212 and RFC 9700. The MCP authentication specification is a profile of these best practices. Key principles to reiterate are:

    • Always use the Authorization Code flow with PKCE. Deprecated flows like Implicit and Resource Owner Password Credentials (ROPC) must not be used.

    • Enforce strict redirect URI validation, allowing only exact matches of pre-registered URIs.

    • Adhere to the principle of least privilege by requesting the minimum necessary scopes for a given task.

    • Utilize short-lived access tokens and securely managed, rotated refresh tokens.

    • Constrain token audience using the resource parameter (RFC 8707) to prevent token misuse.

    By adhering to these principles, a developer can build an MCP client that is not only compliant with the protocol but is also robust, secure, and aligned with the highest standards of modern application security.

    Conclusion

    Implementing authentication for a Model Context Protocol client designed to connect to arbitrary remote servers is a complex but well-defined process. The protocol's prescriptive adoption of a modern OAuth 2.1 profile, while demanding, is the key to its vision of a secure and interoperable AI ecosystem. A successful implementation hinges on a thorough understanding of a sequence of standardized, interconnected mechanisms.

    The journey begins with the Streamable HTTP transport and the critical 401 Unauthorized response that initiates the entire flow. From there, the client must execute a two-part automated handshake: first, discovering the authorization server's capabilities via RFC 8414 (Authorization Server Metadata), and second, programmatically registering itself to obtain a client_id via RFC 7591 (Dynamic Client Registration).

    With the server's endpoints known and a client_id in hand, the client must then execute the Authorization Code Grant with mandatory PKCE, a flow specifically chosen to protect public clients like desktop and native applications. To further harden security against agent-specific threats like the "confused deputy" problem, the implementation must leverage RFC 8707 (Resource Indicators) to bind every token to its specific intended audience.

    Finally, the client must demonstrate operational robustness through a comprehensive token management strategy. This includes securely storing refresh tokens in the operating system's keychain, implementing refresh token rotation to mitigate leakage risks, and building a resilient error-handling state machine that can gracefully manage token expiration and session invalidation. By systematically implementing each of these components, developers can build powerful, context-aware MCP clients that can securely and seamlessly connect to the growing universe of AI tools and services.

  3. propr-dev commented on Aug 23, 2025

    @propr-dev
    Contributor

    🤖 AI processing has started for this issue using claude-opus-4-20250514 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Model: claude-opus-4-20250514
    • Branch: ai-fix/71-feature-add-oauth-2-1-aut-20250824-0115-claude-opus-4-20250514-4ks
    • Base Branch: master
    • Worktree: issue-71-20250824-0115-claude-opus-4-20250514-4ks
  4. added a commit that references this issue on Aug 23, 2025
  5. added a commit that references this issue on Aug 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions