@mcp-b/transports 0.0.0-beta-20260109203913

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.
@@ -0,0 +1,937 @@
1
+ import { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js";
2
+ import { Transport, TransportSendOptions } from "@modelcontextprotocol/sdk/shared/transport.js";
3
+
4
+ //#region src/browser-types.d.ts
5
+ /**
6
+ * Unique identifier for an event in the event store
7
+ */
8
+ type EventId = string;
9
+ /**
10
+ * Unique identifier for a stream of events
11
+ */
12
+ type StreamId = string;
13
+ /**
14
+ * Options for connecting to an MCP server
15
+ */
16
+ interface MCPConnectOptions {
17
+ /**
18
+ * The event ID to resume from if reconnecting
19
+ */
20
+ resumeFrom?: EventId;
21
+ }
22
+ /**
23
+ * Information about the MCP server
24
+ */
25
+ interface MCPServerInfo {
26
+ /**
27
+ * Unique identifier for this server instance
28
+ */
29
+ instanceId: string;
30
+ /**
31
+ * Whether the server maintains session state
32
+ */
33
+ stateful: boolean;
34
+ /**
35
+ * Whether the server has event storage enabled
36
+ */
37
+ hasEventStore: boolean;
38
+ }
39
+ /**
40
+ * Event storage interface for accessing stored events
41
+ */
42
+ interface MCPEventStore {
43
+ /**
44
+ * Get stored events, optionally filtered by client and/or after a specific event
45
+ * @param clientId - Optional client ID to filter events
46
+ * @param afterEventId - Optional event ID to get events after
47
+ * @param limit - Maximum number of events to return (default: 100)
48
+ */
49
+ getEvents(clientId?: string, afterEventId?: EventId, limit?: number): StoredEvent[];
50
+ /**
51
+ * Get the ID of the last event, optionally for a specific client
52
+ * @param clientId - Optional client ID to filter by
53
+ */
54
+ getLastEventId(clientId?: string): EventId | null;
55
+ /**
56
+ * Clear stored events, optionally for a specific client
57
+ * @param clientId - Optional client ID to clear events for
58
+ */
59
+ clearEvents(clientId?: string): void;
60
+ }
61
+ /**
62
+ * The MCP interface exposed on window for browser environments
63
+ */
64
+ interface MCPBrowserInterface {
65
+ /**
66
+ * Connect a client to the MCP server
67
+ * @param clientId - Unique identifier for the client
68
+ * @param options - Optional connection options
69
+ * @returns MessagePort for communication or null if connection fails
70
+ */
71
+ connect(clientId: string, options?: MCPConnectOptions): MessagePort | null;
72
+ /**
73
+ * Disconnect a client from the MCP server
74
+ * @param clientId - The client ID to disconnect
75
+ */
76
+ disconnect(clientId: string): void;
77
+ /**
78
+ * Terminate a client's session and clean up all associated resources
79
+ * @param clientId - The client ID to terminate
80
+ */
81
+ terminateSession?(clientId: string): void;
82
+ /**
83
+ * Check if the MCP server is available and running
84
+ */
85
+ isServerAvailable(): boolean;
86
+ /**
87
+ * Get information about the MCP server
88
+ */
89
+ getServerInfo(): MCPServerInfo;
90
+ /**
91
+ * Event storage access (only available in stateful mode with event store)
92
+ */
93
+ events?: MCPEventStore;
94
+ }
95
+ /**
96
+ * Extended Window interface with MCP support
97
+ */
98
+ interface MCPWindow extends Window {
99
+ mcp?: MCPBrowserInterface;
100
+ }
101
+ /**
102
+ * Message types for internal MCP communication
103
+ */
104
+ interface MCPServerInfoMessage {
105
+ type: 'mcp-server-info';
106
+ serverInstanceId: string;
107
+ serverSessionId?: string;
108
+ hasEventStore: boolean;
109
+ streamId: StreamId;
110
+ }
111
+ interface MCPEventMessage {
112
+ type: 'mcp-event';
113
+ eventId: EventId;
114
+ message: JSONRPCMessage;
115
+ }
116
+ interface MCPReplayEventMessage {
117
+ type: 'mcp-replay-event';
118
+ eventId: EventId;
119
+ message: JSONRPCMessage;
120
+ }
121
+ /**
122
+ * Stored event with metadata for event sourcing
123
+ */
124
+ interface StoredEvent {
125
+ eventId: EventId;
126
+ streamId: StreamId;
127
+ message: JSONRPCMessage;
128
+ timestamp: number;
129
+ clientId: string;
130
+ }
131
+ declare enum NativeMessageType {
132
+ START = "start",
133
+ STARTED = "started",
134
+ STOP = "stop",
135
+ STOPPED = "stopped",
136
+ PING = "ping",
137
+ PONG = "pong",
138
+ ERROR = "error",
139
+ LIST_TOOLS = "list_tools",
140
+ CALL_TOOL = "call_tool",
141
+ TOOL_LIST_UPDATED = "tool_list_updated",
142
+ TOOL_LIST_UPDATED_ACK = "tool_list_updated_ack",
143
+ PROCESS_DATA = "process_data",
144
+ SERVER_STARTED = "server_started",
145
+ SERVER_STOPPED = "server_stopped",
146
+ ERROR_FROM_NATIVE_HOST = "error_from_native_host",
147
+ CONNECT_NATIVE = "connectNative",
148
+ PING_NATIVE = "ping_native",
149
+ DISCONNECT_NATIVE = "disconnect_native",
150
+ }
151
+ /**
152
+ * Chrome Extension Constants
153
+ * Centralized configuration values and magic constants
154
+ */
155
+ declare const NATIVE_HOST: {
156
+ readonly NAME: "com.chromemcp.nativehost";
157
+ readonly DEFAULT_PORT: 12306;
158
+ };
159
+ declare const ERROR_MESSAGES: {
160
+ readonly NATIVE_CONNECTION_FAILED: "Failed to connect to native host";
161
+ readonly NATIVE_DISCONNECTED: "Native connection disconnected";
162
+ readonly SERVER_STATUS_LOAD_FAILED: "Failed to load server status";
163
+ readonly TOOL_EXECUTION_FAILED: "Tool execution failed";
164
+ readonly SERVER_STATUS_SAVE_FAILED: "Failed to save server status";
165
+ };
166
+ declare const SUCCESS_MESSAGES: {
167
+ readonly TOOL_EXECUTED: "Tool executed successfully";
168
+ readonly CONNECTION_ESTABLISHED: "Connection established";
169
+ readonly SERVER_STARTED: "Server started successfully";
170
+ readonly SERVER_STOPPED: "Server stopped successfully";
171
+ };
172
+ declare const STORAGE_KEYS: {
173
+ readonly SERVER_STATUS: "serverStatus";
174
+ };
175
+ declare const BACKGROUND_MESSAGE_TYPES: {
176
+ readonly GET_SERVER_STATUS: "get_server_status";
177
+ readonly REFRESH_SERVER_STATUS: "refresh_server_status";
178
+ readonly SERVER_STATUS_CHANGED: "server_status_changed";
179
+ };
180
+ declare const HOST_NAME: "com.chromemcp.nativehost";
181
+ /**
182
+ * Server status management interface
183
+ */
184
+ interface ServerStatus {
185
+ isRunning: boolean;
186
+ port?: number;
187
+ lastUpdated: number;
188
+ }
189
+ //#endregion
190
+ //#region src/ExtensionClientTransport.d.ts
191
+ /**
192
+ * Configuration options for ExtensionClientTransport
193
+ */
194
+ interface ExtensionClientTransportOptions {
195
+ /**
196
+ * The extension ID to connect to (optional for same-extension connections)
197
+ */
198
+ extensionId?: string;
199
+ /**
200
+ * Port name for the connection
201
+ * Default: 'mcp'
202
+ */
203
+ portName?: string;
204
+ /**
205
+ * Enable automatic reconnection on disconnect
206
+ * Default: true
207
+ */
208
+ autoReconnect?: boolean;
209
+ /**
210
+ * Maximum number of reconnection attempts
211
+ * Default: 10
212
+ */
213
+ maxReconnectAttempts?: number;
214
+ /**
215
+ * Initial reconnection delay in milliseconds
216
+ * Default: 1000
217
+ */
218
+ reconnectDelay?: number;
219
+ /**
220
+ * Maximum reconnection delay in milliseconds
221
+ * Default: 30000
222
+ */
223
+ maxReconnectDelay?: number;
224
+ /**
225
+ * Reconnection backoff multiplier
226
+ * Default: 1.5
227
+ */
228
+ reconnectBackoffMultiplier?: number;
229
+ }
230
+ /**
231
+ * Client transport for Chrome extensions using Port-based messaging.
232
+ * This transport can be used in content scripts, popup scripts, or sidepanel scripts
233
+ * to connect to a server running in the background service worker.
234
+ *
235
+ * Features automatic reconnection to handle background service worker lifecycle.
236
+ */
237
+ declare class ExtensionClientTransport implements Transport {
238
+ private _port;
239
+ private _extensionId;
240
+ private _portName;
241
+ private _messageHandler;
242
+ private _disconnectHandler;
243
+ private _isReconnecting;
244
+ private _reconnectAttempts;
245
+ private _reconnectTimer;
246
+ private _currentReconnectDelay;
247
+ private _isStarted;
248
+ private _isClosed;
249
+ private _autoReconnect;
250
+ private _maxReconnectAttempts;
251
+ private _reconnectDelay;
252
+ private _maxReconnectDelay;
253
+ private _reconnectBackoffMultiplier;
254
+ onclose?: () => void;
255
+ onerror?: (error: Error) => void;
256
+ onmessage?: (message: JSONRPCMessage) => void;
257
+ constructor(options?: ExtensionClientTransportOptions);
258
+ /**
259
+ * Starts the transport by connecting to the extension port
260
+ */
261
+ start(): Promise<void>;
262
+ /**
263
+ * Connects to the extension port
264
+ */
265
+ private _connect;
266
+ /**
267
+ * Sends a message to the server
268
+ */
269
+ send(message: JSONRPCMessage, _options?: TransportSendOptions): Promise<void>;
270
+ /**
271
+ * Closes the transport
272
+ */
273
+ close(): Promise<void>;
274
+ /**
275
+ * Cleans up event listeners and references
276
+ */
277
+ private _cleanup;
278
+ /**
279
+ * Schedules a reconnection attempt
280
+ */
281
+ private _scheduleReconnect;
282
+ /**
283
+ * Attempts to reconnect to the extension
284
+ */
285
+ private _attemptReconnect;
286
+ }
287
+ //#endregion
288
+ //#region src/ExtensionServerTransport.d.ts
289
+ /**
290
+ * Configuration options for ExtensionServerTransport
291
+ */
292
+ type ExtensionServerTransportOptions = {
293
+ /**
294
+ * Enable keep-alive mechanism to prevent service worker shutdown
295
+ * Default: true
296
+ */
297
+ keepAlive?: boolean;
298
+ /**
299
+ * Keep-alive interval in milliseconds
300
+ * Default: 25000 (25 seconds, less than Chrome's 30-second timeout)
301
+ */
302
+ keepAliveInterval?: number;
303
+ };
304
+ /**
305
+ * Server transport for Chrome extensions using Port-based messaging.
306
+ * This transport handles a single client connection through Chrome's port messaging API.
307
+ * It should be used in the extension's background service worker.
308
+ *
309
+ * Features:
310
+ * - Keep-alive mechanism to prevent service worker shutdown
311
+ * - Graceful connection state management
312
+ */
313
+ declare class ExtensionServerTransport implements Transport {
314
+ private _port;
315
+ private _started;
316
+ private _messageHandler;
317
+ private _disconnectHandler;
318
+ private _keepAliveTimer;
319
+ private _options;
320
+ private _connectionInfo;
321
+ onclose?: () => void;
322
+ onerror?: (error: Error) => void;
323
+ onmessage?: (message: JSONRPCMessage) => void;
324
+ constructor(port: chrome.runtime.Port, options?: ExtensionServerTransportOptions);
325
+ /**
326
+ * Starts the transport and begins handling messages
327
+ */
328
+ start(): Promise<void>;
329
+ /**
330
+ * Sends a message to the client
331
+ */
332
+ send(message: JSONRPCMessage, _options?: TransportSendOptions): Promise<void>;
333
+ /**
334
+ * Closes the transport
335
+ */
336
+ close(): Promise<void>;
337
+ /**
338
+ * Cleans up event listeners and references
339
+ */
340
+ private _cleanup;
341
+ /**
342
+ * Starts the keep-alive mechanism
343
+ */
344
+ private _startKeepAlive;
345
+ /**
346
+ * Stops the keep-alive mechanism
347
+ */
348
+ private _stopKeepAlive;
349
+ /**
350
+ * Gets connection information
351
+ */
352
+ getConnectionInfo(): {
353
+ uptime: number;
354
+ isConnected: boolean;
355
+ connectedAt: number;
356
+ lastMessageAt: number;
357
+ messageCount: number;
358
+ };
359
+ }
360
+ //#endregion
361
+ //#region src/IframeChildTransport.d.ts
362
+ interface IframeChildTransportOptions {
363
+ /** Whitelist of parent origins allowed to connect (for security) */
364
+ allowedOrigins: string[];
365
+ /** Optional channel name (default: 'mcp-iframe') */
366
+ channelId?: string;
367
+ /** Retry interval for broadcasting ready signal in milliseconds (default: 250) */
368
+ serverReadyRetryMs?: number;
369
+ }
370
+ /**
371
+ * IframeChildTransport - Server transport for iframe
372
+ *
373
+ * Use this transport when an iframe wants to expose an MCP server to its parent page.
374
+ * Supports cross-origin communication.
375
+ *
376
+ * @example
377
+ * ```typescript
378
+ * const transport = new IframeChildTransport({
379
+ * allowedOrigins: ['https://parent-app.com'],
380
+ * });
381
+ *
382
+ * const server = new Server({ name: 'IframeApp', version: '1.0.0' });
383
+ * await server.connect(transport);
384
+ * ```
385
+ */
386
+ declare class IframeChildTransport implements Transport {
387
+ private _started;
388
+ private _allowedOrigins;
389
+ private _channelId;
390
+ private _messageHandler?;
391
+ private _clientOrigin?;
392
+ private _serverReadyTimeout;
393
+ private readonly _serverReadyRetryMs;
394
+ onclose?: () => void;
395
+ onerror?: (error: Error) => void;
396
+ onmessage?: (message: JSONRPCMessage) => void;
397
+ constructor(options: IframeChildTransportOptions);
398
+ start(): Promise<void>;
399
+ private broadcastServerReady;
400
+ private scheduleServerReadyRetry;
401
+ private clearServerReadyRetry;
402
+ send(message: JSONRPCMessage): Promise<void>;
403
+ close(): Promise<void>;
404
+ }
405
+ //#endregion
406
+ //#region src/IframeParentTransport.d.ts
407
+ interface IframeParentTransportOptions {
408
+ /** Reference to the iframe element */
409
+ iframe: HTMLIFrameElement;
410
+ /** Expected origin of the iframe (for security) */
411
+ targetOrigin: string;
412
+ /** Optional channel name (default: 'mcp-iframe') */
413
+ channelId?: string;
414
+ /** Retry interval for ready handshake in milliseconds (default: 250) */
415
+ checkReadyRetryMs?: number;
416
+ }
417
+ /**
418
+ * IframeParentTransport - Client transport for parent page
419
+ *
420
+ * Use this transport when the parent page wants to connect to an MCP server
421
+ * running inside an iframe. Supports cross-origin communication.
422
+ *
423
+ * @example
424
+ * ```typescript
425
+ * const iframe = document.querySelector('iframe');
426
+ * const transport = new IframeParentTransport({
427
+ * iframe,
428
+ * targetOrigin: 'https://iframe-app.com',
429
+ * });
430
+ *
431
+ * const client = new Client({ name: 'Parent', version: '1.0.0' });
432
+ * await client.connect(transport);
433
+ * ```
434
+ */
435
+ declare class IframeParentTransport implements Transport {
436
+ private _started;
437
+ private _iframe;
438
+ private _targetOrigin;
439
+ private _channelId;
440
+ private _messageHandler?;
441
+ private _checkReadyTimeout;
442
+ private readonly _checkReadyRetryMs;
443
+ readonly serverReadyPromise: Promise<void>;
444
+ private _serverReadyResolve;
445
+ private _serverReadyReject;
446
+ onclose?: () => void;
447
+ onerror?: (error: Error) => void;
448
+ onmessage?: (message: JSONRPCMessage) => void;
449
+ constructor(options: IframeParentTransportOptions);
450
+ start(): Promise<void>;
451
+ private sendCheckReady;
452
+ private scheduleCheckReadyRetry;
453
+ private clearCheckReadyRetry;
454
+ send(message: JSONRPCMessage): Promise<void>;
455
+ close(): Promise<void>;
456
+ }
457
+ //#endregion
458
+ //#region src/TabClientTransport.d.ts
459
+ /**
460
+ * Configuration options for TabClientTransport.
461
+ *
462
+ * @see {@link TabClientTransport}
463
+ */
464
+ interface TabClientTransportOptions {
465
+ /**
466
+ * Expected origin of the server window for security validation.
467
+ *
468
+ * **Security**: This origin is checked against `event.origin` for all incoming
469
+ * messages to prevent cross-origin attacks. Only messages from this origin will
470
+ * be processed.
471
+ *
472
+ * @example 'https://example.com'
473
+ * @example 'http://localhost:3000'
474
+ */
475
+ targetOrigin: string;
476
+ /**
477
+ * Channel identifier for message routing.
478
+ *
479
+ * Multiple transports can coexist on the same page by using different channel IDs.
480
+ * This allows for isolated communication channels between different MCP clients
481
+ * and servers.
482
+ *
483
+ * @default 'mcp-default'
484
+ */
485
+ channelId?: string;
486
+ /**
487
+ * Request timeout in milliseconds.
488
+ *
489
+ * If a request doesn't receive a response within this time, a timeout error
490
+ * is synthesized and delivered to the client. This prevents infinite hangs
491
+ * when the server becomes unresponsive due to:
492
+ * - Page navigation
493
+ * - JavaScript errors
494
+ * - Network issues
495
+ * - Server crashes
496
+ *
497
+ * **Design rationale**: 10 seconds is appropriate for most tool operations.
498
+ * For operations that may take longer (e.g., complex computations, slow network
499
+ * requests), increase this value via the configuration option.
500
+ *
501
+ * @default 10000 (10 seconds)
502
+ * @see {@link _handleRequestTimeout} for timeout implementation
503
+ */
504
+ requestTimeout?: number;
505
+ }
506
+ /**
507
+ * Client-side transport for same-window MCP communication via postMessage.
508
+ *
509
+ * This transport connects an MCP client to a TabServerTransport running in the same
510
+ * window. Communication occurs via the browser's `window.postMessage()` API, which
511
+ * provides:
512
+ * - Same-window message passing (no network overhead)
513
+ * - Origin validation for security
514
+ * - Asynchronous message delivery
515
+ *
516
+ * **Architecture**:
517
+ * ```
518
+ * ┌─────────────────┐ ┌──────────────────┐
519
+ * │ MCP Client │ postMessage() │ MCP Server │
520
+ * │ (This side) │ ←─────────────────→│ (TabServerTransport)
521
+ * └─────────────────┘ └──────────────────┘
522
+ * ```
523
+ *
524
+ * **Key features**:
525
+ * - Request timeout to prevent infinite hangs (default 10s)
526
+ * - Server ready detection via handshake
527
+ * - Origin validation for security
528
+ * - Channel-based message routing
529
+ *
530
+ * **Use cases**:
531
+ * - MCP client running in content script connecting to page context
532
+ * - MCP client in extension popup connecting to background page
533
+ * - Testing and development scenarios
534
+ *
535
+ * @example Basic usage
536
+ * ```typescript
537
+ * const transport = new TabClientTransport({
538
+ * targetOrigin: 'https://example.com',
539
+ * channelId: 'my-mcp-channel',
540
+ * requestTimeout: 10000, // Optional (default)
541
+ * });
542
+ *
543
+ * // Wait for server to be ready
544
+ * await transport.start();
545
+ * await transport.serverReadyPromise;
546
+ *
547
+ * // Now safe to send messages
548
+ * await transport.send({
549
+ * jsonrpc: '2.0',
550
+ * id: 1,
551
+ * method: 'tools/call',
552
+ * params: { name: 'my_tool', arguments: {} }
553
+ * });
554
+ * ```
555
+ *
556
+ * @example With custom timeout
557
+ * ```typescript
558
+ * const transport = new TabClientTransport({
559
+ * targetOrigin: '*',
560
+ * requestTimeout: 60000, // 60 seconds for slow operations
561
+ * });
562
+ * ```
563
+ *
564
+ * @see {@link TabServerTransport} for the server-side implementation
565
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage} for postMessage API
566
+ */
567
+ declare class TabClientTransport implements Transport {
568
+ /** Transport state flag */
569
+ private _started;
570
+ /** Expected origin for message validation */
571
+ private readonly _targetOrigin;
572
+ /** Channel ID for message routing */
573
+ private readonly _channelId;
574
+ /** Request timeout in milliseconds */
575
+ private readonly _requestTimeout;
576
+ /** Message event listener */
577
+ private _messageHandler?;
578
+ /**
579
+ * Promise that resolves when the server is ready to receive messages.
580
+ *
581
+ * **Usage**: Always `await` this promise after calling `start()` and before
582
+ * sending messages. Sending messages before the server is ready may result
583
+ * in lost messages.
584
+ *
585
+ * @example
586
+ * ```typescript
587
+ * await transport.start();
588
+ * await transport.serverReadyPromise;
589
+ * // Now safe to send messages
590
+ * ```
591
+ */
592
+ readonly serverReadyPromise: Promise<void>;
593
+ /** Internal resolver for serverReadyPromise */
594
+ private readonly _serverReadyResolve;
595
+ /** Internal rejector for serverReadyPromise */
596
+ private readonly _serverReadyReject;
597
+ /**
598
+ * Active request tracking for timeout management.
599
+ *
600
+ * **Key**: Request ID (from JSON-RPC message)
601
+ * **Value**: Timeout ID and original request
602
+ *
603
+ * When a response is received, the entry is removed and timeout cleared.
604
+ * If timeout expires first, an error response is synthesized.
605
+ */
606
+ private readonly _activeRequests;
607
+ /** Callback invoked when transport closes */
608
+ onclose?: () => void;
609
+ /** Callback invoked on errors */
610
+ onerror?: (error: Error) => void;
611
+ /** Callback invoked when message received */
612
+ onmessage?: (message: JSONRPCMessage) => void;
613
+ /**
614
+ * Creates a new TabClientTransport instance.
615
+ *
616
+ * **Note**: The transport is not started automatically. Call `start()` to begin
617
+ * listening for messages.
618
+ *
619
+ * @param options - Configuration options
620
+ * @throws {Error} If targetOrigin is not specified
621
+ */
622
+ constructor(options: TabClientTransportOptions);
623
+ /**
624
+ * Starts the transport by registering message listeners.
625
+ *
626
+ * **Lifecycle**:
627
+ * 1. Register `window.addEventListener('message', ...)` handler
628
+ * 2. Send server ready check (in case server started first)
629
+ * 3. Wait for server ready signal via `serverReadyPromise`
630
+ *
631
+ * **Note**: Always `await transport.serverReadyPromise` after calling this method
632
+ * and before sending messages.
633
+ *
634
+ * @throws {Error} If transport is already started
635
+ */
636
+ start(): Promise<void>;
637
+ /**
638
+ * Sends a JSON-RPC message to the server.
639
+ *
640
+ * **Request timeout**: If this is a request (has `method` and `id`), a timeout
641
+ * is started. If the server doesn't respond within `requestTimeout` milliseconds,
642
+ * an error response is synthesized.
643
+ *
644
+ * **Await server ready**: This method automatically awaits `serverReadyPromise`
645
+ * before sending, ensuring messages aren't lost.
646
+ *
647
+ * @param message - JSON-RPC message to send
648
+ * @throws {Error} If transport is not started
649
+ */
650
+ send(message: JSONRPCMessage): Promise<void>;
651
+ /**
652
+ * Closes the transport and cleans up resources.
653
+ *
654
+ * **Cleanup performed**:
655
+ * - Removes message event listener
656
+ * - Clears all active request timeouts
657
+ * - Rejects server ready promise if still pending
658
+ * - Invokes `onclose` callback
659
+ *
660
+ * **Note**: After calling this method, the transport cannot be reused.
661
+ * Create a new instance if needed.
662
+ */
663
+ close(): Promise<void>;
664
+ /**
665
+ * Sends a server ready check message.
666
+ *
667
+ * This prompts the server to respond with 'mcp-server-ready' signal,
668
+ * resolving the `serverReadyPromise`. Useful when the server may have
669
+ * started before the client.
670
+ *
671
+ * @private
672
+ */
673
+ private _sendCheckReady;
674
+ /**
675
+ * Starts timeout tracking for a request.
676
+ *
677
+ * **Behavior**: After `requestTimeout` milliseconds, if no response is received,
678
+ * `_handleRequestTimeout` is called to synthesize an error response.
679
+ *
680
+ * **Note**: Only requests (messages with `method` and `id`) are tracked.
681
+ * Notifications (no `id`) and responses are not tracked.
682
+ *
683
+ * @param message - JSON-RPC request message
684
+ * @private
685
+ */
686
+ private _startRequestTimeout;
687
+ /**
688
+ * Clears timeout tracking for a response.
689
+ *
690
+ * Called when a response (with `result` or `error`) is received.
691
+ * Clears the timeout and removes the tracking entry.
692
+ *
693
+ * @param message - JSON-RPC response message
694
+ * @private
695
+ */
696
+ private _clearRequestTimeout;
697
+ /**
698
+ * Handles request timeout by synthesizing an error response.
699
+ *
700
+ * **Error response format** (JSON-RPC 2.0):
701
+ * ```json
702
+ * {
703
+ * "jsonrpc": "2.0",
704
+ * "id": "<request-id>",
705
+ * "error": {
706
+ * "code": -32000,
707
+ * "message": "Request timeout - server may have navigated or become unresponsive",
708
+ * "data": {
709
+ * "timeoutMs": 10000,
710
+ * "originalMethod": "tools/call"
711
+ * }
712
+ * }
713
+ * }
714
+ * ```
715
+ *
716
+ * **Error code**: `-32000` (Server error) per JSON-RPC 2.0 specification.
717
+ *
718
+ * @param requestId - ID of the timed-out request
719
+ * @private
720
+ */
721
+ private _handleRequestTimeout;
722
+ }
723
+ //#endregion
724
+ //#region src/TabServerTransport.d.ts
725
+ interface TabServerTransportOptions {
726
+ /** Whitelist of origins allowed to connect (for security) */
727
+ allowedOrigins: string[];
728
+ /** Optional channel name (default: 'mcp-default') */
729
+ channelId?: string;
730
+ }
731
+ declare class TabServerTransport implements Transport {
732
+ private _started;
733
+ private _allowedOrigins;
734
+ private _channelId;
735
+ private _messageHandler?;
736
+ private _clientOrigin?;
737
+ private _beforeUnloadHandler?;
738
+ private _cleanupInterval?;
739
+ private _pendingRequests;
740
+ private readonly REQUEST_TIMEOUT_MS;
741
+ onclose?: () => void;
742
+ onerror?: (error: Error) => void;
743
+ onmessage?: (message: JSONRPCMessage) => void;
744
+ constructor(options: TabServerTransportOptions);
745
+ start(): Promise<void>;
746
+ send(message: JSONRPCMessage): Promise<void>;
747
+ /**
748
+ * Handle page navigation by sending interrupted responses for all pending requests.
749
+ * Called during beforeunload event.
750
+ * @private
751
+ */
752
+ private _handleBeforeUnload;
753
+ /**
754
+ * Clean up stale requests that have been pending for too long.
755
+ * Called periodically to prevent memory leaks.
756
+ * @private
757
+ */
758
+ private _cleanupStaleRequests;
759
+ close(): Promise<void>;
760
+ }
761
+ //#endregion
762
+ //#region src/UserScriptClientTransport.d.ts
763
+ /**
764
+ * Configuration options for UserScriptClientTransport
765
+ */
766
+ interface UserScriptClientTransportOptions {
767
+ /**
768
+ * The extension ID to connect to (optional for same-extension connections)
769
+ */
770
+ extensionId?: string;
771
+ /**
772
+ * Port name for the connection
773
+ * Default: 'mcp'
774
+ */
775
+ portName?: string;
776
+ /**
777
+ * Enable automatic reconnection on disconnect
778
+ * Default: true
779
+ */
780
+ autoReconnect?: boolean;
781
+ /**
782
+ * Maximum number of reconnection attempts
783
+ * Default: 10
784
+ */
785
+ maxReconnectAttempts?: number;
786
+ /**
787
+ * Initial reconnection delay in milliseconds
788
+ * Default: 1000
789
+ */
790
+ reconnectDelay?: number;
791
+ /**
792
+ * Maximum reconnection delay in milliseconds
793
+ * Default: 30000
794
+ */
795
+ maxReconnectDelay?: number;
796
+ /**
797
+ * Reconnection backoff multiplier
798
+ * Default: 1.5
799
+ */
800
+ reconnectBackoffMultiplier?: number;
801
+ }
802
+ /**
803
+ * Client transport for Chrome MV3 User Scripts using Port-based messaging.
804
+ * This transport can be used inside a User Script context to connect to the
805
+ * extension's background service worker. On the extension side, connections
806
+ * are received via chrome.runtime.onUserScriptConnect.
807
+ *
808
+ * Features automatic reconnection to handle background service worker lifecycle.
809
+ */
810
+ declare class UserScriptClientTransport implements Transport {
811
+ private _port;
812
+ private _extensionId;
813
+ private _portName;
814
+ private _messageHandler;
815
+ private _disconnectHandler;
816
+ private _isReconnecting;
817
+ private _reconnectAttempts;
818
+ private _reconnectTimer;
819
+ private _currentReconnectDelay;
820
+ private _isStarted;
821
+ private _isClosed;
822
+ private _autoReconnect;
823
+ private _maxReconnectAttempts;
824
+ private _reconnectDelay;
825
+ private _maxReconnectDelay;
826
+ private _reconnectBackoffMultiplier;
827
+ onclose?: () => void;
828
+ onerror?: (error: Error) => void;
829
+ onmessage?: (message: JSONRPCMessage) => void;
830
+ constructor(options?: UserScriptClientTransportOptions);
831
+ /**
832
+ * Starts the transport by connecting to the extension port
833
+ */
834
+ start(): Promise<void>;
835
+ /**
836
+ * Connects to the extension port
837
+ */
838
+ private _connect;
839
+ /**
840
+ * Sends a message to the server
841
+ */
842
+ send(message: JSONRPCMessage, _options?: TransportSendOptions): Promise<void>;
843
+ /**
844
+ * Closes the transport
845
+ */
846
+ close(): Promise<void>;
847
+ /**
848
+ * Cleans up event listeners and references
849
+ */
850
+ private _cleanup;
851
+ /**
852
+ * Schedules a reconnection attempt
853
+ */
854
+ private _scheduleReconnect;
855
+ /**
856
+ * Attempts to reconnect to the extension
857
+ */
858
+ private _attemptReconnect;
859
+ }
860
+ //#endregion
861
+ //#region src/UserScriptServerTransport.d.ts
862
+ /**
863
+ * Configuration options for UserScriptServerTransport
864
+ */
865
+ type UserScriptServerTransportOptions = {
866
+ /**
867
+ * Enable keep-alive mechanism to prevent service worker shutdown
868
+ * Default: true
869
+ */
870
+ keepAlive?: boolean;
871
+ /**
872
+ * Keep-alive interval in milliseconds
873
+ * Default: 25000 (25 seconds, less than Chrome's 30-second timeout)
874
+ */
875
+ keepAliveInterval?: number;
876
+ };
877
+ /**
878
+ * Server transport for Chrome MV3 User Scripts using Port-based messaging.
879
+ * This transport handles a single client connection through Chrome's port
880
+ * messaging API. It should be used in the extension's background service
881
+ * worker. Connections are initiated from User Scripts via chrome.runtime.connect
882
+ * and received here via chrome.runtime.onUserScriptConnect.
883
+ *
884
+ * Features:
885
+ * - Keep-alive mechanism to prevent service worker shutdown
886
+ * - Graceful connection state management
887
+ */
888
+ declare class UserScriptServerTransport implements Transport {
889
+ private _port;
890
+ private _started;
891
+ private _messageHandler;
892
+ private _disconnectHandler;
893
+ private _keepAliveTimer;
894
+ private _options;
895
+ private _connectionInfo;
896
+ onclose?: () => void;
897
+ onerror?: (error: Error) => void;
898
+ onmessage?: (message: JSONRPCMessage) => void;
899
+ constructor(port: chrome.runtime.Port, options?: UserScriptServerTransportOptions);
900
+ /**
901
+ * Starts the transport and begins handling messages
902
+ */
903
+ start(): Promise<void>;
904
+ /**
905
+ * Sends a message to the client
906
+ */
907
+ send(message: JSONRPCMessage, _options?: TransportSendOptions): Promise<void>;
908
+ /**
909
+ * Closes the transport
910
+ */
911
+ close(): Promise<void>;
912
+ /**
913
+ * Cleans up event listeners and references
914
+ */
915
+ private _cleanup;
916
+ /**
917
+ * Starts the keep-alive mechanism
918
+ */
919
+ private _startKeepAlive;
920
+ /**
921
+ * Stops the keep-alive mechanism
922
+ */
923
+ private _stopKeepAlive;
924
+ /**
925
+ * Gets connection information
926
+ */
927
+ getConnectionInfo(): {
928
+ uptime: number;
929
+ isConnected: boolean;
930
+ connectedAt: number;
931
+ lastMessageAt: number;
932
+ messageCount: number;
933
+ };
934
+ }
935
+ //#endregion
936
+ export { BACKGROUND_MESSAGE_TYPES, ERROR_MESSAGES, EventId, ExtensionClientTransport, ExtensionClientTransportOptions, ExtensionServerTransport, ExtensionServerTransportOptions, HOST_NAME, IframeChildTransport, IframeChildTransportOptions, IframeParentTransport, IframeParentTransportOptions, MCPBrowserInterface, MCPConnectOptions, MCPEventMessage, MCPEventStore, MCPReplayEventMessage, MCPServerInfo, MCPServerInfoMessage, MCPWindow, NATIVE_HOST, NativeMessageType, STORAGE_KEYS, SUCCESS_MESSAGES, ServerStatus, StoredEvent, StreamId, TabClientTransport, TabClientTransportOptions, TabServerTransport, TabServerTransportOptions, UserScriptClientTransport, UserScriptClientTransportOptions, UserScriptServerTransport, UserScriptServerTransportOptions };
937
+ //# sourceMappingURL=index.d.ts.map