@mcp-fe/mcp-worker 0.0.14 → 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.
package/LICENSE ADDED
@@ -0,0 +1,203 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity granting the License.
13
+
14
+ "Legal Entity" shall mean the union of the acting entity and all
15
+ other entities that control, are controlled by, or are under common
16
+ control with that entity. For the purposes of this definition,
17
+ "control" means (i) the power, direct or indirect, to cause the
18
+ direction or management of such entity, whether by contract or
19
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity
23
+ exercising permissions granted by this License.
24
+
25
+ "Source" shall mean the preferred form for making modifications,
26
+ including but not limited to software source code, documentation
27
+ source, and configuration files.
28
+
29
+ "Object" shall mean any form resulting from mechanical
30
+ transformation or translation of a Source form, including but
31
+ not limited to compiled object code, generated documentation,
32
+ and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or
35
+ Object form, made available under the License, as indicated by a
36
+ copyright notice that is included in or attached to the work
37
+ (which shall not include communications that are solely about
38
+ and bear an appropriate legal notice).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based upon (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and derivative works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control
57
+ systems, and issue tracking systems that are managed by, or on behalf
58
+ of, the Licensor for the purpose of discussing and improving the Work,
59
+ but excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to use, reproduce, modify, merge, publish,
70
+ distribute, sublicense, and/or sell copies of the Work, and to
71
+ permit persons to whom the Work is furnished to do so, subject to
72
+ the following conditions:
73
+
74
+ The above copyright notice and this permission notice shall be
75
+ included in all copies or substantial portions of the Work.
76
+
77
+ 3. Grant of Patent License. Subject to the terms and conditions of
78
+ this License, each Contributor hereby grants to You a perpetual,
79
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
80
+ (except as stated in this section) patent license to make, have made,
81
+ use, offer to sell, sell, import, and otherwise transfer the Work,
82
+ where such license applies only to those patent claims licensable
83
+ by such Contributor that are necessarily infringed by their
84
+ Contribution(s) alone or by combination of their Contribution(s)
85
+ with the Work to which such Contribution(s) was submitted. If You
86
+ institute patent litigation against any entity (including a
87
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
88
+ or a Contribution incorporated within the Work constitutes direct
89
+ or contributory patent infringement, then any patent licenses
90
+ granted to You under this License for that Work shall terminate
91
+ as of the date such litigation is filed.
92
+
93
+ 4. Redistribution. You may reproduce and distribute copies of the
94
+ Work or Derivative Works thereof in any medium, with or without
95
+ modifications, and in Source or Object form, provided that You
96
+ meet the following conditions:
97
+
98
+ (a) You must give any other recipients of the Work or
99
+ Derivative Works a copy of this License; and
100
+
101
+ (b) You must cause any modified files to carry prominent notices
102
+ stating that You changed the files; and
103
+
104
+ (c) You must retain, in the Source form of any Derivative Works
105
+ that You distribute, all copyright, patent, trademark, and
106
+ attribution notices from the Source form of the Work,
107
+ excluding those notices that do not pertain to any part of
108
+ the Derivative Works; and
109
+
110
+ (d) If the Work includes a "NOTICE" text file as part of its
111
+ distribution, then any Derivative Works that You distribute must
112
+ include a readable copy of the attribution notices contained
113
+ within such NOTICE file, excluding those notices that do not
114
+ pertain to any part of the Derivative Works, in at least one
115
+ of the following places: within a NOTICE text file distributed
116
+ as part of the Derivative Works; within the Source form or
117
+ documentation, if provided along with the Derivative Works; or,
118
+ within a display generated by the Derivative Works, if and
119
+ wherever such third-party notices normally appear. The contents
120
+ of the NOTICE file are for informational purposes only and
121
+ do not modify the License. You may add Your own attribution
122
+ notices within Derivative Works that You distribute, alongside
123
+ or as an addendum to the NOTICE text from the Work, provided
124
+ that such additional attribution notices cannot be construed
125
+ as modifying the License.
126
+
127
+ You may add Your own copyright notice to Your modifications and
128
+ may provide additional or different license terms and conditions
129
+ for use, reproduction, or distribution of Your modifications, or
130
+ for any such Derivative Works as a whole, provided Your use,
131
+ reproduction, and distribution of the Work otherwise complies with
132
+ the conditions stated in this License.
133
+
134
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
135
+ any Contribution intentionally submitted for inclusion in the Work
136
+ by You to the Licensor shall be under the terms and conditions of
137
+ this License, without any additional terms or conditions.
138
+ Notwithstanding the above, nothing herein shall supersede or modify
139
+ the terms of any separate license agreement you may have executed
140
+ with Licensor regarding such Contributions.
141
+
142
+ 6. Trademarks. This License does not grant permission to use the trade
143
+ names, trademarks, service marks, or product names of the Licensor,
144
+ except as required for reasonable and customary use in describing the
145
+ origin of the Work and reproducing the content of the NOTICE file.
146
+
147
+ 7. Disclaimer of Warranty. Unless required by applicable law or
148
+ agreed to in writing, Licensor provides the Work (and each
149
+ Contributor provides its Contributions) on an "AS IS" BASIS,
150
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
151
+ implied, including, without limitation, any warranties or conditions
152
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
153
+ PARTICULAR PURPOSE. You are solely responsible for determining the
154
+ appropriateness of using or redistributing the Work and assume any
155
+ risks associated with Your exercise of permissions under this License.
156
+
157
+ 8. Limitation of Liability. In no event and under no legal theory,
158
+ whether in tort (including negligence), contract, or otherwise,
159
+ unless required by applicable law (such as deliberate and grossly
160
+ negligent acts) or agreed to in writing, shall any Contributor be
161
+ liable to You for damages, including any direct, indirect, special,
162
+ incidental, or consequential damages of any character arising as a
163
+ result of this License or out of the use or inability to use the
164
+ Work (including but not limited to damages for loss of goodwill,
165
+ work stoppage, computer failure or malfunction, or any and all
166
+ other commercial damages or losses), even if such Contributor
167
+ has been advised of the possibility of such damages.
168
+
169
+ 9. Accepting Warranty or Support. You may choose to offer, and to
170
+ charge a fee for, warranty, support, indemnity or other liability
171
+ obligations and/or rights consistent with this License. However, in
172
+ accepting such obligations, You may act only on Your own behalf and on
173
+ Your sole responsibility, not on behalf of any other Contributor, and
174
+ only if You agree to indemnify, defend, and hold each Contributor
175
+ harmless for any liability incurred by, or claims asserted against,
176
+ such Contributor by reason of your accepting any such warranty or support.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same page as the copyright notice for easier identification within
189
+ third-party archives.
190
+
191
+ Copyright 2026 [name of copyright owner]
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
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,6 +1,13 @@
1
1
  {
2
2
  "name": "@mcp-fe/mcp-worker",
3
- "version": "0.0.14",
3
+ "version": "0.0.16",
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
+ },
4
11
  "private": false,
5
12
  "type": "module",
6
13
  "main": "./index.js",
package/src/index.d.ts CHANGED
@@ -1,3 +1,18 @@
1
+ /**
2
+ * Copyright 2026 MCP-FE Contributors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
1
16
  import { WorkerClient } from './lib/worker-client';
2
17
  export { type WorkerClientInitOptions } from './lib/worker-client';
3
18
  export { queryEvents, type UserEvent } from './lib/database';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../libs/mcp-worker/src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAC,MAAO,qBAAqB,CAAC;AAElD,OAAO,EAAE,KAAK,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,KAAK,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAG7D,eAAO,MAAM,YAAY,cAAqB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../libs/mcp-worker/src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEnD,OAAO,EAAE,KAAK,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,KAAK,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAG7D,eAAO,MAAM,YAAY,cAAqB,CAAC"}