@mcp-fe/mcp-worker 0.0.15 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +454 -37
  2. package/package.json +7 -1
package/README.md CHANGED
@@ -1,62 +1,479 @@
1
1
  # @mcp-fe/mcp-worker
2
2
 
3
- This library provides a client adapter and ready-to-use worker scripts for working with MCP (Model Context Protocol).
3
+ The core package of the MCP-FE (Model Context Protocol - Frontend Edge) ecosystem. This library provides a browser-based MCP server implementation using Web Workers, enabling AI agents to query real-time frontend application state and user interaction data.
4
4
 
5
- Exports
5
+ ## Overview
6
6
 
7
- - `index` the main client module (exports the `workerClient` singleton and related types). Import this in your client application.
8
- - `mcp-service-worker.js` — Service Worker implementation intended to be registered via `navigator.serviceWorker.register(...)`.
9
- - `mcp-shared-worker.js` — SharedWorker implementation intended to be started via `new SharedWorker(...)`.
7
+ `@mcp-fe/mcp-worker` turns your browser into an active, queryable MCP node by running MCP server endpoints in a Web Worker. It bridges the gap between AI agents and the live state of your frontend application, making runtime data accessible through standard MCP tools.
10
8
 
11
- Note: Worker script files (service/shared) must be available on your application's public path so the browser can fetch them (for example `/mcp-service-worker.js` and `/mcp-shared-worker.js`).
9
+ ### Key Features
12
10
 
13
- Quick start
11
+ - **Browser-based MCP Server**: Full MCP server implementation running in Web Workers
12
+ - **Dual Worker Support**: Uses SharedWorker (preferred) with ServiceWorker fallback
13
+ - **IndexedDB Storage**: Persistent storage for user events and application state
14
+ - **WebSocket Transport**: Real-time connection to MCP proxy servers
15
+ - **Zero Backend Dependencies**: Runs entirely in the browser
16
+ - **Authentication Support**: Built-in token-based authentication
17
+ - **Connection Management**: Automatic reconnection and status monitoring
14
18
 
15
- 1) Make worker files available on your public path
19
+ ## Architecture
16
20
 
17
- - Copy the worker files (`mcp-service-worker.js`, `mcp-shared-worker.js`) into the folder your webserver serves as public (for example `public/` or `dist/`).
18
- - Important: the URL used during registration must match the actual location of the files. The `WorkerClient` defaults to `/mcp-shared-worker.js` and `/mcp-service-worker.js`.
19
- If you place them elsewhere, pass the correct URLs to `init`.
21
+ The package implements a **Worker-as-MCP-Edge-Server** pattern:
20
22
 
21
- 3) Import and initialize in your client app
23
+ ```
24
+ Frontend App ←→ WorkerClient ←→ Web Worker (MCP Server) ←→ WebSocket ←→ MCP Proxy ←→ AI Agent
25
+ ```
22
26
 
23
- Example (TypeScript):
27
+ 1. **Frontend App**: Uses `workerClient` to send events and queries
28
+ 2. **WorkerClient**: Manages worker lifecycle and provides clean API
29
+ 3. **Web Worker**: Implements MCP server endpoints, stores data in IndexedDB
30
+ 4. **WebSocket**: Maintains persistent connection to MCP proxy server
31
+ 5. **MCP Proxy**: Bridges browser worker with external AI agents
32
+ 6. **AI Agent**: Queries frontend state using standard MCP tools
24
33
 
25
- ```ts
26
- import { workerClient } from '@mcp-fe/mcp-worker';
34
+ ## Installation
27
35
 
28
- // Optionally provide custom worker URLs and backend WebSocket URL
29
- await workerClient.init({
30
- sharedWorkerUrl: '/mcp-shared-worker.js',
31
- serviceWorkerUrl: '/mcp-service-worker.js',
32
- backendWsUrl: 'wss://your-backend.example/ws'
36
+ ```bash
37
+ npm install @mcp-fe/mcp-worker
38
+ # or
39
+ pnpm add @mcp-fe/mcp-worker
40
+ # or
41
+ yarn add @mcp-fe/mcp-worker
42
+ ```
43
+
44
+ ## Quick Start
45
+
46
+ ### 1. Copy Worker Files to Public Directory
47
+
48
+ The package exports pre-built worker scripts that must be accessible from your web server:
49
+
50
+ ```bash
51
+ # Copy worker files to your public directory
52
+ cp node_modules/@mcp-fe/mcp-worker/mcp-shared-worker.js public/
53
+ cp node_modules/@mcp-fe/mcp-worker/mcp-service-worker.js public/
54
+ ```
55
+
56
+ For build tools like Vite, Webpack, or Nx, you can configure them to copy these files automatically:
57
+
58
+ **Vite example:**
59
+ ```typescript
60
+ // vite.config.ts
61
+ import { defineConfig } from 'vite';
62
+
63
+ export default defineConfig({
64
+ // ... other config
65
+ publicDir: 'public',
66
+ build: {
67
+ rollupOptions: {
68
+ // Copy worker files during build
69
+ external: ['@mcp-fe/mcp-worker/mcp-*.js']
70
+ }
71
+ }
33
72
  });
