Repository navigation
Description
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
-
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.
-
State Management in
useConnection.ts:- Introduce new state variables to manage the OAuth flow, including
isAuthFlowActive,accessToken, andrefreshToken. - Implement logic to securely store and retrieve tokens, preferably using session storage for this initial implementation.
- Introduce new state variables to manage the OAuth flow, including
-
OAuth Flow Logic in
useConnection.ts:- Modify the
handleConnectfunction 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.
- Modify the
-
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.tsxfor this component.
- Create a new component,
-
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.
- Modify the client's request-making logic to include the
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
Authorizationheader. - The UI clearly indicates when a connection is authenticated.
Activity
integry commentedon Jul 30, 2025
Suggested Implementation
Here is a breakdown of the code changes required to implement OAuth 2.1 support.
1. Update
src/components/ConnectionPanel.tsxAdd a checkbox for the user to manually initiate the OAuth flow.
2. Update
src/hooks/useConnection.tsThis is where the bulk of the logic will reside. We'll add state for OAuth and modify the
handleConnectfunction.3. Create
src/components/OAuthCallback.tsxThis new component will handle the redirect from the authorization server.
4. Update
src/App.tsxAdd a new route for the
OAuthCallbackcomponent.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.
integry commentedon Jul 30, 2025
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-26revision, 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
POSTrequests (for client-to-server messages) andGETrequests (for initiating server-to-client message streams). When a client sends aPOSTrequest containing a JSON-RPC message, the server has the flexibility to respond with either a singleapplication/jsonobject or to upgrade the connection to atext/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
Originheader 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:An SSE endpoint (e.g.,
/sse), to which the client makes aGETrequest to establish a long-lived connection for receiving messages from the server.A separate messaging endpoint (e.g.,
/messages), to which the client sendsPOSTrequests containing its JSON-RPC messages.A key behavior of this legacy transport is that upon connecting to the
/sseendpoint, the server's first message is anendpointevent. This event contains the URI that the client must use for all its subsequentPOSTrequests. A client can use the presence of this initialendpointevent 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
Authorizationheader 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 Unauthorizedstatus code.For servers compliant with the latest specifications (protocol version
2025-06-18and later), this401response is not just an error; it is the trigger for the entire dynamic authentication process. The response MUST include aWWW-Authenticateheader 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.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 :
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).
The user authenticates with the third-party service and grants it permission to share information with the MCP server.
The MCP server receives an authorization code or token from the third-party provider.
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 :
Agent Identity: The AI agent or MCP client itself may possess a distinct, traceable identity, separate from the user's.
Delegator Authentication: The human user (the delegator) must authenticate themselves to the system. This is the standard login process.
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.
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.
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
resourceparameter (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 Unauthorizedresponse 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 aclient_idvia RFC 7591 (Dynamic Client Registration).With the server's endpoints known and a
client_idin 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.
propr-dev commentedon Aug 23, 2025
🤖 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:
claude-opus-4-20250514ai-fix/71-feature-add-oauth-2-1-aut-20250824-0115-claude-opus-4-20250514-4ksmasterissue-71-20250824-0115-claude-opus-4-20250514-4ksfix(ai): Resolve issue #71 - Feature: Add OAuth 2.1 Authentication fo…
Merge pull request #159 from integry/ai-fix/71-feature-add-oauth-2-1-…