npm package: @hashangit/mcp-browser-client
Description: A browser-safe client for the Model Context Protocol (MCP) using Server-Sent Events (SSE) with OAuth support.
Author: hashangit
Latest version: 0.0.2

# MCP Browser Client

[![build](https://github.com/hashangit/mcp-browser-sdk/actions/workflows/main.yml/badge.svg)](https://github.com/hashangit/mcp-browser-sdk/actions/workflows/main.yml)
[![npm version](https://img.shields.io/npm/v/@hashangit/mcp-browser-client.svg)](https://www.npmjs.com/package/@hashangit/mcp-browser-client)
[![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

`@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](https://www.npmjs.com/package/@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 `authProvider` model 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:

```bash
npm install @hashangit/mcp-browser-client
```

## Quick Start

Here's how to create an MCP client using your choice of transport.

```typescript
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

1.  **User Initiates Login**: Your application calls a method like `myAuthProvider.authorize()`.
2.  **Generate PKCE Parameters**: Your provider uses the SDK's helpers to generate a `code_verifier` and `code_challenge`.
3.  **Redirect**: The user is redirected to your authorization server with the `code_challenge`.
4.  **Grant Consent**: The user logs in and grants consent.
5.  **Receive Code**: The user is redirected back to your application with an `authorization_code`.
6.  **Exchange for Tokens**: Your provider sends the `authorization_code` and the original `code_verifier` to the token endpoint.
7.  **Store Tokens**: Securely store the returned `access_token` and `refresh_token`. The `tokens()` 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](https://nx.dev) installed in the repository.

1.  **Clone the repository.**
2.  **Install dependencies.**
    ```bash
    npm install
    ```
3.  **Build the library.**
    ```bash
    nx build browser-client
    ```
    The build output will be in the `packages/browser-client/dist` directory.

## License

This project is licensed under the Apache-2.0 License. See the [LICENSE](LICENSE) file for details.