73
+ ```
74
+
75
+ ### 2. Initialize in Your Application
76
+
77
+ ```typescript
78
+ import { workerClient } from '@mcp-fe/mcp-worker';
79
+
80
+ // Initialize the worker client
81
+ async function initMCP() {
82
+ try {
83
+ await workerClient.init({
84
+ sharedWorkerUrl: '/mcp-shared-worker.js', // optional, default value
85
+ serviceWorkerUrl: '/mcp-service-worker.js', // optional, default value
86
+ backendWsUrl: 'ws://localhost:3001' // your MCP proxy server
87
+ });
88
+
89
+ console.log('MCP Worker initialized successfully');
90
+ } catch (error) {
91
+ console.error('Failed to initialize MCP Worker:', error);
92
+ }
93
+ }
94
+
95
+ // Call during app startup
96
+ initMCP();
97
+ ```
98
+
99
+ ### 3. Set Authentication Token (Optional)
100
+
101
+ ```typescript
102
+ // Set authentication token for user-specific data
103
+ workerClient.setAuthToken('Bearer your-jwt-token-here');
104
+
105
+ // Or queue the token before initialization
106
+ workerClient.setAuthToken('Bearer token');
107
+ await workerClient.init(/* options */);
108
+ ```
109
+
110
+ ## API Reference
111
+
112
+ ### WorkerClient
34
113
 
35
- // Set an auth token (if you use authentication)
36
- workerClient.setAuthToken('Bearer ...');
114
+ The main singleton instance for communicating with the MCP worker.
37
115
 
38
- // Send an event to the worker (fire-and-forget)
39
- await workerClient.post('STORE_EVENT', { event: { /* ... */ } });
116
+ #### `workerClient.init(options?)`
40
117
 
41
- // Request events (request/response)
42
- const res = await workerClient.request('GET_EVENTS');
43
- if (res && (res as any).events) {
44
- console.log('Events:', (res as any).events);
118
+ Initializes the worker client with optional configuration.
119
+
120
+ **Parameters:**
121
+ - `options?: WorkerClientInitOptions | ServiceWorkerRegistration`
122
+
123
+ **WorkerClientInitOptions:**
124
+ ```typescript
125
+ interface WorkerClientInitOptions {
126
+ sharedWorkerUrl?: string; // Default: '/mcp-shared-worker.js'
127
+ serviceWorkerUrl?: string; // Default: '/mcp-service-worker.js'
128
+ backendWsUrl?: string; // Default: 'ws://localhost:3001'
45
129
  }
46
130
  ```
47
131
 
48
- Alternatively, register the Service Worker yourself and pass the registration to `init`:
132
+ **Examples:**
133
+ ```typescript
134
+ // Basic initialization with defaults
135
+ await workerClient.init();
136
+
137
+ // Custom configuration
138
+ await workerClient.init({
139
+ backendWsUrl: 'wss://my-mcp-proxy.com/ws',
140
+ sharedWorkerUrl: '/workers/mcp-shared-worker.js'
141
+ });
49
142
 
50
- ```ts
51
- // register the service worker (e.g. in your app entry file)
143
+ // Use existing ServiceWorker registration
52
144
  const registration = await navigator.serviceWorker.register('/mcp-service-worker.js');
53
145
  await workerClient.init(registration);
54
146
  ```
55
147
 
