bidi-browser-mcp 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +398 -343
  3. package/dist/bin.js +3 -2
  4. package/dist/config.js +4 -0
  5. package/dist/connection/bidi-client.d.ts +13 -1
  6. package/dist/connection/bidi-client.js +59 -8
  7. package/dist/connection/browser-discovery.d.ts +20 -0
  8. package/dist/connection/browser-discovery.js +76 -12
  9. package/dist/connection/chromium-mapper.d.ts +9 -0
  10. package/dist/connection/chromium-mapper.js +24 -0
  11. package/dist/connection/event-pipeline.d.ts +15 -2
  12. package/dist/connection/event-pipeline.js +45 -3
  13. package/dist/connection/protocol-probe.d.ts +43 -0
  14. package/dist/connection/protocol-probe.js +112 -0
  15. package/dist/index.js +6 -0
  16. package/dist/session/session-manager.d.ts +26 -1
  17. package/dist/session/session-manager.js +262 -6
  18. package/dist/snapshot/cache.d.ts +4 -0
  19. package/dist/snapshot/cache.js +8 -0
  20. package/dist/snapshot/dom-snapshot.js +190 -181
  21. package/dist/snapshot/element-script.d.ts +23 -0
  22. package/dist/snapshot/element-script.js +70 -0
  23. package/dist/snapshot/token-optimizer.js +26 -8
  24. package/dist/snapshot/uid-verify.d.ts +43 -0
  25. package/dist/snapshot/uid-verify.js +154 -0
  26. package/dist/tools/browser.js +21 -6
  27. package/dist/tools/context.js +4 -6
  28. package/dist/tools/interact.d.ts +1 -0
  29. package/dist/tools/interact.js +593 -0
  30. package/dist/tools/network.d.ts +1 -0
  31. package/dist/tools/network.js +166 -0
  32. package/dist/tools/page.js +53 -2
  33. package/dist/tools/ping.js +5 -1
  34. package/dist/tools/script.d.ts +1 -0
  35. package/dist/tools/script.js +166 -0
  36. package/dist/types.d.ts +50 -1
  37. package/dist/utils/bidi-value.d.ts +10 -0
  38. package/dist/utils/bidi-value.js +56 -0
  39. package/dist/utils/errors.d.ts +3 -1
  40. package/dist/utils/errors.js +13 -7
  41. package/dist/utils/redact.d.ts +16 -0
  42. package/dist/utils/redact.js +47 -0
  43. package/package.json +86 -86
