@hashangit/mcp-browser-client
v0.0.2
Published
A browser-safe client for the Model Context Protocol (MCP) using Server-Sent Events (SSE) with OAuth support.
Maintainers
Readme
MCP Browser Client
@hashangit/mcp-browser-client is a versatile client library for the Model Context Protocol (MCP), specifically designed for use in modern web browsers. It provides multiple robust, browser-safe transport layers (SSE, WebSocket, and HTTP Streaming) and is designed to work with the OAuth 2.1 Authorization Code Flow with PKCE.
This package bundles and re-exports the core components of the official @modelcontextprotocol/sdk, providing a single, convenient dependency for building browser-based MCP applications.
Features
- Multiple Transport Options: Includes a custom Server-Sent Events (SSE) transport and re-exports the official WebSocket and Streamable HTTP transports, all of which are safe for browser use.
- Secure OAuth 2.1 + PKCE: Designed for modern, secure authentication. The
authProvidermodel makes it easy to integrate your PKCE flow logic. - Automatic Reconnection (SSE): The custom SSE transport automatically handles connection retries with backoff strategies.
- Type-Safe: Fully written in TypeScript with exported types for all major components.
- One-Stop Shop: Provides direct access to the
Client, error types, schemas, and transport interfaces from the core SDK, so you only need one dependency.
Installation
Install the package using your favorite package manager:
npm install @hashangit/mcp-browser-clientQuick Start
Here's how to create an MCP client using your choice of transport.
import {
Client,
SSEClientTransport, // or WebSocketClientTransport, StreamableHTTPClientTransport
// ... other necessary imports
} from '@hashangit/mcp-browser-client';
import type { OAuthClientProvider } from '@hashangit/mcp-browser-client';
// 1. Implement your OAuth provider to handle the PKCE flow.
const myAuthProvider: OAuthClientProvider = {
async tokens() {
// This function is responsible for securely storing and retrieving OAuth tokens.
// It should handle the token refresh flow if a token is expired.
// The core SDK provides helpers for the PKCE code challenge.
const token = localStorage.getItem('my_access_token');
if (!token) throw new Error('Not authenticated');
return { access_token: token };
},
// ... other methods to handle the authorization code flow (e.g., authorize())
};
// 2. Choose and configure your transport
const transport = new SSEClientTransport({
url: 'https://your-mcp-server.com/events',
authProvider: myAuthProvider,
});
// 3. Create and start the client
const client = new Client({ transport });
async function main() {
try {
await client.start();
console.log('Client connected successfully!');
const tools = await client.listTools();
console.log('Available tools:', tools);
} catch (error) {
console.error('Failed to connect:', error);
}
}
main();Supported Transports
This package provides and re-exports three browser-safe transports. Choose the one that best fits your server's capabilities.
| Transport | Description | Best For |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| SSEClientTransport | A custom transport using Server-Sent Events (SSE). Implemented with @microsoft/fetch-event-source for reliability and auto-reconnection. | Unidirectional real-time updates from server to client over standard HTTP. |
| WebSocketClientTransport | The standard WebSocket transport from the core SDK. | Bidirectional, low-latency, real-time communication. |
| StreamableHTTPClientTransport | A transport from the core SDK that uses streaming HTTP responses. | Environments where WebSockets are not available but streaming is needed. |
Authentication: OAuth 2.1 with PKCE
Secure authentication is critical. This library is designed to facilitate the OAuth 2.1 Authorization Code Flow with Proof Key for Code Exchange (PKCE).
The responsibility for handling the PKCE handshake (creating a code_verifier and code_challenge, redirecting the user, and exchanging the authorization code for tokens) lies with the OAuthClientProvider implementation you provide.
The @modelcontextprotocol/sdk (which is included in this package) contains helpers that use the browser's Web Crypto API to securely generate the necessary PKCE parameters.
Conceptual PKCE Flow
- User Initiates Login: Your application calls a method like
myAuthProvider.authorize(). - Generate PKCE Parameters: Your provider uses the SDK's helpers to generate a
code_verifierandcode_challenge. - Redirect: The user is redirected to your authorization server with the
code_challenge. - Grant Consent: The user logs in and grants consent.
- Receive Code: The user is redirected back to your application with an
authorization_code. - Exchange for Tokens: Your provider sends the
authorization_codeand the originalcode_verifierto the token endpoint. - Store Tokens: Securely store the returned
access_tokenandrefresh_token. Thetokens()method will then make these available to the MCP client transport.
Refer to the official @modelcontextprotocol/sdk documentation for detailed usage of the authentication and PKCE helpers.
API Reference
SSEClientTransport (alias SseBrowserTransport)
new SSEClientTransport(options: SseBrowserTransportOptions)
| Option | Type | Required | Description |
| -------------- | --------------------- | :------: | ------------------------------------------------------------------------------------------------------- |
| url | string | Yes | The full URL of the MCP server's SSE endpoint. |
| authProvider | OAuthClientProvider | No | An optional provider to handle OAuth authentication using the PKCE flow. |
| headers | Record<string, string> | No | Custom headers to include with every request. |
| timeout | number | No | Connection timeout in milliseconds. |
Building from Source
To build the library from the source code, you'll need Nx installed in the repository.
- Clone the repository.
- Install dependencies.
npm install - Build the library.
The build output will be in thenx build browser-clientpackages/browser-client/distdirectory.
License
This project is licensed under the Apache-2.0 License. See the LICENSE file for details.
