bidi-browser-mcp 0.1.9
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 +21 -0
- package/README.md +343 -0
- package/dist/bin.d.ts +6 -0
- package/dist/bin.js +37 -0
- package/dist/config.d.ts +6 -0
- package/dist/config.js +122 -0
- package/dist/connection/bidi-client.d.ts +29 -0
- package/dist/connection/bidi-client.js +298 -0
- package/dist/connection/browser-discovery.d.ts +30 -0
- package/dist/connection/browser-discovery.js +393 -0
- package/dist/connection/chromium-mapper.d.ts +55 -0
- package/dist/connection/chromium-mapper.js +293 -0
- package/dist/connection/event-pipeline.d.ts +37 -0
- package/dist/connection/event-pipeline.js +167 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +66 -0
- package/dist/profile/profile-store.d.ts +88 -0
- package/dist/profile/profile-store.js +350 -0
- package/dist/session/context-manager.d.ts +17 -0
- package/dist/session/context-manager.js +179 -0
- package/dist/session/session-manager.d.ts +31 -0
- package/dist/session/session-manager.js +366 -0
- package/dist/snapshot/cache.d.ts +15 -0
- package/dist/snapshot/cache.js +37 -0
- package/dist/snapshot/dom-snapshot.d.ts +5 -0
- package/dist/snapshot/dom-snapshot.js +270 -0
- package/dist/snapshot/element-resolver.d.ts +13 -0
- package/dist/snapshot/element-resolver.js +25 -0
- package/dist/snapshot/token-optimizer.d.ts +16 -0
- package/dist/snapshot/token-optimizer.js +103 -0
- package/dist/tools/base-tool.d.ts +34 -0
- package/dist/tools/base-tool.js +55 -0
- package/dist/tools/browser.d.ts +1 -0
- package/dist/tools/browser.js +75 -0
- package/dist/tools/cleanup.d.ts +1 -0
- package/dist/tools/cleanup.js +64 -0
- package/dist/tools/console.d.ts +1 -0
- package/dist/tools/console.js +87 -0
- package/dist/tools/context.d.ts +1 -0
- package/dist/tools/context.js +156 -0
- package/dist/tools/observe.d.ts +1 -0
- package/dist/tools/observe.js +92 -0
- package/dist/tools/page.d.ts +1 -0
- package/dist/tools/page.js +139 -0
- package/dist/tools/ping.d.ts +1 -0
- package/dist/tools/ping.js +71 -0
- package/dist/tools/registry.d.ts +13 -0
- package/dist/tools/registry.js +47 -0
- package/dist/tools/spaces.d.ts +1 -0
- package/dist/tools/spaces.js +98 -0
- package/dist/tools/tabs.d.ts +1 -0
- package/dist/tools/tabs.js +155 -0
- package/dist/types.d.ts +277 -0
- package/dist/types.js +5 -0
- package/dist/utils/assert.d.ts +12 -0
- package/dist/utils/assert.js +74 -0
- package/dist/utils/errors.d.ts +24 -0
- package/dist/utils/errors.js +60 -0
- package/dist/utils/result.d.ts +14 -0
- package/dist/utils/result.js +37 -0
- package/package.json +86 -0
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { WebSocket } from 'ws';
|
|
3
|
+
import { ActionableError } from '../utils/errors.js';
|
|
4
|
+
// Version-pinned in package.json: this path is a build artifact of the
|
|
5
|
+
// mapper's own build and may move between versions.
|
|
6
|
+
const MAPPER_CDP_MODULE = 'chromium-bidi/out/Default/gen/src/cdp/CdpConnection.js';
|
|
7
|
+
// The deep import above is a build artifact: a different chromium-bidi
|
|
8
|
+
// version can move or rename it, so the dependency is pinned exactly.
|
|
9
|
+
const MAPPER_VERSION = '158.0.8123-0';
|
|
10
|
+
// chromium-bidi's own engines range. The server itself runs on wider Node
|
|
11
|
+
// versions (Firefox needs no mapper); only Chromium needs this range.
|
|
12
|
+
const MAPPER_NODE_RANGE = '>=20.19.0 <22.0.0 || >=22.12.0';
|
|
13
|
+
/** True when this Node version satisfies chromium-bidi's engines range. */
|
|
14
|
+
export function nodeSupportsMapper(version = process.versions.node) {
|
|
15
|
+
const [major = 0, minor = 0] = version.split('.').map(Number);
|
|
16
|
+
if (major === 20)
|
|
17
|
+
return minor >= 19;
|
|
18
|
+
if (major === 21)
|
|
19
|
+
return true;
|
|
20
|
+
if (major === 22)
|
|
21
|
+
return minor >= 12;
|
|
22
|
+
return major > 22;
|
|
23
|
+
}
|
|
24
|
+
function mapperInstallFix() {
|
|
25
|
+
const parts = [
|
|
26
|
+
'Install the optional mapper with the package manager that installed this' +
|
|
27
|
+
' server, without omitting optional dependencies.' +
|
|
28
|
+
` npm: npm install -g chromium-bidi@${MAPPER_VERSION} (global server)` +
|
|
29
|
+
` or npm install chromium-bidi@${MAPPER_VERSION} (project server).` +
|
|
30
|
+
' pnpm: reinstall the server itself (pnpm add -g bidi-browser-mcp) or run' +
|
|
31
|
+
' it through pnpm dlx - pnpm isolates global packages, so a separate' +
|
|
32
|
+
' global chromium-bidi is not visible to the server.' +
|
|
33
|
+
' If an install used --omit=optional, reinstall without it.',
|
|
34
|
+
];
|
|
35
|
+
if (!nodeSupportsMapper()) {
|
|
36
|
+
parts.push(`chromium-bidi requires Node ${MAPPER_NODE_RANGE}; this process is` +
|
|
37
|
+
` Node ${process.versions.node}.`);
|
|
38
|
+
}
|
|
39
|
+
return parts.join(' ');
|
|
40
|
+
}
|
|
41
|
+
export function isModuleNotFound(error) {
|
|
42
|
+
const code = error?.code;
|
|
43
|
+
if (code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND') {
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
47
|
+
return /Cannot find (module|package)/i.test(message);
|
|
48
|
+
}
|
|
49
|
+
async function loadMapperModules() {
|
|
50
|
+
try {
|
|
51
|
+
const index = (await import('chromium-bidi'));
|
|
52
|
+
// Runtime-resolved deep import into the optional dependency; the cast
|
|
53
|
+
// asserts the documented shape instead of leaking `any`.
|
|
54
|
+
const cdp = (await import(MAPPER_CDP_MODULE));
|
|
55
|
+
return {
|
|
56
|
+
BidiServer: index.BidiMapper.BidiServer,
|
|
57
|
+
MapperCdpConnection: cdp.MapperCdpConnection,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
62
|
+
if (isModuleNotFound(error)) {
|
|
63
|
+
throw new ActionableError('MISSING_DEPENDENCY', 'Chromium support needs the optional "chromium-bidi" mapper package.', {
|
|
64
|
+
fix: mapperInstallFix(),
|
|
65
|
+
details: {
|
|
66
|
+
reason,
|
|
67
|
+
node: process.versions.node,
|
|
68
|
+
requiredNode: MAPPER_NODE_RANGE,
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
throw new ActionableError('CONNECTION_FAILED', 'The installed chromium-bidi mapper failed to load.', {
|
|
73
|
+
fix: `chromium-bidi is pinned at ${MAPPER_VERSION} because the mapper` +
|
|
74
|
+
' deep-import path moves between versions. Reinstall exactly that' +
|
|
75
|
+
' version with the package manager that installed this server' +
|
|
76
|
+
(nodeSupportsMapper()
|
|
77
|
+
? '.'
|
|
78
|
+
: `; this process is Node ${process.versions.node} and the mapper` +
|
|
79
|
+
` requires Node ${MAPPER_NODE_RANGE}.`),
|
|
80
|
+
details: {
|
|
81
|
+
reason,
|
|
82
|
+
pinnedVersion: MAPPER_VERSION,
|
|
83
|
+
node: process.versions.node,
|
|
84
|
+
requiredNode: MAPPER_NODE_RANGE,
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const CONNECTING = 0;
|
|
90
|
+
const OPEN = 1;
|
|
91
|
+
const CLOSED = 3;
|
|
92
|
+
/**
|
|
93
|
+
* ws-compatible facade. BiDiClient drives it exactly like a real WebSocket:
|
|
94
|
+
* every `send()` is a BiDi command routed into the mapper, every mapper
|
|
95
|
+
* reply is re-emitted as a 'message' event, and the CDP side dropping is
|
|
96
|
+
* surfaced as a socket close.
|
|
97
|
+
*/
|
|
98
|
+
export class MapperSocket extends EventEmitter {
|
|
99
|
+
CLOSED = CLOSED;
|
|
100
|
+
readyState = CONNECTING;
|
|
101
|
+
#commandHandler;
|
|
102
|
+
#teardown;
|
|
103
|
+
/**
|
|
104
|
+
* Messages the mapper emits while it is still starting. Dropping them would
|
|
105
|
+
* lose contextCreated events for tabs that already exist (the mapper replays
|
|
106
|
+
* them at startup), so they are buffered and flushed right after 'open'.
|
|
107
|
+
*/
|
|
108
|
+
#pendingMessages = [];
|
|
109
|
+
static #MAX_PENDING_MESSAGES = 500;
|
|
110
|
+
/** Registered by the BidiServer transport wrapper. */
|
|
111
|
+
setCommandHandler(handler) {
|
|
112
|
+
this.#commandHandler = handler;
|
|
113
|
+
}
|
|
114
|
+
/** Mapper outgoing message -> BiDiClient 'message' event. */
|
|
115
|
+
pushMessage(message) {
|
|
116
|
+
if (this.readyState === OPEN) {
|
|
117
|
+
this.emit('message', JSON.stringify(message));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (this.readyState === CONNECTING &&
|
|
121
|
+
this.#pendingMessages.length < MapperSocket.#MAX_PENDING_MESSAGES) {
|
|
122
|
+
this.#pendingMessages.push(message);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** Schedule 'open' and register the teardown for close paths. */
|
|
126
|
+
attach(teardown) {
|
|
127
|
+
this.#teardown = teardown;
|
|
128
|
+
// Emit 'open' on a macrotask so BiDiClient attaches its listeners (same
|
|
129
|
+
// tick as the await that produced this socket) before the event fires.
|
|
130
|
+
setTimeout(() => {
|
|
131
|
+
if (this.readyState === CONNECTING) {
|
|
132
|
+
this.readyState = OPEN;
|
|
133
|
+
this.emit('open');
|
|
134
|
+
const pending = this.#pendingMessages;
|
|
135
|
+
this.#pendingMessages = [];
|
|
136
|
+
for (const message of pending) {
|
|
137
|
+
this.emit('message', JSON.stringify(message));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}, 0);
|
|
141
|
+
}
|
|
142
|
+
/** BiDi JSON from BiDiClient; forward into the mapper. */
|
|
143
|
+
send(data) {
|
|
144
|
+
if (this.readyState !== OPEN) {
|
|
145
|
+
throw new Error('Mapper socket is not open.');
|
|
146
|
+
}
|
|
147
|
+
let command;
|
|
148
|
+
try {
|
|
149
|
+
command = JSON.parse(data);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
void this.#commandHandler?.(command);
|
|
155
|
+
}
|
|
156
|
+
close() {
|
|
157
|
+
this.terminate();
|
|
158
|
+
}
|
|
159
|
+
terminate() {
|
|
160
|
+
if (this.readyState === CLOSED) {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
this.readyState = CLOSED;
|
|
164
|
+
this.#runTeardown();
|
|
165
|
+
// Async, mirroring ws, so a listener registered right after close()
|
|
166
|
+
// still receives the event.
|
|
167
|
+
queueMicrotask(() => this.emit('close', 1000, Buffer.alloc(0)));
|
|
168
|
+
}
|
|
169
|
+
/** The CDP side dropped: surface as a socket close so sessions reset. */
|
|
170
|
+
notifyCdpDrop() {
|
|
171
|
+
this.#emitClosed();
|
|
172
|
+
}
|
|
173
|
+
#emitClosed() {
|
|
174
|
+
if (this.readyState === CLOSED) {
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
this.readyState = CLOSED;
|
|
178
|
+
this.#runTeardown();
|
|
179
|
+
queueMicrotask(() => this.emit('close', 1006, Buffer.alloc(0)));
|
|
180
|
+
}
|
|
181
|
+
#runTeardown() {
|
|
182
|
+
this.#pendingMessages = [];
|
|
183
|
+
const teardown = this.#teardown;
|
|
184
|
+
this.#teardown = undefined;
|
|
185
|
+
try {
|
|
186
|
+
teardown?.();
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
// Teardown is best effort; the socket is closing regardless.
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Connect to a Chromium CDP endpoint and start the in-process mapper.
|
|
195
|
+
* Resolves with a ws-compatible socket that speaks WebDriver BiDi.
|
|
196
|
+
*/
|
|
197
|
+
export async function openChromiumMapperSocket(options) {
|
|
198
|
+
const modules = await loadMapperModules();
|
|
199
|
+
const cdpSocket = new WebSocket(options.cdpUrl);
|
|
200
|
+
try {
|
|
201
|
+
await new Promise((resolve, reject) => {
|
|
202
|
+
const timer = setTimeout(() => {
|
|
203
|
+
cdpSocket.removeAllListeners();
|
|
204
|
+
// Same hazard as the raw BiDi path: ws emits the handshake-abort
|
|
205
|
+
// 'error' asynchronously; keep a listener attached.
|
|
206
|
+
cdpSocket.on('error', () => { });
|
|
207
|
+
try {
|
|
208
|
+
cdpSocket.terminate();
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
// Ignore terminate errors.
|
|
212
|
+
}
|
|
213
|
+
reject(new ActionableError('CONNECTION_FAILED', `Timed out connecting to the Chromium CDP endpoint at ${options.cdpUrl}.`, {
|
|
214
|
+
fix: 'Approve the debugging permission dialog in the browser window, then retry.',
|
|
215
|
+
}));
|
|
216
|
+
}, options.timeoutMs);
|
|
217
|
+
cdpSocket.once('error', (error) => {
|
|
218
|
+
clearTimeout(timer);
|
|
219
|
+
reject(new ActionableError('CONNECTION_FAILED', `Chromium CDP endpoint refused the connection: ${error.message}`, { fix: 'Verify the browser runs with --remote-debugging-port.' }));
|
|
220
|
+
});
|
|
221
|
+
cdpSocket.once('open', () => {
|
|
222
|
+
clearTimeout(timer);
|
|
223
|
+
resolve();
|
|
224
|
+
});
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
cdpSocket.removeAllListeners();
|
|
229
|
+
// ws emits the handshake-abort 'error' asynchronously; never leave the
|
|
230
|
+
// socket without a listener or the process crashes.
|
|
231
|
+
cdpSocket.on('error', () => { });
|
|
232
|
+
throw error;
|
|
233
|
+
}
|
|
234
|
+
const cdpConnection = new modules.MapperCdpConnection({
|
|
235
|
+
setOnMessage: (handler) => {
|
|
236
|
+
cdpSocket.on('message', (data) => {
|
|
237
|
+
const raw = typeof data === 'string'
|
|
238
|
+
? data
|
|
239
|
+
: Array.isArray(data)
|
|
240
|
+
? Buffer.concat(data).toString('utf8')
|
|
241
|
+
: Buffer.from(data).toString('utf8');
|
|
242
|
+
void handler(raw);
|
|
243
|
+
});
|
|
244
|
+
},
|
|
245
|
+
sendMessage: (message) => {
|
|
246
|
+
cdpSocket.send(typeof message === 'string' ? message : JSON.stringify(message));
|
|
247
|
+
},
|
|
248
|
+
close: () => {
|
|
249
|
+
try {
|
|
250
|
+
cdpSocket.close();
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
// Already closing or still handshaking.
|
|
254
|
+
}
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
const socket = new MapperSocket();
|
|
258
|
+
const browserClient = await cdpConnection.createBrowserSession();
|
|
259
|
+
const bidiServer = await modules.BidiServer.createAndStart({
|
|
260
|
+
setOnMessage: (handler) => {
|
|
261
|
+
socket.setCommandHandler(handler);
|
|
262
|
+
},
|
|
263
|
+
sendMessage: (message) => {
|
|
264
|
+
socket.pushMessage(message);
|
|
265
|
+
},
|
|
266
|
+
close: () => {
|
|
267
|
+
// Nothing extra: the mapper has no server-side socket to close.
|
|
268
|
+
},
|
|
269
|
+
}, cdpConnection, browserClient,
|
|
270
|
+
// The mapper excludes "its own" CDP target by id. This process hosts the
|
|
271
|
+
// mapper, so there is no such target; a non-existent id is harmless.
|
|
272
|
+
'bidi-browser-mcp-node-hosted-mapper');
|
|
273
|
+
// A CDP-level drop must reset our BiDi session state (SessionManager's
|
|
274
|
+
// onClose recovery depends on the 'close' event).
|
|
275
|
+
cdpSocket.once('close', () => socket.notifyCdpDrop());
|
|
276
|
+
cdpSocket.once('error', () => socket.notifyCdpDrop());
|
|
277
|
+
socket.attach(() => {
|
|
278
|
+
bidiServer.close();
|
|
279
|
+
cdpConnection.close();
|
|
280
|
+
cdpSocket.removeAllListeners();
|
|
281
|
+
// ws emits a handshake-abort 'error' after terminate; keep a listener on
|
|
282
|
+
// the teardown path or that event would crash the process.
|
|
283
|
+
cdpSocket.on('error', () => { });
|
|
284
|
+
try {
|
|
285
|
+
cdpSocket.terminate();
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
// Ignore terminate errors.
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
return socket;
|
|
292
|
+
}
|
|
293
|
+
//# sourceMappingURL=chromium-mapper.js.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { BiDiClientLike, BiDiEvent, ConsoleEntry, EventFilter, EventPipelineLike, EventRecord, RuntimeStats } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* v0.1.5 subscribes only to events its tools consume. Network, userPrompt,
|
|
4
|
+
* and download events join when their tools land, keeping buffers small.
|
|
5
|
+
*/
|
|
6
|
+
export declare const SUBSCRIBED_EVENTS: readonly ["browsingContext.contextCreated", "browsingContext.contextDestroyed", "browsingContext.domContentLoaded", "log.entryAdded"];
|
|
7
|
+
export interface EventPipelineOptions {
|
|
8
|
+
/** Max buffered events per method; oldest are dropped and counted. */
|
|
9
|
+
readonly bufferLimitPerMethod?: number;
|
|
10
|
+
}
|
|
11
|
+
type Sink = (event: BiDiEvent) => void;
|
|
12
|
+
/**
|
|
13
|
+
* Routes BiDi events to sinks and keeps bounded per-method buffers.
|
|
14
|
+
* One `session.subscribe` for the lifetime of the session.
|
|
15
|
+
*/
|
|
16
|
+
export declare class EventPipeline implements EventPipelineLike {
|
|
17
|
+
#private;
|
|
18
|
+
constructor(options?: EventPipelineOptions);
|
|
19
|
+
/**
|
|
20
|
+
* Subscribe once and start routing. Must be called after the client is
|
|
21
|
+
* connected; `session.subscribe` is a plain command here.
|
|
22
|
+
*/
|
|
23
|
+
attach(client: BiDiClientLike): Promise<void>;
|
|
24
|
+
registerSink(sink: Sink): () => void;
|
|
25
|
+
/** Called directly by sinks that were registered before the router. */
|
|
26
|
+
record(event: BiDiEvent): void;
|
|
27
|
+
events(filter?: EventFilter): readonly EventRecord[];
|
|
28
|
+
consoleEntries(filter?: {
|
|
29
|
+
level?: string;
|
|
30
|
+
context?: string;
|
|
31
|
+
limit?: number;
|
|
32
|
+
}): readonly ConsoleEntry[];
|
|
33
|
+
clearConsole(): void;
|
|
34
|
+
stats(): RuntimeStats;
|
|
35
|
+
detach(): void;
|
|
36
|
+
}
|
|
37
|
+
export {};
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { assertPositiveInt } from '../utils/assert.js';
|
|
2
|
+
/**
|
|
3
|
+
* v0.1.5 subscribes only to events its tools consume. Network, userPrompt,
|
|
4
|
+
* and download events join when their tools land, keeping buffers small.
|
|
5
|
+
*/
|
|
6
|
+
export const SUBSCRIBED_EVENTS = [
|
|
7
|
+
'browsingContext.contextCreated',
|
|
8
|
+
'browsingContext.contextDestroyed',
|
|
9
|
+
'browsingContext.domContentLoaded',
|
|
10
|
+
'log.entryAdded',
|
|
11
|
+
];
|
|
12
|
+
const DEFAULT_BUFFER_LIMIT = 200;
|
|
13
|
+
/**
|
|
14
|
+
* Routes BiDi events to sinks and keeps bounded per-method buffers.
|
|
15
|
+
* One `session.subscribe` for the lifetime of the session.
|
|
16
|
+
*/
|
|
17
|
+
export class EventPipeline {
|
|
18
|
+
#bufferLimit;
|
|
19
|
+
#buffers = new Map();
|
|
20
|
+
#dropped = new Map();
|
|
21
|
+
#sinks = new Set();
|
|
22
|
+
#offClient;
|
|
23
|
+
constructor(options = {}) {
|
|
24
|
+
this.#bufferLimit = options.bufferLimitPerMethod ?? DEFAULT_BUFFER_LIMIT;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Subscribe once and start routing. Must be called after the client is
|
|
28
|
+
* connected; `session.subscribe` is a plain command here.
|
|
29
|
+
*/
|
|
30
|
+
async attach(client) {
|
|
31
|
+
if (this.#offClient !== undefined) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
await client.request('session.subscribe', { events: [...SUBSCRIBED_EVENTS] });
|
|
35
|
+
this.#offClient = client.onEvent((event) => {
|
|
36
|
+
this.#route(event);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
registerSink(sink) {
|
|
40
|
+
this.#sinks.add(sink);
|
|
41
|
+
return () => {
|
|
42
|
+
this.#sinks.delete(sink);
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** Called directly by sinks that were registered before the router. */
|
|
46
|
+
record(event) {
|
|
47
|
+
this.#route(event);
|
|
48
|
+
}
|
|
49
|
+
#route(event) {
|
|
50
|
+
for (const sink of this.#sinks) {
|
|
51
|
+
try {
|
|
52
|
+
sink(event);
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// A failing sink must never take down the router — and with it the
|
|
56
|
+
// MCP process.
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
this.#buffer(event);
|
|
60
|
+
}
|
|
61
|
+
#buffer(event) {
|
|
62
|
+
const buffer = this.#buffers.get(event.method) ?? [];
|
|
63
|
+
if (buffer.length >= this.#bufferLimit) {
|
|
64
|
+
buffer.shift();
|
|
65
|
+
this.#dropped.set(event.method, (this.#dropped.get(event.method) ?? 0) + 1);
|
|
66
|
+
}
|
|
67
|
+
buffer.push({ method: event.method, params: event.params, receivedAt: Date.now() });
|
|
68
|
+
this.#buffers.set(event.method, buffer);
|
|
69
|
+
}
|
|
70
|
+
events(filter = {}) {
|
|
71
|
+
const limit = filter.limit === undefined ? undefined : assertPositiveInt(filter.limit, 'limit');
|
|
72
|
+
const wanted = filter.methods === undefined
|
|
73
|
+
? [...this.#buffers.keys()]
|
|
74
|
+
: filter.methods.filter((method) => this.#buffers.has(method));
|
|
75
|
+
const collected = [];
|
|
76
|
+
const returned = [];
|
|
77
|
+
for (const method of wanted) {
|
|
78
|
+
const buffer = this.#buffers.get(method) ?? [];
|
|
79
|
+
for (const record of buffer) {
|
|
80
|
+
if (filter.context !== undefined && record.params.context !== filter.context) {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
collected.push(record);
|
|
84
|
+
returned.push({ method, record });
|
|
85
|
+
if (limit !== undefined && collected.length >= limit) {
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (limit !== undefined && collected.length >= limit) {
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (filter.drain === true) {
|
|
94
|
+
// Remove only what was returned — the rest of the buffer stays for a
|
|
95
|
+
// later call.
|
|
96
|
+
for (const method of wanted) {
|
|
97
|
+
const buffer = this.#buffers.get(method) ?? [];
|
|
98
|
+
const removed = new Set(returned.filter((entry) => entry.method === method).map((entry) => entry.record));
|
|
99
|
+
this.#buffers.set(method, buffer.filter((record) => !removed.has(record)));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return collected;
|
|
103
|
+
}
|
|
104
|
+
consoleEntries(filter = {}) {
|
|
105
|
+
const records = this.events({
|
|
106
|
+
methods: ['log.entryAdded'],
|
|
107
|
+
context: filter.context,
|
|
108
|
+
});
|
|
109
|
+
const limit = filter.limit === undefined ? undefined : assertPositiveInt(filter.limit, 'limit');
|
|
110
|
+
const entries = [];
|
|
111
|
+
for (const record of records) {
|
|
112
|
+
const params = record.params;
|
|
113
|
+
const level = typeof params.level === 'string' ? params.level : 'info';
|
|
114
|
+
if (filter.level !== undefined && filter.level !== '' && level !== filter.level) {
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
entries.push({
|
|
118
|
+
channel: typeof params.channel === 'string' ? params.channel : 'console',
|
|
119
|
+
level,
|
|
120
|
+
text: describeLogText(params),
|
|
121
|
+
...(typeof record.params.context === 'string' ? { context: record.params.context } : {}),
|
|
122
|
+
receivedAt: record.receivedAt,
|
|
123
|
+
});
|
|
124
|
+
if (limit !== undefined && entries.length >= limit) {
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return entries;
|
|
129
|
+
}
|
|
130
|
+
clearConsole() {
|
|
131
|
+
this.#buffers.delete('log.entryAdded');
|
|
132
|
+
}
|
|
133
|
+
stats() {
|
|
134
|
+
const buffered = {};
|
|
135
|
+
for (const [method, buffer] of this.#buffers) {
|
|
136
|
+
if (buffer.length > 0) {
|
|
137
|
+
buffered[method] = buffer.length;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const dropped = {};
|
|
141
|
+
for (const [method, count] of this.#dropped) {
|
|
142
|
+
dropped[method] = count;
|
|
143
|
+
}
|
|
144
|
+
return { subscribed: [...SUBSCRIBED_EVENTS], buffered, dropped };
|
|
145
|
+
}
|
|
146
|
+
detach() {
|
|
147
|
+
this.#offClient?.();
|
|
148
|
+
this.#offClient = undefined;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function describeLogText(params) {
|
|
152
|
+
if (typeof params.text === 'string' && params.text !== '') {
|
|
153
|
+
return params.text;
|
|
154
|
+
}
|
|
155
|
+
if (Array.isArray(params.args)) {
|
|
156
|
+
const parts = params.args.map((arg) => {
|
|
157
|
+
if (arg !== null && typeof arg === 'object' && 'value' in arg) {
|
|
158
|
+
const value = arg.value;
|
|
159
|
+
return typeof value === 'string' ? value : JSON.stringify(value ?? null);
|
|
160
|
+
}
|
|
161
|
+
return JSON.stringify(arg);
|
|
162
|
+
});
|
|
163
|
+
return parts.join(' ');
|
|
164
|
+
}
|
|
165
|
+
return '(no text)';
|
|
166
|
+
}
|
|
167
|
+
//# sourceMappingURL=event-pipeline.js.map
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public entry point for bidi-browser-mcp.
|
|
3
|
+
*
|
|
4
|
+
* Importing this module must not start anything. The CLI entry is
|
|
5
|
+
* `src/bin.ts`, which calls `createServer()` and connects stdio.
|
|
6
|
+
*/
|
|
7
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
8
|
+
import { SessionManager } from './session/session-manager.js';
|
|
9
|
+
import type { Config } from './types.js';
|
|
10
|
+
export declare const VERSION: string;
|
|
11
|
+
export interface CreateServerOptions {
|
|
12
|
+
/** Override config in tests. Production reads env through loadConfig(). */
|
|
13
|
+
config?: Config;
|
|
14
|
+
}
|
|
15
|
+
/** Build the MCP server without attaching a transport. */
|
|
16
|
+
export declare function createServer(options?: CreateServerOptions): {
|
|
17
|
+
server: Server;
|
|
18
|
+
session: SessionManager;
|
|
19
|
+
};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public entry point for bidi-browser-mcp.
|
|
3
|
+
*
|
|
4
|
+
* Importing this module must not start anything. The CLI entry is
|
|
5
|
+
* `src/bin.ts`, which calls `createServer()` and connects stdio.
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync } from 'node:fs';
|
|
8
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
9
|
+
import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
10
|
+
import { loadConfig } from './config.js';
|
|
11
|
+
import { browserTool } from './tools/browser.js';
|
|
12
|
+
import { cleanupTool } from './tools/cleanup.js';
|
|
13
|
+
import { consoleTool } from './tools/console.js';
|
|
14
|
+
import { contextTool } from './tools/context.js';
|
|
15
|
+
import { observeTool } from './tools/observe.js';
|
|
16
|
+
import { pageTool } from './tools/page.js';
|
|
17
|
+
import { spacesTool } from './tools/spaces.js';
|
|
18
|
+
import { pingTool } from './tools/ping.js';
|
|
19
|
+
import { tabsTool } from './tools/tabs.js';
|
|
20
|
+
import { ToolRegistry } from './tools/registry.js';
|
|
21
|
+
import { SessionManager } from './session/session-manager.js';
|
|
22
|
+
import { ActionableError } from './utils/errors.js';
|
|
23
|
+
import { toToolResult } from './utils/result.js';
|
|
24
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
25
|
+
export const VERSION = pkg.version;
|
|
26
|
+
/** Build the MCP server without attaching a transport. */
|
|
27
|
+
export function createServer(options = {}) {
|
|
28
|
+
const config = options.config ?? loadConfig();
|
|
29
|
+
if (config.outputMode === 'file') {
|
|
30
|
+
throw new ActionableError('INVALID_CONFIG', 'BIDI_OUTPUT_MODE=file is not implemented yet.', { fix: 'Use BIDI_OUTPUT_MODE=full or BIDI_OUTPUT_MODE=inline.' });
|
|
31
|
+
}
|
|
32
|
+
const session = new SessionManager({ config, serverVersion: VERSION });
|
|
33
|
+
const ctx = {
|
|
34
|
+
version: VERSION,
|
|
35
|
+
config,
|
|
36
|
+
startedAt: Date.now(),
|
|
37
|
+
session,
|
|
38
|
+
};
|
|
39
|
+
const registry = new ToolRegistry();
|
|
40
|
+
registry.register(pingTool);
|
|
41
|
+
registry.register(browserTool);
|
|
42
|
+
registry.register(tabsTool);
|
|
43
|
+
registry.register(consoleTool);
|
|
44
|
+
registry.register(observeTool);
|
|
45
|
+
registry.register(cleanupTool);
|
|
46
|
+
registry.register(pageTool);
|
|
47
|
+
registry.register(contextTool);
|
|
48
|
+
registry.register(spacesTool);
|
|
49
|
+
const server = new Server({ name: 'bidi-browser-mcp', version: VERSION }, { capabilities: { tools: {} } });
|
|
50
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
51
|
+
tools: registry.toolsFor(config.toolset).map((tool) => ({
|
|
52
|
+
name: tool.name,
|
|
53
|
+
title: tool.title,
|
|
54
|
+
description: tool.description,
|
|
55
|
+
inputSchema: tool.inputSchema,
|
|
56
|
+
...(tool.outputSchema === undefined ? {} : { outputSchema: tool.outputSchema }),
|
|
57
|
+
...(tool.annotations === undefined ? {} : { annotations: tool.annotations }),
|
|
58
|
+
})),
|
|
59
|
+
}));
|
|
60
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
61
|
+
const result = await registry.dispatch(request.params.name, request.params.arguments ?? {}, ctx);
|
|
62
|
+
return toToolResult(result, config.maxInlineLen, config.outputMode);
|
|
63
|
+
});
|
|
64
|
+
return { server, session };
|
|
65
|
+
}
|
|
66
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only Firefox/Zen profile data: container identities and Zen spaces.
|
|
3
|
+
* Nothing here writes to the profile; the browser owns its files.
|
|
4
|
+
*/
|
|
5
|
+
export interface ContainerIdentity {
|
|
6
|
+
readonly userContextId: number;
|
|
7
|
+
readonly name?: string;
|
|
8
|
+
readonly icon?: string;
|
|
9
|
+
readonly color?: string;
|
|
10
|
+
readonly isPublic: boolean;
|
|
11
|
+
}
|
|
12
|
+
export interface SpaceInfo {
|
|
13
|
+
readonly uuid: string;
|
|
14
|
+
readonly name: string;
|
|
15
|
+
readonly themeType?: string;
|
|
16
|
+
/** Zen binds spaces to container ids (containers.json int id). */
|
|
17
|
+
readonly containerId?: number;
|
|
18
|
+
}
|
|
19
|
+
export interface ProfileStore {
|
|
20
|
+
readonly containers: readonly ContainerIdentity[];
|
|
21
|
+
readonly spaces: readonly SpaceInfo[];
|
|
22
|
+
/** Non-fatal read problems, surfaced to the caller. */
|
|
23
|
+
readonly warnings: readonly string[];
|
|
24
|
+
}
|
|
25
|
+
export interface ContainerNameJoin {
|
|
26
|
+
readonly names: ReadonlyMap<string, ContainerIdentity>;
|
|
27
|
+
/**
|
|
28
|
+
* True when the number of BiDi ids matches the number of public identities.
|
|
29
|
+
* Firefox exposes no id bridge, so the join is positional and only
|
|
30
|
+
* trustworthy while the counts line up.
|
|
31
|
+
*/
|
|
32
|
+
readonly aligned: boolean;
|
|
33
|
+
}
|
|
34
|
+
/** Refuse to decode an unbounded session store into the MCP process. */
|
|
35
|
+
export declare const MAX_SESSION_STORE_BYTES: number;
|
|
36
|
+
/** containers.json holds a handful of identities; anything larger is corrupt. */
|
|
37
|
+
export declare const MAX_CONTAINERS_BYTES: number;
|
|
38
|
+
/**
|
|
39
|
+
* Hard ceiling for decoded output. The input cap does not bound expansion:
|
|
40
|
+
* LZ4 overlapping matches can inflate a small file enormously.
|
|
41
|
+
*/
|
|
42
|
+
export declare const MAX_DECODED_BYTES: number;
|
|
43
|
+
/**
|
|
44
|
+
* Decode an LZ4 block (Firefox's mozLz4 payload). Minimal, dev-stable.
|
|
45
|
+
* `expectedSize` preallocates the output buffer — the byte-per-number array
|
|
46
|
+
* this replaced cost ~8 bytes per decoded byte.
|
|
47
|
+
*
|
|
48
|
+
* Safety: buffers are zero-filled (never `allocUnsafe`), a short literal read
|
|
49
|
+
* is an error instead of a gap, and the decoded size is capped.
|
|
50
|
+
*/
|
|
51
|
+
export declare function lz4BlockDecode(input: Buffer, expectedSize?: number): Buffer;
|
|
52
|
+
/** Decode a Firefox mozLz4 container (8-byte magic + size + LZ4 block). */
|
|
53
|
+
export declare function decodeMozLz4(raw: Buffer): string;
|
|
54
|
+
export declare function parseContainersJson(text: string): readonly ContainerIdentity[];
|
|
55
|
+
/**
|
|
56
|
+
* Extract space definitions from the session store. Objects look like
|
|
57
|
+
* `{"uuid":"{...}","name":"...","theme":{...},"containerTabId":N,...}`;
|
|
58
|
+
* the anchor regex hits inside the object, so scanning resumes from the
|
|
59
|
+
* nearest preceding `{` and parses a balanced object. The anchor tolerates
|
|
60
|
+
* whitespace and any key order, so a Zen format change does not silently
|
|
61
|
+
* empty the list.
|
|
62
|
+
*/
|
|
63
|
+
export declare function parseSpaces(text: string): readonly SpaceInfo[];
|
|
64
|
+
/**
|
|
65
|
+
* Join BiDi user context ids (uuids, 'default' first in id order) with
|
|
66
|
+
* containers.json identities. Verified on Firefox 158/Zen 1.23: BiDi lists
|
|
67
|
+
* public containers in internal-id order; names join positionally. The
|
|
68
|
+
* "default" context has no containers.json identity.
|
|
69
|
+
*
|
|
70
|
+
* The join is positional because Firefox exposes no id bridge, so it is only
|
|
71
|
+
* trustworthy while the counts line up. A mismatch means a name could land on
|
|
72
|
+
* the wrong container — names are dropped instead.
|
|
73
|
+
*/
|
|
74
|
+
export declare function joinContainerNames(bidiIds: readonly string[], containers: readonly ContainerIdentity[]): ContainerNameJoin;
|
|
75
|
+
/** Read container identities only. Never touches the session store. */
|
|
76
|
+
export declare function readContainers(profilePath: string): readonly ContainerIdentity[];
|
|
77
|
+
export interface SpacesReadResult {
|
|
78
|
+
readonly spaces: readonly SpaceInfo[];
|
|
79
|
+
readonly warnings: readonly string[];
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Read Zen spaces from the session store. The file can hold open-tab URLs and
|
|
83
|
+
* form state — only derived metadata (uuid, name, theme, container id) leaves
|
|
84
|
+
* this function.
|
|
85
|
+
*/
|
|
86
|
+
export declare function readSpaces(profilePath: string): SpacesReadResult;
|
|
87
|
+
/** Read profile data; missing files degrade to empty lists. */
|
|
88
|
+
export declare function readProfileStore(profilePath: string): ProfileStore;
|