56
- Notes & best practices
148
+ #### `workerClient.post(type, payload?)`
149
+
150
+ Send a fire-and-forget message to the worker.
151
+
152
+ **Parameters:**
153
+ - `type: string` - Message type
154
+ - `payload?: Record<string, unknown>` - Message payload
155
+
156
+ **Example:**
157
+ ```typescript
158
+ // Store a user event
159
+ await workerClient.post('STORE_EVENT', {
160
+ event: {
161
+ type: 'click',
162
+ element: 'button',
163
+ elementText: 'Submit Form',
164
+ path: '/checkout',
165
+ timestamp: Date.now()
166
+ }
167
+ });
168
+ ```
169
+
170
+ #### `workerClient.request(type, payload?, timeoutMs?)`
171
+
172
+ Send a request expecting a response via MessageChannel.
173
+
174
+ **Parameters:**
175
+ - `type: string` - Request type
176
+ - `payload?: Record<string, unknown>` - Request payload
177
+ - `timeoutMs?: number` - Timeout in milliseconds (default: 5000)
178
+
179
+ **Returns:** `Promise<T>` - Response data
180
+
181
+ **Example:**
182
+ ```typescript
183
+ // Get stored events
184
+ const response = await workerClient.request('GET_EVENTS', {
185
+ type: 'click',
186
+ limit: 10
187
+ });
188
+
189
+ console.log('Recent clicks:', response.events);
190
+ ```
191
+
192
+ #### `workerClient.setAuthToken(token)`
193
+
194
+ Set authentication token for the current session.
195
+
196
+ **Parameters:**
197
+ - `token: string` - Authentication token (e.g., JWT)
198
+
199
+ **Example:**
200
+ ```typescript
201
+ // Set token after user login
202
+ workerClient.setAuthToken('Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6...');
203
+
204
+ // Clear token on logout
205
+ workerClient.setAuthToken('');
206
+ ```
207
+
208
+ #### `workerClient.getConnectionStatus()`
209
+
210
+ Get current connection status to the MCP proxy server.
211
+
212
+ **Returns:** `Promise<boolean>` - Connection status
213
+
214
+ **Example:**
215
+ ```typescript
216
+ const isConnected = await workerClient.getConnectionStatus();
217
+ console.log('MCP connection:', isConnected ? 'Connected' : 'Disconnected');
218
+ ```
219
+
220
+ #### Connection Status Events
221
+
222
+ Subscribe to connection status changes:
223
+
224
+ ```typescript
225
+ // Listen for connection changes
226
+ const handleConnectionChange = (connected: boolean) => {
227
+ console.log('Connection status changed:', connected);
228
+ };
229
+
230
+ workerClient.onConnectionStatus(handleConnectionChange);
231
+
232
+ // Stop listening
233
+ workerClient.offConnectionStatus(handleConnectionChange);
234
+ ```
235
+
236
+ ## Worker Implementation Details
237
+
238
+ ### SharedWorker vs ServiceWorker
239
+
240
+ **SharedWorker (Preferred):**
241
+ - Single instance shared across all browser windows/tabs on the same origin
242
+ - Maintains persistent WebSocket connection even when tabs are closed
243
+ - Better for multi-tab applications
244
+ - Supported in Chrome, Firefox, and Safari
245
+
246
+ **ServiceWorker (Fallback):**
247
+ - Runs in background with browser-managed lifecycle
248
+ - Automatic fallback when SharedWorker is unavailable
249
+ - Handles offline scenarios and background sync
250
+ - Universal browser support
251
+
252
+ The `WorkerClient` automatically chooses the best available option.
253
+
254
+ ### Data Storage
255
+
256
+ Events are stored in IndexedDB with the following schema:
257
+
258
+ ```typescript
259
+ interface UserEvent {
260
+ id: string;
261
+ type: 'navigation' | 'click' | 'input' | 'custom';
262
+ timestamp: number;
263
+ path?: string;
264
+ from?: string; // navigation: previous route
265
+ to?: string; // navigation: current route
266
+ element?: string; // interaction: element tag
267
+ elementId?: string; // interaction: element ID
268
+ elementClass?: string; // interaction: element classes
269
+ elementText?: string; // interaction: element text content
270
+ metadata?: Record<string, unknown>;
271
+ }
272
+ ```
273
+
274
+ ### MCP Tools Exposed
275
+
276
+ The worker exposes these MCP tools to AI agents:
277
+
278
+ - `get_user_events` - Query stored user interaction events
279
+ - `get_connection_status` - Check WebSocket connection status
280
+ - `get_session_info` - Get current session information
281
+
282
+ ## Advanced Usage
283
+
284
+ ### Custom Event Storage
285
+
286
+ ```typescript
287
+ // Store custom business events
288
+ await workerClient.post('STORE_EVENT', {
289
+ event: {
290
+ type: 'custom',
291
+ timestamp: Date.now(),
292
+ metadata: {
293
+ eventName: 'purchase_completed',
294
+ orderId: '12345',
295
+ amount: 99.99,
296
+ currency: 'USD'
297
+ }
298
+ }
299
+ });
300
+ ```
301
+
302
+ ### Querying Specific Events
303
+
304
+ ```typescript
305
+ // Get navigation events from the last hour
306
+ const response = await workerClient.request('GET_EVENTS', {
307
+ type: 'navigation',
308
+ startTime: Date.now() - (60 * 60 * 1000),
309
+ limit: 50
310
+ });
311
+
312
+ // Get clicks on specific elements
313
+ const clicks = await workerClient.request('GET_EVENTS', {
314
+ type: 'click',
315
+ path: '/checkout',
316
+ limit: 20
317
+ });
318
+ ```
319
+
320
+ ### Error Handling
321
+
322
+ ```typescript
323
+ try {
324
+ await workerClient.init();
325
+ } catch (error) {
326
+ if (error.message.includes('SharedWorker')) {
327
+ console.log('SharedWorker not supported, falling back to ServiceWorker');
328
+ } else {
329
+ console.error('Worker initialization failed:', error);
330
+ }
331
+ }
332
+
333
+ // Handle request timeouts
334
+ try {
335
+ const data = await workerClient.request('GET_EVENTS', {}, 2000); // 2s timeout
336
+ } catch (error) {
337
+ if (error.message.includes('timeout')) {
338
+ console.log('Request timed out, worker may be busy');
339
+ }
340
+ }
341
+ ```
342
+
343
+ ## Integration with Higher-Level Libraries
344
+
345
+ This package is designed to be used with higher-level integration libraries:
346
+
347
+ - **[@mcp-fe/event-tracker](../event-tracker/README.md)**: Framework-agnostic event tracking
348
+ - **[@mcp-fe/react-event-tracker](../react-event-tracker/README.md)**: React-specific hooks and components
349
+
350
+ **Example with event-tracker:**
351
+ ```typescript
352
+ import { initEventTracker, trackEvent } from '@mcp-fe/event-tracker';
353
+
354
+ // Initialize (uses @mcp-fe/mcp-worker internally)
355
+ await initEventTracker({
356
+ backendWsUrl: 'ws://localhost:3001'
357
+ });
358
+
359
+ // Track events (stored via mcp-worker)
360
+ await trackEvent({
361
+ type: 'click',
362
+ element: 'button',
363
+ elementText: 'Save Changes'
364
+ });
365
+ ```
366
+
367
+ ## Setting Up MCP Proxy Server
368
+
369
+ The worker connects to an MCP proxy server that bridges browser workers with AI agents. You need a Node.js MCP proxy running to use this package effectively.
370
+
371
+ ### Using the Official Docker Image
372
+
373
+ The easiest way to run the MCP proxy server is using the official Docker image:
374
+
375
+ ```bash
376
+ # Pull and run the MCP proxy server
377
+ docker pull ghcr.io/mcp-fe/mcp-fe/mcp-server:main
378
+ docker run -p 3001:3001 ghcr.io/mcp-fe/mcp-fe/mcp-server:main
379
+ ```
380
+
381
+ The server will be available at `ws://localhost:3001` for your frontend applications.
382
+
383
+
384
+ **With Environment Variables:**
385
+ ```bash
386
+ docker run -p 3001:3001 \
387
+ -e NODE_ENV=production \
388
+ -e PORT=3001 \
389
+ ghcr.io/mcp-fe/mcp-fe/mcp-server:main
390
+ ```
391
+
392
+ ### Development Setup
393
+
394
+ For development, you can run the proxy server from source:
395
+
396
+ ```bash
397
+ # Clone the MCP-FE repository
398
+ git clone https://github.com/mcp-fe/mcp-fe.git
399
+ cd mcp-fe
400
+
401
+ # Install dependencies
402
+ pnpm install
403
+
404
+ # Start the MCP proxy server
405
+ nx serve mcp-server
406
+ ```
407
+
408
+ The proxy server handles:
409
+ - WebSocket connections from browser workers
410
+ - MCP protocol message routing
411
+ - Tool call forwarding between AI agents and frontend applications
412
+ - Connection management and error handling
413
+
414
+ See the [mcp-server documentation](../../apps/mcp-server/README.md) and main [MCP-FE documentation](../../README.md) for complete proxy server setup and configuration options.
415
+
416
+ ## Browser Compatibility
417
+
418
+ - **Chrome/Chromium**: Full support (SharedWorker + ServiceWorker)
419
+ - **Firefox**: Full support (SharedWorker + ServiceWorker)
420
+ - **Safari**: SharedWorker support, ServiceWorker fallback
421
+ - **Edge**: Full support (Chromium-based)
422
+
423
+ **Minimum Requirements:**
424
+ - ES2020+ support
425
+ - WebWorker support
426
+ - IndexedDB support
427
+ - WebSocket support (for MCP proxy connection)
428
+
429
+ ## Troubleshooting
430
+
431
+ ### Worker Files Not Found (404)
432
+
433
+ **Problem**: `Failed to load worker script` errors
434
+
435
+ **Solution**:
436
+ 1. Ensure worker files are copied to your public directory
437
+ 2. Verify the URLs match your server configuration
438
+ 3. Check browser Network tab for 404 errors
439
+
440
+ ```typescript
441
+ // Custom paths if needed
442
+ await workerClient.init({
443
+ sharedWorkerUrl: '/assets/workers/mcp-shared-worker.js',
444
+ serviceWorkerUrl: '/assets/workers/mcp-service-worker.js'
445
+ });
446
+ ```
447
+
448
+ ### Connection Issues
449
+
450
+ **Problem**: `getConnectionStatus()` returns `false`
451
+
452
+ **Solution**:
453
+ 1. Verify MCP proxy server is running on the specified URL
454
+ 2. Check WebSocket connection in browser Developer Tools
455
+ 3. Verify CORS settings if proxy is on different origin
456
+
457
+ ### SharedWorker Not Working
458
+
459
+ **Problem**: Falls back to ServiceWorker unexpectedly
460
+
461
+ **Solution**:
462
+ 1. SharedWorker requires HTTPS in production
463
+ 2. Some browsers disable SharedWorker in private/incognito mode
464
+ 3. Enterprise browser policies may block SharedWorker
465
+
466
+
467
+ ## Related Packages
468
+
469
+ - **[Main MCP-FE Project](../../README.md)**: Complete documentation and examples
470
+ - **[@mcp-fe/event-tracker](../event-tracker/README.md)**: Framework-agnostic event tracking API
471
+ - **[@mcp-fe/react-event-tracker](../react-event-tracker/README.md)**: React integration hooks
472
+
473
+ ## License
474
+
475
+ Licensed under the Apache License, Version 2.0. See the [LICENSE](../../LICENSE) file for details.
476
+
477
+ ---
57
478
 