@@ -0,0 +1,154 @@
1
+ import { ActionableError } from '../utils/errors.js';
2
+ import { unwrapBiDiValue } from '../utils/bidi-value.js';
3
+ import { resolveElement, resolvePlan } from './element-resolver.js';
4
+ /**
5
+ * Document-space rects may drift before an action runs; the size keeps its
6
+ * meaning across scrolls, DOM shifts, and reflow (plan decisions §3).
7
+ */
8
+ const SIZE_TOLERANCE = 4;
9
+ /**
10
+ * Compare a probe result with the snapshot entry.
11
+ * Precedence (§3): nothing resolved → missing; selector ambiguous → ambiguous;
12
+ * resolved but no longer the same element → stale.
13
+ */
14
+ export function compareElement(probe, element) {
15
+ if (!probe.found) {
16
+ return 'missing';
17
+ }
18
+ if (probe.matches !== 1) {
19
+ return 'ambiguous';
20
+ }
21
+ if (probe.tag === null || probe.tag !== element.tag) {
22
+ return 'stale';
23
+ }
24
+ if (probe.rect === null) {
25
+ return 'stale';
26
+ }
27
+ return (Math.abs(probe.rect[2] - (element.bounds[2] ?? 0)) <= SIZE_TOLERANCE &&
28
+ Math.abs(probe.rect[3] - (element.bounds[3] ?? 0)) <= SIZE_TOLERANCE
29
+ ? 'ok'
30
+ : 'stale');
31
+ }
32
+ /**
33
+ * The verify function: resolve the recorded plan (iframe chain → shadow root →
34
+ * selector) and report what is there now, in document-space coordinates.
35
+ * The plan is embedded as JSON, so page strings cannot break the source.
36
+ */
37
+ export function verifyFunctionSource(plan) {
38
+ const planJson = JSON.stringify({
39
+ frame: plan.frame ?? null,
40
+ shadowHost: plan.shadowHost ?? null,
41
+ selector: plan.selector,
42
+ });
43
+ return `(function verifyUid () {
44
+ var plan = ${planJson};
45
+ var out = { found: false, tag: null, rect: null, matches: 0, reason: null };
46
+ try {
47
+ var doc = document;
48
+ var frames = plan.frame || [];
49
+ for (var i = 0; i < frames.length; i++) {
50
+ var frame = doc.querySelector(frames[i]);
51
+ var inner = frame ? frame.contentDocument : null;
52
+ if (!inner || !inner.documentElement) { out.reason = 'frame unavailable'; return out; }
53
+ doc = inner;
54
+ }
55
+ var scope = doc;
56
+ if (plan.shadowHost !== null) {
57
+ var host = doc.querySelector(plan.shadowHost);
58
+ var root = host ? host.shadowRoot : null;
59
+ if (!root) { out.reason = 'shadow root unavailable'; return out; }
60
+ scope = root;
61
+ }
62
+ var matches = scope.querySelectorAll(plan.selector);
63
+ out.matches = matches.length;
64
+ var el = matches[0];
65
+ if (!el) return out;
66
+ var rect = el.getBoundingClientRect();
67
+ var view = doc.defaultView;
68
+ out.found = true;
69
+ out.tag = el.tagName.toLowerCase();
70
+ out.rect = [
71
+ rect.x + (view ? view.pageXOffset || 0 : 0),
72
+ rect.y + (view ? view.pageYOffset || 0 : 0),
73
+ rect.width,
74
+ rect.height
75
+ ];
76
+ } catch (e) {
77
+ out.reason = String(e && e.message ? e.message : e);
78
+ }
79
+ return out;
80
+ })`;
81
+ }
82
+ /** Parse a `script.callFunction` result into a probe; bad shapes probe absent. */
83
+ export function parseVerifyProbe(raw) {
84
+ const value = unwrapBiDiValue(raw);
85
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
86
+ return { found: false, tag: null, rect: null, matches: 0, reason: 'unparsable result' };
87
+ }
88
+ const record = value;
89
+ const rect = record.rect;
90
+ return {
91
+ found: record.found === true,
92
+ tag: typeof record.tag === 'string' ? record.tag : null,
93
+ rect: Array.isArray(rect) &&
94
+ rect.length === 4 &&
95
+ rect.every((entry) => typeof entry === 'number')
96
+ ? [rect[0], rect[1], rect[2], rect[3]]
97
+ : null,
98
+ matches: typeof record.matches === 'number' ? record.matches : 0,
99
+ reason: typeof record.reason === 'string' ? record.reason : null,
100
+ };
101
+ }
102
+ function verdictError(verdict, element, probe, probeReason) {
103
+ const fix = 'Take a fresh page.snapshot and retry with the new uid.';
104
+ const details = {
105
+ uid: element.uid,
106
+ selector: element.selector,
107
+ ...(probeReason === null ? {} : { probeReason }),
108
+ };
109
+ switch (verdict) {
110
+ case 'missing':
111
+ return new ActionableError('ELEMENT_NOT_FOUND', `Element ${element.uid} no longer exists: its selector resolves to nothing.`, { fix, details });
112
+ case 'ambiguous':
113
+ return new ActionableError('STALE_UID', `Element ${element.uid} is stale: its selector now matches ${probe.matches} elements.`, { fix, details });
114
+ default:
115
+ return new ActionableError('STALE_UID', `Element ${element.uid} no longer matches its snapshot identity (tag or size changed).`, { fix, details });
116
+ }
117
+ }
118
+ /**
119
+ * Re-resolve one snapshot uid in the live page. Resolves silently when the
120
+ * element still matches; otherwise throws ELEMENT_NOT_FOUND / STALE_UID
121
+ * with the precedence from plan decisions §3. Wave 1 actions call this
122
+ * before dispatching BiDi input commands.
123
+ */
124
+ export async function verifySnapshotElement(request, snapshot, uid) {
125
+ await verifyElementRef(request, resolveElement(snapshot, uid), snapshot.context, uid);
126
+ }
127
+ /**
128
+ * Verify one known element reference (the plan cache path) against the live
129
+ * page. Same verdicts and precedence as verifySnapshotElement (§3): the plan
130
+ * is only a resolution hint, verification is the safety.
131
+ */
132
+ export async function verifyElementRef(request, element, context, uid) {
133
+ const plan = resolvePlan(element);
134
+ let result;
135
+ try {
136
+ result = await request('script.callFunction', {
137
+ functionDeclaration: verifyFunctionSource(plan),
138
+ target: { context },
139
+ awaitPromise: false,
140
+ });
141
+ }
142
+ catch (error) {
143
+ if (error instanceof ActionableError) {
144
+ throw error;
145
+ }
146
+ throw new ActionableError('SCRIPT_ERROR', 'Failed to run the uid verification script.', { cause: error, details: { context, uid } });
147
+ }
148
+ const probe = parseVerifyProbe(result.result !== undefined ? result.result : result);
149
+ const verdict = compareElement(probe, element);
150
+ if (verdict !== 'ok') {
151
+ throw verdictError(verdict, element, probe, probe.reason);
152
+ }
153
+ }
154
+ //# sourceMappingURL=uid-verify.js.map
@@ -1,5 +1,6 @@
1
1
  import { defineTool, requireAction } from './base-tool.js';
