npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

browser-mcp-client

v1.0.4

Published

Model Context Protocol Client

Downloads

61

Readme

MCP Client

仓库地址: https://gitee.com/mofum/browser-mcp-client

Model Context Protocol (MCP) 客户端库,提供与MCP协议服务器通信的完整功能,支持多种传输方式和认证机制,适用于各类AI模型交互场景。

📦 安装

使用npm安装:

npm install browser-mcp-client

或者使用yarn:

yarn add browser-mcp-client

🚀 快速开始

基本用法

// 导入客户端类
import { Client } from 'browser-mcp-client/client/index.js';

// 导入传输层实现(根据需要选择)
import { SSEClientTransport } from 'browser-mcp-client/client/sse.js';
import { StreamableClientTransport } from 'browser-mcp-client/client/streamableHttp.js';
import { WebSocketClientTransport } from 'browser-mcp-client/client/websocket.js';

// 导入类型定义(TypeScript项目)
import type { ClientOptions, TransportOptions } from 'browser-mcp-client/types.js';

// 创建客户端实例
const client = new Client({
  name: "MyMCPApplication",
  version: "1.0.0"
}, {
  serverUrl: 'http://localhost:3000',
  transport: new WebSocketClientTransport({})
});

// 连接到服务器
await client.connect();

// 发送消息
const response = await client.request({
  method: "completion/complete",
  params: {
    prompt: "写一首关于编程的诗",
    maxTokens: 100
  }
});

console.log('Received response:', response);

// 监听事件
client.on('notification', (notification) => {
  console.log('Received notification:', notification);
});

// 断开连接
await client.disconnect();

📁 目录结构

├── client/              # 客户端实现
│   ├── index.js         # 客户端主入口
│   ├── sse.js           # SSE传输实现
│   ├── streamableHttp.js # Streamable HTTP传输实现
│   ├── websocket.js     # WebSocket传输实现
│   └── auth.js          # 认证模块
├── shared/              # 共享工具和协议定义
│   ├── protocol.js      # 协议定义
│   ├── transport.js     # 传输层接口
│   └── auth-utils.js    # 认证工具
├── types.js             # JavaScript类型定义
└── types.d.ts           # TypeScript类型定义

🔧 核心功能

传输层

MCP Client支持三种不同的传输层实现,您可以根据项目需求选择最合适的方式:

  • WebSocket:全双工通信,适用于需要实时双向通信的场景,如聊天应用、实时数据更新等

    import { WebSocketClientTransport } from 'browser-mcp-client/client/websocket.js';
      
    const transport = new WebSocketClientTransport({
      url: 'ws://localhost:3000/ws',
      reconnect: {
        enabled: true,
        maxAttempts: 5,
        delay: 1000
      }
    });
  • SSE (Server-Sent Events):单向服务器推送,适用于服务器需要主动发送更新的场景,如进度更新、状态变化等

    import { SSEClientTransport } from 'browser-mcp-client/client/sse.js';
      
    const transport = new SSEClientTransport({
      url: 'http://localhost:3000/sse'
    });
  • Streamable HTTP:基于HTTP的流式通信,适用于需要支持旧浏览器或HTTP代理的场景

    import { StreamableClientTransport } from 'browser-mcp-client/client/streamableHttp.js';
      
    const transport = new StreamableClientTransport({
      url: 'http://localhost:3000/api'
    });

认证

支持OAuth 2.0认证流程,包括PKCE挑战,确保安全的客户端认证:

import { Auth } from 'browser-mcp-client/client/auth.js';

const auth = new Auth({
  clientId: 'your-client-id',
  authorizationEndpoint: 'https://auth.example.com/oauth2/authorize',
  tokenEndpoint: 'https://auth.example.com/oauth2/token',
  redirectUri: 'https://your-app.com/callback',
  scopes: ['read', 'write']
});

// 使用认证配置创建客户端
const client = new Client({
  name: "MyApp",
  version: "1.0.0"
}, {
  serverUrl: 'http://localhost:3000',
  transport: new WebSocketClientTransport({}),
  auth
});

消息处理

提供完整的消息序列化、反序列化和验证功能,确保与服务器通信的正确性和一致性:

// 发送请求并指定响应验证模式
const result = await client.request({
  method: "prompts/get",
  params: {
    id: "prompt-123"
  }
}, GetPromptResultSchema);

// 发送不需要响应的通知
await client.notification({
  method: "logging/setLevel",
  params: {
    level: "info"
  }
});

会话管理

自动管理与服务器的会话状态,处理连接断开、重连等场景:

// 监听连接状态变化
client.on('connect', () => {
  console.log('Connected to server');
});

client.on('disconnect', (reason) => {
  console.log('Disconnected from server:', reason);
});

client.on('error', (error) => {
  console.error('Client error:', error);
});

📋 类型支持

完整的TypeScript类型定义,提供更好的开发体验和类型安全:

import type {
  ClientOptions,
  TransportOptions,
  Request,
  Notification,
  Result,
  Capabilities,
  AuthOptions
} from 'browser-mcp-client/types.js';

// 创建类型化客户端
const client = new Client<MyCustomRequest, MyCustomNotification, MyCustomResult>({
  name: "TypedClient",
  version: "1.0.0"
}, {
  serverUrl: 'http://localhost:3000',
  transport: new WebSocketClientTransport({})
});

⚙️ 配置选项

客户端配置

const clientOptions = {
  name: "MyApplication",  // 应用名称
  version: "1.0.0"        // 应用版本
};

const transportOptions = {
  serverUrl: 'http://localhost:3000',  // 服务器URL
  transport: null,                     // 传输层实例
  auth: null,                          // 认证配置
  reconnect: {
    enabled: true,                    // 是否启用自动重连
    maxAttempts: 5,                   // 最大重连次数
    delay: 1000                       // 重连间隔(毫秒)
  },
  timeout: 30000                       // 请求超时时间(毫秒)
};

const client = new Client(clientOptions, transportOptions);

能力注册

可以注册客户端支持的能力,以便服务器了解客户端的功能:

client.registerCapabilities({
  prompts: {
    create: true,
    update: true
  },
  resources: {
    read: true,
    subscribe: true
  },
  sampling: true,
  elicitation: true
});

📚 实用示例

MCP Client库提供了多个示例,展示如何在不同场景下使用该库:

1. WebSocket示例

展示如何使用WebSocket传输层进行实时双向通信。位于 examples/websocket-demo/ 目录。

2. SSE示例

展示如何使用Server-Sent Events接收服务器推送的实时更新。位于 examples/sse-demo/ 目录。

3. Streamable HTTP示例

展示如何使用基于HTTP的流式通信。位于 examples/streamable-demo/ 目录。

4. VSCode布局示例

展示如何构建类似VSCode的界面布局。位于 examples/vscode-layout-demo/ 目录。

🤝 兼容性

  • 支持现代浏览器(Chrome 90+, Firefox 88+, Safari 14+, Edge 90+)
  • 支持Node.js 16+环境
  • 使用ES模块语法
  • 兼容TypeScript 4.5+项目

🔍 常见操作示例

完成请求

// 请求AI模型生成内容
const completionResult = await client.request({
  method: "completion/complete",
  params: {
    prompt: "解释什么是MCP协议",
    maxTokens: 200,
    temperature: 0.7
  }
}, CompleteResultSchema);

console.log("生成的内容:", completionResult.content);

获取提示词列表

// 获取服务器上可用的提示词列表
const promptsResult = await client.request({
  method: "prompts/list",
  params: {
    limit: 10,
    offset: 0
  }
}, ListPromptsResultSchema);

console.log("可用的提示词:", promptsResult.items);

调用工具

// 调用服务器提供的工具
const toolResult = await client.request({
  method: "tools/call",
  params: {
    toolId: "calculator",
    parameters: {
      operation: "add",
      a: 5,
      b: 3
    }
  }
}, CallToolResultSchema);

console.log("计算结果:", toolResult.result);

资源订阅

// 订阅资源更新
await client.request({
  method: "resources/subscribe",
  params: {
    resourceUri: "resource://example/data"
  }
}, EmptyResultSchema);

// 监听资源更新通知
client.on('notification', (notification) => {
  if (notification.method === "notifications/resources/updated") {
    console.log("资源已更新:", notification.params.resourceUri);
  }
});

📄 许可证

MIT