58
- - `WorkerClient` prefers `SharedWorker` (shared across windows/iframes on the same origin). If `SharedWorker` is not available, it will automatically fall back to `ServiceWorker`.
59
- - If you need different worker URLs, pass `sharedWorkerUrl` and `serviceWorkerUrl` to `workerClient.init(...)`.
60
- - Worker scripts must be served from the same origin as your app.
61
- - Calling `workerClient.setAuthToken(...)` before initialization is allowed: the client will queue the token and send it when a worker becomes available.
62
- - The default worker URLs are `/mcp-shared-worker.js` and `/mcp-service-worker.js`.
479
+ **Note**: This package is the foundational layer of the MCP-FE ecosystem. For most applications, consider using the higher-level integration packages like `@mcp-fe/react-event-tracker` which provide a more convenient API.
package/package.json CHANGED
@@ -1,7 +1,13 @@
1
1
  {
2
2
  "name": "@mcp-fe/mcp-worker",
3
- "version": "0.0.15",
3
+ "version": "0.0.16",
4
4
  "license": "Apache-2.0",
5
+ "homepage": "https://mcp-fe.ai",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/mcp-fe/mcp-fe.git",
9
+ "directory": "libs/mcp-worker"
10
+ },
5
11
  "private": false,
6
12
  "type": "module",
7
13
  "main": "./index.js",