2
2
  import { ActionableError } from '../utils/errors.js';
3
+ import { redactProfilePath, redactStatusProfile } from '../utils/redact.js';
3
4
  import { ok } from '../utils/result.js';
4
5
  const ACTIONS = ['status', 'profiles', 'version', 'connect', 'disconnect'];
5
6
  const INPUT_SCHEMA = {
@@ -8,7 +9,11 @@ const INPUT_SCHEMA = {
8
9
  action: {
9
10
  type: 'string',
10
11
  enum: [...ACTIONS],
11
- description: 'status: connection state; profiles: discovery candidates; version: server + browser; connect: attach; disconnect: end session',
12
+ description: 'status: connection state; profiles: discovery candidates (id, family, port, protocol reachability, connectable verdict, reason when not); version: server + browser; connect: attach (optionally to a specific candidate); disconnect: end session',
13
+ },
14
+ target: {
15
+ type: 'string',
16
+ description: "connect: which browser to attach to — candidate id from browser.profiles ('f-9444', 'c-9222'), a port ('9444'), an exact ws endpoint, or a profile/user-data path (the redacted '~\\…' form works). Omit for ordered auto-connect. Switching ends the current session first (tabs stay open).",
12
17
  },
13
18
  },
14
19
  required: ['action'],
@@ -38,7 +43,7 @@ const OUTPUT_SCHEMA = {
38
43
  export const browserTool = defineTool({
39
44
  name: 'browser',
40
45
  title: 'Browser session',
41
- description: 'Inspect and control the single BiDi session. This never launches, closes, or mutates the user’s browser.',
46
+ description: 'Inspect and control the single BiDi session. This never launches, closes, or mutates the user’s browser. connect accepts a target (candidate id, port, endpoint, or profile path) to pick a specific browser — profiles lists every discovered browser with its id, family, port, whether it is reachable and connectable (BiDi handshake verdict; Chromium is never WS-probed by the listing because attaching may require the user to approve a debugging prompt), and the live one.',
42
47
  toolset: 'core',
43
48
  actions: ACTIONS,
44
49
  inputSchema: INPUT_SCHEMA,
@@ -57,13 +62,23 @@ export const browserTool = defineTool({
57
62
  }
58
63
  switch (action) {
59
64
  case 'status':
60
- return ok(action, await session.status());
65
+ return ok(action, redactStatusProfile(await session.status()));
61
66
  case 'profiles':
62
- return ok(action, { candidates: await session.profiles() });
67
+ return ok(action, {
68
+ // Profile paths embed the OS username; redact before the tool answer.
69
+ candidates: (await session.profiles()).map((candidate) => ({
70
+ ...candidate,
71
+ ...(candidate.profilePath === undefined
72
+ ? {}
73
+ : { profilePath: redactProfilePath(candidate.profilePath) }),
74
+ })),
75
+ });
63
76
  case 'version':
64
77
  return ok(action, await session.version());
65
- case 'connect':
66
- return ok(action, await session.connect());
78
+ case 'connect': {
79
+ const target = typeof args.target === 'string' ? args.target : undefined;
80
+ return ok(action, await session.connectTo(target));
81
+ }
67
82
  case 'disconnect':
68
83
  await session.disconnect();
69
84
  return ok(action, { connected: false });
@@ -133,12 +133,10 @@ export const contextTool = defineTool({
133
133
  return ok(action, { removed: userContext });
134
134
  }
135
135
  case 'tabs-in': {
136
- const userContext = typeof args.userContext === 'string' ? args.userContext : undefined;
137
- if (userContext === undefined || userContext === '') {
138
- throw new ActionableError('INVALID_ARGUMENT', 'context.tabs-in requires userContext.', {
139
- fix: 'Pass the id from context.list.',
140
- });
141
- }
136
+ // Tab-in-container queries usually mean the default container, so a
137
+ // missing id defaults there instead of failing (Wave 0 small fix).
138
+ const raw = typeof args.userContext === 'string' ? args.userContext.trim() : '';
139
+ const userContext = raw === '' ? 'default' : raw;
142
140
  const tree = await session.request('browsingContext.getTree', { maxDepth: 1 });
143
141
  const tabs = (tree.contexts ?? [])
144
142
  .filter((entry) => entry.userContext === userContext)
@@ -0,0 +1 @@
1
+ export declare const interactTool: import("../types.js").ToolDefinition;