webmcp-settle 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +148 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/navigate.d.ts +35 -0
- package/dist/navigate.js +68 -0
- package/dist/navigate.js.map +1 -0
- package/dist/settle.d.ts +62 -0
- package/dist/settle.js +122 -0
- package/dist/settle.js.map +1 -0
- package/package.json +27 -4
- package/probe/README.md +78 -0
- package/probe/webmcp-timing-probe.mjs +514 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Craft Quantities
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,149 @@
|
|
|
1
|
-
#
|
|
1
|
+
# webmcp-settle
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Wait for a page's [WebMCP](https://github.com/webmachinelearning/webmcp) tools to finish registering, and navigate
|
|
4
|
+
single-page apps without answering early.
|
|
5
|
+
|
|
6
|
+
[](https://github.com/Axelima/webmcp-settle/actions/workflows/ci.yml)
|
|
7
|
+
[](LICENSE)
|
|
8
|
+
|
|
9
|
+
Two small pieces, no dependencies, any framework:
|
|
10
|
+
|
|
11
|
+
- **`webmcp-settle`**: a ~200-line library for the page.
|
|
12
|
+
- **[`probe/`](probe/)**: a read-only command-line tool that measures when a site's tools register.
|
|
13
|
+
|
|
14
|
+
## The problem
|
|
15
|
+
|
|
16
|
+
Most pages load their WebMCP tool module after they render, so tools register some time after the page appears. A
|
|
17
|
+
navigation is also several steps: the address changes, the new heading is drawn, the document title is set in an
|
|
18
|
+
effect, and the page's tools register last.
|
|
19
|
+
|
|
20
|
+
An agent that acts when the first step finishes works with the wrong state. It reports the previous page's title, or
|
|
21
|
+
it lists tools and sees only the site-wide ones.
|
|
22
|
+
|
|
23
|
+
This was measured on a production site with about 200 WebMCP tools
|
|
24
|
+
([craftquantities.com](https://craftquantities.com/developers/webmcp/)) and discussed in
|
|
25
|
+
[webmachinelearning/webmcp#402](https://github.com/webmachinelearning/webmcp/issues/402). The site's `open_page` tool
|
|
26
|
+
was fixed with exactly the code in this package. Over 42 live navigations:
|
|
27
|
+
|
|
28
|
+
| | before | after |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| Navigations answered while every one of the new page's tools was still unregistered | 36 / 42 | 1 / 42 |
|
|
31
|
+
| Calculator → calculator (the same `<h1>` element reused by React) | 8 s, then timed out | 0.2 s |
|
|
32
|
+
| `open_page` median | 1,042 ms | 771 ms |
|
|
33
|
+
|
|
34
|
+
The same timing shows up in Chrome DevTools MCP. Right after `navigate_page`, `list_webmcp_tools` returned the 8
|
|
35
|
+
site-wide tools; about a second later it returned all 19.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
npm install webmcp-settle
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Use
|
|
44
|
+
|
|
45
|
+
### 1. Announce each registration
|
|
46
|
+
|
|
47
|
+
Wrap the step that loads and registers a page's tools, so a waiter knows it is in progress:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { modelContext, registerTracked } from "webmcp-settle";
|
|
51
|
+
|
|
52
|
+
const context = modelContext(); // document.modelContext, or null where the browser has none
|
|
53
|
+
if (context) {
|
|
54
|
+
const controller = new AbortController(); // abort it when the page unmounts: that unregisters the tools
|
|
55
|
+
registerTracked(context, async () => (await import("./calculator-tools.js")).tools, controller.signal);
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Code in another bundle can announce without importing anything:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
window.dispatchEvent(new CustomEvent("webmcp:pending", { detail: registrationPromise }));
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### 2. Wait for the tools
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { listenForPending, toolsSettled } from "webmcp-settle";
|
|
69
|
+
|
|
70
|
+
listenForPending(); // once, early: counts registrations announced with the window event
|
|
71
|
+
const complete = await toolsSettled({ timeoutMs: 5000 }); // false on timeout or abort
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### 3. Navigate and answer only when the new page is there
|
|
75
|
+
|
|
76
|
+
For a site-wide navigation tool such as `open_page`:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import { navigateAndSettle } from "webmcp-settle";
|
|
80
|
+
|
|
81
|
+
const result = await navigateAndSettle((url) => router.push(url), "/calculators/concrete/", {
|
|
82
|
+
headingSelector: "main h1",
|
|
83
|
+
});
|
|
84
|
+
// { arrived, toolsSettled, title, heading, path }
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`navigateAndSettle` waits for four things, in order:
|
|
88
|
+
|
|
89
|
+
1. The address is the requested one.
|
|
90
|
+
2. The heading is new. It counts as new when it is a different element, or the same element with different text,
|
|
91
|
+
because frameworks such as React reuse the `<h1>` between two pages of one kind.
|
|
92
|
+
3. The document title has had a short window to follow.
|
|
93
|
+
4. Every registration the new page announced has finished.
|
|
94
|
+
|
|
95
|
+
### With React
|
|
96
|
+
|
|
97
|
+
```tsx
|
|
98
|
+
import { useEffect } from "react";
|
|
99
|
+
import { modelContext, registerTracked } from "webmcp-settle";
|
|
100
|
+
|
|
101
|
+
export function useWebMcpTools(load: () => Promise<readonly { name: string }[]>, key: string) {
|
|
102
|
+
useEffect(() => {
|
|
103
|
+
const context = modelContext();
|
|
104
|
+
if (!context) return;
|
|
105
|
+
const controller = new AbortController();
|
|
106
|
+
registerTracked(context, load, controller.signal);
|
|
107
|
+
return () => controller.abort();
|
|
108
|
+
}, [key]);
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## API
|
|
113
|
+
|
|
114
|
+
| Export | What it does |
|
|
115
|
+
|---|---|
|
|
116
|
+
| `modelContext()` | `document.modelContext`, or `null` where the browser offers none |
|
|
117
|
+
| `registerTracked(context, load, signal?)` | Loads the tools, registers each with `signal`, skips refused names, announces the whole step. Resolves to the names registered |
|
|
118
|
+
| `trackPending(promise)` | Counts a registration in progress until it settles |
|
|
119
|
+
| `announcePending(promise, target?)` | Dispatches `webmcp:pending` with the promise; returns it |
|
|
120
|
+
| `listenForPending(target?)` | Starts counting announced registrations; returns a stop function |
|
|
121
|
+
| `pendingCount()` | Registrations not finished yet |
|
|
122
|
+
| `toolsSettled({ timeoutMs, signal, frames })` | `true` once none is pending; `false` on timeout or abort |
|
|
123
|
+
| `navigateAndSettle(navigate, url, options)` | Navigates and resolves `{ arrived, toolsSettled, title, heading, path }` |
|
|
124
|
+
| `waitFor(check, { timeoutMs, signal })` | Polls `check()` every animation frame |
|
|
125
|
+
|
|
126
|
+
## Measuring a site
|
|
127
|
+
|
|
128
|
+
[`probe/`](probe/) opens a site's pages in Chrome with WebMCP switched on. For each page it records when every tool
|
|
129
|
+
registers, the registration waves, and the time until the tool set settles. It can also time a site's own navigation
|
|
130
|
+
tool and count the tools that register after that tool has answered. It only reads the pages; the one exception is
|
|
131
|
+
the navigation tool you name, which it calls. See [probe/README.md](probe/README.md).
|
|
132
|
+
|
|
133
|
+
## Using the tools from Chrome DevTools MCP
|
|
134
|
+
|
|
135
|
+
[chrome-devtools-mcp](https://github.com/ChromeDevTools/chrome-devtools-mcp) lists and calls WebMCP tools when it is
|
|
136
|
+
started with `--categoryExperimentalWebmcp --chromeArg=--enable-features=WebMCP`. Remember that a list taken right
|
|
137
|
+
after `navigate_page` can be partial, so list again or use the site's own settled navigation tool.
|
|
138
|
+
|
|
139
|
+
## Requirements
|
|
140
|
+
|
|
141
|
+
- Browsers with WebMCP: Chrome with `--enable-features=WebMCP`. Elsewhere `modelContext()` returns `null` and
|
|
142
|
+
nothing is loaded.
|
|
143
|
+
- The library is ES2022 with no dependencies.
|
|
144
|
+
- The probe needs Node 20+, Playwright, and an installed Chrome.
|
|
145
|
+
|
|
146
|
+
## License
|
|
147
|
+
|
|
148
|
+
[MIT](LICENSE). Made by [Craft Quantities](https://craftquantities.com), a free construction quantities site whose
|
|
149
|
+
pages expose their calculators to browser agents through WebMCP.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { PENDING_EVENT, trackPending, announcePending, listenForPending, pendingCount, toolsSettled, registerTracked, modelContext, type SettleOptions, type ToolLike, type ModelContextLike, } from "./settle.js";
|
|
2
|
+
export { navigateAndSettle, waitFor, type NavigateOptions, type NavigateResult, type WaitOptions } from "./navigate.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,YAAY,EACZ,YAAY,EACZ,eAAe,EACf,YAAY,GAIb,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAA+D,MAAM,eAAe,CAAC"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export interface WaitOptions {
|
|
2
|
+
timeoutMs?: number;
|
|
3
|
+
signal?: AbortSignal;
|
|
4
|
+
}
|
|
5
|
+
/** Resolves true once `check()` holds (checked every animation frame), false on timeout or abort. */
|
|
6
|
+
export declare function waitFor(check: () => boolean, { timeoutMs, signal }?: WaitOptions): Promise<boolean>;
|
|
7
|
+
export interface NavigateOptions {
|
|
8
|
+
/** Where the page's main heading is (default "main h1"): its change marks the new page as drawn. */
|
|
9
|
+
headingSelector?: string;
|
|
10
|
+
/** How long the new page may take to show, in ms (default 8000). */
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
/** How long to wait for the document title to follow the heading, in ms (default 1500). */
|
|
13
|
+
titleTimeoutMs?: number;
|
|
14
|
+
/** How long to wait for the new page's tools, in ms (default 5000). */
|
|
15
|
+
toolsTimeoutMs?: number;
|
|
16
|
+
signal?: AbortSignal;
|
|
17
|
+
}
|
|
18
|
+
export interface NavigateResult {
|
|
19
|
+
/** The new page was shown at the requested path before the timeout. */
|
|
20
|
+
arrived: boolean;
|
|
21
|
+
/** Every tool registration announced by the new page finished before its timeout. */
|
|
22
|
+
toolsSettled: boolean;
|
|
23
|
+
/** The new page's title: the document title, or its heading when the title was never updated. */
|
|
24
|
+
title: string;
|
|
25
|
+
heading: string;
|
|
26
|
+
path: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Calls `navigate(url)` (the app router's push, or a link click) and resolves once the requested path shows a new
|
|
30
|
+
* heading, the title has had a moment to follow, and the new page's announced tool registrations have finished.
|
|
31
|
+
*
|
|
32
|
+
* A heading counts as new when it is a different element OR the same element with different text: frameworks such as
|
|
33
|
+
* React keep the same `<h1>` between two pages of one kind, so an element check alone never sees the second page.
|
|
34
|
+
*/
|
|
35
|
+
export declare function navigateAndSettle(navigate: (url: string) => unknown, url: string, options?: NavigateOptions): Promise<NavigateResult>;
|
package/dist/navigate.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Navigating inside a single-page app and answering only once the new page is really there.
|
|
3
|
+
*
|
|
4
|
+
* In a client-side navigation the address changes first, the new page's heading is drawn next, the document title is
|
|
5
|
+
* set in an effect after that, and the page's own tools register later still. A navigation tool that answers at the
|
|
6
|
+
* first of these reports the page it came from, or leaves the agent with the old page's tool list. This waits for
|
|
7
|
+
* each step in turn.
|
|
8
|
+
*/
|
|
9
|
+
import { toolsSettled } from "./settle.js";
|
|
10
|
+
/** Resolves true once `check()` holds (checked every animation frame), false on timeout or abort. */
|
|
11
|
+
export function waitFor(check, { timeoutMs = 8000, signal } = {}) {
|
|
12
|
+
return new Promise((resolve) => {
|
|
13
|
+
const until = Date.now() + timeoutMs;
|
|
14
|
+
const tick = () => {
|
|
15
|
+
if (signal?.aborted)
|
|
16
|
+
return resolve(false);
|
|
17
|
+
let ok = false;
|
|
18
|
+
try {
|
|
19
|
+
ok = check();
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
ok = false;
|
|
23
|
+
}
|
|
24
|
+
if (ok)
|
|
25
|
+
return resolve(true);
|
|
26
|
+
if (Date.now() >= until)
|
|
27
|
+
return resolve(false);
|
|
28
|
+
if (typeof requestAnimationFrame === "function")
|
|
29
|
+
requestAnimationFrame(tick);
|
|
30
|
+
else
|
|
31
|
+
setTimeout(tick, 16);
|
|
32
|
+
};
|
|
33
|
+
tick();
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
const trimSlash = (p) => p.replace(/\/+$/, "") || "/";
|
|
37
|
+
/**
|
|
38
|
+
* Calls `navigate(url)` (the app router's push, or a link click) and resolves once the requested path shows a new
|
|
39
|
+
* heading, the title has had a moment to follow, and the new page's announced tool registrations have finished.
|
|
40
|
+
*
|
|
41
|
+
* A heading counts as new when it is a different element OR the same element with different text: frameworks such as
|
|
42
|
+
* React keep the same `<h1>` between two pages of one kind, so an element check alone never sees the second page.
|
|
43
|
+
*/
|
|
44
|
+
export async function navigateAndSettle(navigate, url, options = {}) {
|
|
45
|
+
const { headingSelector = "main h1", timeoutMs = 8000, titleTimeoutMs = 1500, toolsTimeoutMs = 5000, signal } = options;
|
|
46
|
+
const target = new URL(url, location.href);
|
|
47
|
+
const samePage = trimSlash(target.pathname) === trimSlash(location.pathname);
|
|
48
|
+
const oldHeading = document.querySelector(headingSelector);
|
|
49
|
+
const oldHeadingText = oldHeading?.textContent ?? "";
|
|
50
|
+
const oldTitle = document.title;
|
|
51
|
+
navigate(url);
|
|
52
|
+
const arrived = await waitFor(() => {
|
|
53
|
+
if (trimSlash(location.pathname) !== trimSlash(target.pathname))
|
|
54
|
+
return false;
|
|
55
|
+
const heading = document.querySelector(headingSelector);
|
|
56
|
+
return heading !== null && (samePage || heading !== oldHeading || (heading.textContent ?? "") !== oldHeadingText);
|
|
57
|
+
}, { timeoutMs, signal });
|
|
58
|
+
const read = () => ({ heading: (document.querySelector(headingSelector)?.textContent ?? "").trim(), path: location.pathname + location.search });
|
|
59
|
+
if (!arrived)
|
|
60
|
+
return { arrived: false, toolsSettled: false, title: document.title, ...read() };
|
|
61
|
+
if (!samePage)
|
|
62
|
+
await waitFor(() => document.title !== oldTitle, { timeoutMs: titleTimeoutMs, signal });
|
|
63
|
+
const settled = await toolsSettled({ timeoutMs: toolsTimeoutMs, signal });
|
|
64
|
+
const now = read();
|
|
65
|
+
const title = samePage || document.title !== oldTitle ? document.title : now.heading || document.title;
|
|
66
|
+
return { arrived: true, toolsSettled: settled, title, ...now };
|
|
67
|
+
}
|
|
68
|
+
//# sourceMappingURL=nav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G,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;IACjJ,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC;IAE/F,IAAI,CAAC,QAAQ;QAAE,MAAM,OAAO,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,KAAK,KAAK,QAAQ,EAAE,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,EAAE,CAAC,CAAC;IACvG,MAAM,OAAO,GAAG,MAAM,YAAY,CAAC,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,EAAE,CAAC,CAAC;IAC1E,MAAM,GAAG,GAAG,IAAI,EAAE,CAAC;IACnB,MAAM,KAAK,GAAG,QAAQ,IAAI,QAAQ,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,IAAI,QAAQ,CAAC,KAAK,CAAC;IACvG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,GAAG,EAAE,CAAC;AACjE,CAAC"}
|
package/dist/settle.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool registrations still in progress, and waiting for them to finish.
|
|
3
|
+
*
|
|
4
|
+
* A page usually loads its WebMCP tool module after it mounts, so tools are registered some time after the page
|
|
5
|
+
* appears. An agent that navigates and then lists the tools straight away sees only the ones that were already there.
|
|
6
|
+
* A page (or each component that registers tools) announces the promise that registers them; `toolsSettled()` waits
|
|
7
|
+
* until every announced registration has finished.
|
|
8
|
+
*
|
|
9
|
+
* Announcing goes through a window event, so code that registers tools does not need to import this module: it can
|
|
10
|
+
* dispatch `new CustomEvent(PENDING_EVENT, { detail: promise })` itself.
|
|
11
|
+
*/
|
|
12
|
+
/** The window event a page dispatches with the promise that registers its tools as `detail`. */
|
|
13
|
+
export declare const PENDING_EVENT = "webmcp:pending";
|
|
14
|
+
/** Counts `loading` as a registration in progress until it settles (fulfilled or rejected). */
|
|
15
|
+
export declare function trackPending(loading: PromiseLike<unknown>): void;
|
|
16
|
+
/**
|
|
17
|
+
* Announces `loading` on `target` (the window by default) with {@link PENDING_EVENT}, for pages whose waiting code
|
|
18
|
+
* lives in another bundle. Returns `loading` so it can be awaited in place.
|
|
19
|
+
*/
|
|
20
|
+
export declare function announcePending<T>(loading: Promise<T>, target?: EventTarget | undefined): Promise<T>;
|
|
21
|
+
/**
|
|
22
|
+
* Starts counting the registrations announced on `target` with {@link PENDING_EVENT}. Called once, before any page
|
|
23
|
+
* code runs, by whatever waits for the tools (a navigation tool, a test harness). Returns a function that stops it.
|
|
24
|
+
*/
|
|
25
|
+
export declare function listenForPending(target?: EventTarget | undefined): () => void;
|
|
26
|
+
/** How many announced registrations have not finished yet. */
|
|
27
|
+
export declare function pendingCount(): number;
|
|
28
|
+
export interface SettleOptions {
|
|
29
|
+
/** Give up after this long, in milliseconds (5000 by default). */
|
|
30
|
+
timeoutMs?: number;
|
|
31
|
+
/** Stop waiting when this aborts (resolves false). */
|
|
32
|
+
signal?: AbortSignal;
|
|
33
|
+
/**
|
|
34
|
+
* Animation frames to wait first (2 by default), so a page that has just committed has had the chance to start its
|
|
35
|
+
* registrations in its effects before the count is read.
|
|
36
|
+
*/
|
|
37
|
+
frames?: number;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Resolves `true` once no announced registration is in progress, or `false` on timeout or abort. New registrations
|
|
41
|
+
* announced while waiting are waited for too.
|
|
42
|
+
*/
|
|
43
|
+
export declare function toolsSettled(options?: SettleOptions): Promise<boolean>;
|
|
44
|
+
/** The members of a WebMCP tool this module relies on. */
|
|
45
|
+
export interface ToolLike {
|
|
46
|
+
name: string;
|
|
47
|
+
[key: string]: unknown;
|
|
48
|
+
}
|
|
49
|
+
/** The part of `document.modelContext` this module uses. */
|
|
50
|
+
export interface ModelContextLike {
|
|
51
|
+
registerTool(tool: ToolLike, options?: {
|
|
52
|
+
signal?: AbortSignal;
|
|
53
|
+
}): unknown;
|
|
54
|
+
}
|
|
55
|
+
/** The document's model context, or null where the browser offers none. */
|
|
56
|
+
export declare function modelContext(): ModelContextLike | null;
|
|
57
|
+
/**
|
|
58
|
+
* Loads and registers a page's tools as one tracked registration: `load()` returns the tool list (typically from a
|
|
59
|
+
* dynamic import), each tool is registered with `signal`, and the whole step is announced so `toolsSettled()` waits
|
|
60
|
+
* for it. A tool the browser refuses (a name already taken) is skipped. Resolves to the names registered.
|
|
61
|
+
*/
|
|
62
|
+
export declare function registerTracked(context: ModelContextLike, load: () => Promise<readonly ToolLike[]> | readonly ToolLike[], signal?: AbortSignal): Promise<string[]>;
|
package/dist/settle.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool registrations still in progress, and waiting for them to finish.
|
|
3
|
+
*
|
|
4
|
+
* A page usually loads its WebMCP tool module after it mounts, so tools are registered some time after the page
|
|
5
|
+
* appears. An agent that navigates and then lists the tools straight away sees only the ones that were already there.
|
|
6
|
+
* A page (or each component that registers tools) announces the promise that registers them; `toolsSettled()` waits
|
|
7
|
+
* until every announced registration has finished.
|
|
8
|
+
*
|
|
9
|
+
* Announcing goes through a window event, so code that registers tools does not need to import this module: it can
|
|
10
|
+
* dispatch `new CustomEvent(PENDING_EVENT, { detail: promise })` itself.
|
|
11
|
+
*/
|
|
12
|
+
/** The window event a page dispatches with the promise that registers its tools as `detail`. */
|
|
13
|
+
export const PENDING_EVENT = "webmcp:pending";
|
|
14
|
+
const pending = new Set();
|
|
15
|
+
let listening = false;
|
|
16
|
+
/** Counts `loading` as a registration in progress until it settles (fulfilled or rejected). */
|
|
17
|
+
export function trackPending(loading) {
|
|
18
|
+
const promise = Promise.resolve(loading);
|
|
19
|
+
pending.add(promise);
|
|
20
|
+
const done = () => {
|
|
21
|
+
pending.delete(promise);
|
|
22
|
+
};
|
|
23
|
+
promise.then(done, done);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Announces `loading` on `target` (the window by default) with {@link PENDING_EVENT}, for pages whose waiting code
|
|
27
|
+
* lives in another bundle. Returns `loading` so it can be awaited in place.
|
|
28
|
+
*/
|
|
29
|
+
export function announcePending(loading, target = globalThis.window) {
|
|
30
|
+
target?.dispatchEvent(new CustomEvent(PENDING_EVENT, { detail: loading }));
|
|
31
|
+
return loading;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Starts counting the registrations announced on `target` with {@link PENDING_EVENT}. Called once, before any page
|
|
35
|
+
* code runs, by whatever waits for the tools (a navigation tool, a test harness). Returns a function that stops it.
|
|
36
|
+
*/
|
|
37
|
+
export function listenForPending(target = globalThis.window) {
|
|
38
|
+
if (!target || listening)
|
|
39
|
+
return () => undefined;
|
|
40
|
+
listening = true;
|
|
41
|
+
const onPending = (event) => {
|
|
42
|
+
const loading = event.detail;
|
|
43
|
+
if (loading && typeof loading.then === "function")
|
|
44
|
+
trackPending(loading);
|
|
45
|
+
};
|
|
46
|
+
target.addEventListener(PENDING_EVENT, onPending);
|
|
47
|
+
return () => {
|
|
48
|
+
target.removeEventListener(PENDING_EVENT, onPending);
|
|
49
|
+
listening = false;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** How many announced registrations have not finished yet. */
|
|
53
|
+
export function pendingCount() {
|
|
54
|
+
return pending.size;
|
|
55
|
+
}
|
|
56
|
+
const nextFrame = () => new Promise((resolve) => {
|
|
57
|
+
if (typeof requestAnimationFrame === "function")
|
|
58
|
+
requestAnimationFrame(() => resolve());
|
|
59
|
+
else
|
|
60
|
+
setTimeout(resolve, 16);
|
|
61
|
+
});
|
|
62
|
+
/**
|
|
63
|
+
* Resolves `true` once no announced registration is in progress, or `false` on timeout or abort. New registrations
|
|
64
|
+
* announced while waiting are waited for too.
|
|
65
|
+
*/
|
|
66
|
+
export async function toolsSettled(options = {}) {
|
|
67
|
+
const { timeoutMs = 5000, signal, frames = 2 } = options;
|
|
68
|
+
const until = Date.now() + timeoutMs;
|
|
69
|
+
for (let i = 0; i < frames; i++)
|
|
70
|
+
await nextFrame();
|
|
71
|
+
while (pending.size > 0) {
|
|
72
|
+
if (signal?.aborted)
|
|
73
|
+
return false;
|
|
74
|
+
const left = until - Date.now();
|
|
75
|
+
if (left <= 0)
|
|
76
|
+
return false;
|
|
77
|
+
let timer;
|
|
78
|
+
await Promise.race([
|
|
79
|
+
Promise.allSettled([...pending]),
|
|
80
|
+
new Promise((resolve) => {
|
|
81
|
+
timer = setTimeout(resolve, left);
|
|
82
|
+
}),
|
|
83
|
+
]);
|
|
84
|
+
clearTimeout(timer);
|
|
85
|
+
await nextFrame();
|
|
86
|
+
}
|
|
87
|
+
return !signal?.aborted;
|
|
88
|
+
}
|
|
89
|
+
/** The document's model context, or null where the browser offers none. */
|
|
90
|
+
export function modelContext() {
|
|
91
|
+
const doc = globalThis.document;
|
|
92
|
+
const context = doc?.modelContext;
|
|
93
|
+
return context && typeof context.registerTool === "function" ? context : null;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Loads and registers a page's tools as one tracked registration: `load()` returns the tool list (typically from a
|
|
97
|
+
* dynamic import), each tool is registered with `signal`, and the whole step is announced so `toolsSettled()` waits
|
|
98
|
+
* for it. A tool the browser refuses (a name already taken) is skipped. Resolves to the names registered.
|
|
99
|
+
*/
|
|
100
|
+
export function registerTracked(context, load, signal) {
|
|
101
|
+
const run = (async () => {
|
|
102
|
+
const tools = await load();
|
|
103
|
+
const names = [];
|
|
104
|
+
for (const tool of tools) {
|
|
105
|
+
if (signal?.aborted)
|
|
106
|
+
break;
|
|
107
|
+
try {
|
|
108
|
+
const result = context.registerTool(tool, signal ? { signal } : undefined);
|
|
109
|
+
if (result && typeof result.then === "function")
|
|
110
|
+
await result;
|
|
111
|
+
names.push(tool.name);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return names;
|
|
118
|
+
})();
|
|
119
|
+
trackPending(run);
|
|
120
|
+
return announcePending(run);
|
|
121
|
+
}
|
|
122
|
+
//# sourceMappingURL=settle.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"settle.js","sourceRoot":"","sources":["../src/settle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,gGAAgG;AAChG,MAAM,CAAC,MAAM,aAAa,GAAG,gBAAgB,CAAC;AAE9C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAoB,CAAC;AAC5C,IAAI,SAAS,GAAG,KAAK,CAAC;AAEtB,+FAA+F;AAC/F,MAAM,UAAU,YAAY,CAAC,OAA6B;IACxD,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IACzC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACrB,MAAM,IAAI,GAAG,GAAG,EAAE;QAChB,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAC1B,CAAC,CAAC;IACF,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAC3B,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,eAAe,CAAI,OAAmB,EAAE,SAAkC,UAAU,CAAC,MAAM;IACzG,MAAM,EAAE,aAAa,CAAC,IAAI,WAAW,CAAC,aAAa,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;IAC3E,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,SAAkC,UAAU,CAAC,MAAM;IAClF,IAAI,CAAC,MAAM,IAAI,SAAS;QAAE,OAAO,GAAG,EAAE,CAAC,SAAS,CAAC;IACjD,SAAS,GAAG,IAAI,CAAC;IACjB,MAAM,SAAS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AAI,MAAM,IAAI,OAAQ,MAA+B,CAAC,IAAI,KAAK,UAAU;oBAAE,MAAM,MAAM,CAAC;gBACxF,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACxB,CAAC;YAAC,MAAM,CAAC;gBACP,SAAS;YACX,CAAC;QACH,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC,EAAE,CAAC;IACL,YAAY,CAAC,GAAG,CAAC,CAAC;IAClB,OAAO,eAAe,CAAC,GAAG,CAAC,CAAC;AAC9B,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "webmcp-settle",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Wait for a page's WebMCP tools to finish registering, and navigate single-page apps without answering early.",
|
|
5
|
+
"keywords": ["webmcp", "mcp", "model-context", "ai-agents", "navigator.modelContext", "browser-agents"],
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Craft Quantities (https://craftquantities.com)",
|
|
8
|
+
"homepage": "https://github.com/Axelima/webmcp-settle#readme",
|
|
9
|
+
"repository": { "type": "git", "url": "git+https://github.com/Axelima/webmcp-settle.git" },
|
|
10
|
+
"bugs": { "url": "https://github.com/Axelima/webmcp-settle/issues" },
|
|
11
|
+
"type": "module",
|
|
12
|
+
"main": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } },
|
|
15
|
+
"files": ["dist", "probe", "README.md", "LICENSE"],
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc -p tsconfig.build.json",
|
|
19
|
+
"test": "vitest run",
|
|
20
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
21
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"jsdom": "^26.1.0",
|
|
25
|
+
"typescript": "^5.8.3",
|
|
26
|
+
"vitest": "^3.2.4"
|
|
27
|
+
},
|
|
28
|
+
"engines": { "node": ">=20" }
|
|
29
|
+
}
|
package/probe/README.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# webmcp-timing-probe
|
|
2
|
+
|
|
3
|
+
A command-line tool that measures **when** a site's WebMCP tools register. It works on any site.
|
|
4
|
+
|
|
5
|
+
Many sites register their tools in waves: some at the load event, more after hydration, more once lazy-loaded code arrives. An agent that lists tools at load can see only part of the set. So can an agent that calls a site's "open page" tool and lists tools as soon as that call returns. This is the late-registration race discussed in [webmachinelearning/webmcp#402](https://github.com/webmachinelearning/webmcp/issues/402). The probe measures it on real pages.
|
|
6
|
+
|
|
7
|
+
## How it works
|
|
8
|
+
|
|
9
|
+
The probe adds a script that runs before any page script. That script wraps `document.modelContext.registerTool` (and `provideContext`, if the page has it) and records the time of every registration. For each page and run, the probe reports:
|
|
10
|
+
|
|
11
|
+
- how many tools existed at the load event
|
|
12
|
+
- the final tool count
|
|
13
|
+
- the registration waves (a new wave starts after a gap of more than 100 ms)
|
|
14
|
+
- when the tool set settled (no new registration for 3 s, giving up after 20 s)
|
|
15
|
+
|
|
16
|
+
Two measurements are optional:
|
|
17
|
+
|
|
18
|
+
- **Navigation race.** The probe calls the site's own navigation tool. It then compares the title the tool returned with `document.title` once the page has settled. It also counts the **late tools**: tools of the new page that registered after the call returned. 0 late tools means the navigation tool waited for the new page's tools.
|
|
19
|
+
- **Read-only call timing.** The probe calls tools marked `readOnlyHint` that need no input. It times call → `toolactivated` → resolve and records the Event Timing and Long Animation Frame (LoAF) entries inside that window.
|
|
20
|
+
|
|
21
|
+
**Read-only by default.** The probe calls no tools unless you ask. Then it calls only tools marked `readOnlyHint` that need no input, plus the one navigation tool you name. It sends no telemetry. Sitemap requests use the user-agent `webmcp-timing-probe`.
|
|
22
|
+
|
|
23
|
+
## Requirements
|
|
24
|
+
|
|
25
|
+
- Node 20 or later
|
|
26
|
+
- Playwright: the `playwright` or `@playwright/test` package, in the current directory or in the folder you pass with `--playwright`
|
|
27
|
+
- Google Chrome with WebMCP support, installed. The probe launches it as channel `chrome` with `--enable-features=WebMCPTesting,WebMCP --enable-blink-features=WebMCP,WebMCPTesting`.
|
|
28
|
+
|
|
29
|
+
## Usage
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
node probe/webmcp-timing-probe.mjs --url https://example.com/ --url https://example.com/docs/ --runs 3
|
|
33
|
+
node probe/webmcp-timing-probe.mjs --sitemap https://example.com/sitemap.xml --max 30
|
|
34
|
+
node probe/webmcp-timing-probe.mjs --url https://example.com/a/ \
|
|
35
|
+
--navigate-tool open_page --navigate-arg-json '{"path":"/b/"}'
|
|
36
|
+
node probe/webmcp-timing-probe.mjs --navigate-tool open_page --follow https://example.com/a/ https://example.com/b/
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
| Flag | Meaning |
|
|
40
|
+
|---|---|
|
|
41
|
+
| `--url <u>` | Page to probe. You can repeat it. |
|
|
42
|
+
| `--urls-file <file>` | File with one URL per line. Lines starting with `#` are ignored. |
|
|
43
|
+
| `--sitemap <url>` | Sitemap or sitemap index. Pages are sampled evenly up to `--max`. |
|
|
44
|
+
| `--max <n>` | Most pages to take from the sitemap (default 20). |
|
|
45
|
+
| `--runs <n>` | Runs per page, each in a fresh browser context (default 1). |
|
|
46
|
+
| `--quiet-ms <ms>` | Gap with no new registration that counts as settled (default 3000). |
|
|
47
|
+
| `--settle-timeout-ms <ms>` | Longest wait for the set to settle (default 20000). |
|
|
48
|
+
| `--wave-gap-ms <ms>` | Gap that starts a new wave (default 100). |
|
|
49
|
+
| `--navigate-tool <name>` | The site's navigation tool. This is the only tool without `readOnlyHint` the probe will call. |
|
|
50
|
+
| `--navigate-arg-json <json>` | Arguments for the navigation tool. `{path}` and `{url}` are replaced with the target's path and URL. |
|
|
51
|
+
| `--follow <from> <to>` | Run the navigation race from `<from>` to `<to>`. You can repeat it. The default arguments are `{"path":"{path}"}`. |
|
|
52
|
+
| `--call-readonly` | Also time calls to read-only tools that need no input. |
|
|
53
|
+
| `--call-max <n>` | Most read-only tools to call per page (default 3). |
|
|
54
|
+
| `--headed` | Show the browser window. |
|
|
55
|
+
| `--out <dir>` | Output folder (default `./webmcp-timing-out`). |
|
|
56
|
+
| `--playwright <dir>` | Folder whose `node_modules` contains Playwright (default: the current directory). |
|
|
57
|
+
|
|
58
|
+
If a page does not register the navigation tool, the navigation race is skipped for that page and the report says so.
|
|
59
|
+
|
|
60
|
+
## Output
|
|
61
|
+
|
|
62
|
+
The probe writes two files to `--out`:
|
|
63
|
+
|
|
64
|
+
- `results.json`: the raw runs, including every registration with its time, plus medians for each page.
|
|
65
|
+
- `summary.md`: the tables below. Medians are taken across runs. Times are in ms from the start of navigation.
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
| Page | Tools at load | Final tools | Waves | First wave (tools @ ms) | Load | Last registration | Settle after load | Unsettled runs |
|
|
69
|
+
|---|---:|---:|---:|---:|---:|---:|---:|---:|
|
|
70
|
+
| example.com/calc/ | 0 | 19 | 2 | 8 @ 712.3 | 615.9 | 1170.2 | 554.3 | 0 |
|
|
71
|
+
|
|
72
|
+
## Navigation race (open_page)
|
|
73
|
+
| From | Target / args | Run | Tool ms | Returned title | Final title | Title matches | New page tools | Late tools | Settled after call |
|
|
74
|
+
|---|---|---:|---:|---|---|---|---:|---:|---:|
|
|
75
|
+
| example.com/calc/ | {"path":"/tile/"} | 1 | 980.6 | Tile Calculator | Tile Calculator | yes | 11 | 0 | 963.5 |
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
If you pass `--call-readonly`, a third table lists each read-only call: call time, time to `toolactivated`, Event Timing entries and LoAF entries.
|
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* webmcp-timing-probe — measure WHEN a site's WebMCP tools register, and whether a navigation tool returns before the
|
|
4
|
+
* next page's tools exist.
|
|
5
|
+
*
|
|
6
|
+
* WHY
|
|
7
|
+
* WebMCP tools are registered by page scripts (document.modelContext.registerTool). Many sites register them in
|
|
8
|
+
* several waves: a few at load, more after hydration, more after lazy chunks arrive. An agent that lists tools at the
|
|
9
|
+
* load event, or that calls a site's own "open page" tool and lists tools as soon as it resolves, can see a partial
|
|
10
|
+
* set. This is the late-registration race discussed in webmachinelearning/webmcp#402. The probe measures it on real
|
|
11
|
+
* pages so sites (and the spec discussion) can work from numbers:
|
|
12
|
+
*
|
|
13
|
+
* 1. Registration waves: an init script wraps document.modelContext.registerTool (and provideContext, if present)
|
|
14
|
+
* before any page script runs and timestamps every registration. Reported per page: tools present at the load
|
|
15
|
+
* event, final tool count, waves (clusters separated by more than --wave-gap-ms), and when the set settled (no
|
|
16
|
+
* registration for --quiet-ms, capped at --settle-timeout-ms).
|
|
17
|
+
* 2. Navigation race (optional): call the site's own navigation tool, then compare the title it returned with
|
|
18
|
+
* document.title once the page has settled, and count the new page's tools that registered AFTER the tool call
|
|
19
|
+
* resolved ("late tools"). Zero late tools means the tool waited for the next page's registrations.
|
|
20
|
+
* 3. Read-only call timing (optional, --call-readonly): call tools annotated readOnlyHint that need no input, timing
|
|
21
|
+
* call -> toolactivated -> resolve, with Event Timing and Long Animation Frame entries inside the call window.
|
|
22
|
+
*
|
|
23
|
+
* SAFETY
|
|
24
|
+
* Read-only by default: it opens pages and records registrations. It never calls a tool unless asked, and then only
|
|
25
|
+
* tools annotated readOnlyHint with no required inputs (--call-readonly) or the one navigation tool you name
|
|
26
|
+
* (--navigate-tool). No telemetry; HTTP fetches (sitemaps) use the user-agent "webmcp-timing-probe".
|
|
27
|
+
*
|
|
28
|
+
* REQUIREMENTS
|
|
29
|
+
* - Node 18+.
|
|
30
|
+
* - Playwright (the "playwright" or "@playwright/test" package) installed in the current directory or in the
|
|
31
|
+
* directory given by --playwright.
|
|
32
|
+
* - An installed Google Chrome with native WebMCP (Chrome 158+). It is launched as channel "chrome" with
|
|
33
|
+
* --enable-features=WebMCPTesting,WebMCP --enable-blink-features=WebMCP,WebMCPTesting.
|
|
34
|
+
*
|
|
35
|
+
* USAGE
|
|
36
|
+
* node webmcp-timing-probe.mjs --url https://example.com/ --url https://example.com/docs/ --runs 3
|
|
37
|
+
* node webmcp-timing-probe.mjs --urls-file pages.txt --out ./timing
|
|
38
|
+
* node webmcp-timing-probe.mjs --sitemap https://example.com/sitemap.xml --max 30 --runs 2
|
|
39
|
+
* node webmcp-timing-probe.mjs --url https://craftquantities.com/ \
|
|
40
|
+
* --navigate-tool open_page --navigate-arg-json '{"path":"/build/"}'
|
|
41
|
+
* node webmcp-timing-probe.mjs --navigate-tool open_page --follow https://example.com/a/ https://example.com/b/
|
|
42
|
+
* node webmcp-timing-probe.mjs --url https://example.com/ --call-readonly --playwright ../some-project
|
|
43
|
+
*
|
|
44
|
+
* OPTIONS
|
|
45
|
+
* --url <u> page to probe (repeatable)
|
|
46
|
+
* --urls-file <file> file with one URL per line (# comments allowed)
|
|
47
|
+
* --sitemap <url> sitemap or sitemap index; pages are sampled evenly up to --max (default 20)
|
|
48
|
+
* --max <n> cap for sitemap pages (default 20)
|
|
49
|
+
* --runs <n> runs per page, each in a fresh browser context (default 1)
|
|
50
|
+
* --quiet-ms <ms> settled after this long without a registration (default 3000)
|
|
51
|
+
* --settle-timeout-ms <ms> give up waiting for settle after this (default 20000)
|
|
52
|
+
* --wave-gap-ms <ms> registrations further apart than this start a new wave (default 100)
|
|
53
|
+
* --navigate-tool <name> the site's navigation tool (only this non-read-only tool is ever called)
|
|
54
|
+
* --navigate-arg-json <j> arguments for it; "{path}" and "{url}" are replaced with the target's path / URL
|
|
55
|
+
* (default with --follow: {"path":"{path}"})
|
|
56
|
+
* --follow <from> <to> navigation race from page <from> to <to> (repeatable); without --follow the race runs
|
|
57
|
+
* on every probed page with --navigate-arg-json as given
|
|
58
|
+
* --call-readonly also time calls of readOnlyHint tools with no required inputs
|
|
59
|
+
* --call-max <n> at most this many read-only tools per page (default 3)
|
|
60
|
+
* --headed show the browser
|
|
61
|
+
* --out <dir> output directory (default ./webmcp-timing-out): results.json, summary.md
|
|
62
|
+
* --playwright <dir> directory whose node_modules holds playwright or @playwright/test (default: cwd)
|
|
63
|
+
*/
|
|
64
|
+
import fs from "node:fs";
|
|
65
|
+
import path from "node:path";
|
|
66
|
+
import { createRequire } from "node:module";
|
|
67
|
+
|
|
68
|
+
/* ---------------------------------------------------------------- arguments */
|
|
69
|
+
const argv = process.argv.slice(2);
|
|
70
|
+
const opts = { url: [], follow: [] };
|
|
71
|
+
const FLAGS = new Set(["call-readonly", "headed", "help"]);
|
|
72
|
+
for (let i = 0; i < argv.length; i++) {
|
|
73
|
+
const a = argv[i];
|
|
74
|
+
if (!a.startsWith("--")) die(`unexpected argument: ${a}`);
|
|
75
|
+
const name = a.slice(2);
|
|
76
|
+
if (FLAGS.has(name)) { opts[name] = true; continue; }
|
|
77
|
+
if (name === "follow") {
|
|
78
|
+
const from = argv[++i], to = argv[++i];
|
|
79
|
+
if (!from || !to) die("--follow needs two URLs: --follow <from> <to>");
|
|
80
|
+
opts.follow.push({ from, to });
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const v = argv[++i];
|
|
84
|
+
if (v === undefined) die(`--${name} needs a value`);
|
|
85
|
+
if (name === "url") opts.url.push(v);
|
|
86
|
+
else opts[name] = v;
|
|
87
|
+
}
|
|
88
|
+
if (opts.help) {
|
|
89
|
+
const src = fs.readFileSync(new URL(import.meta.url), "utf8");
|
|
90
|
+
console.log(src.slice(src.indexOf("/**") + 3, src.indexOf("*/")).replace(/^ \* ?/gm, ""));
|
|
91
|
+
process.exit(0);
|
|
92
|
+
}
|
|
93
|
+
function die(msg) {
|
|
94
|
+
console.error(`webmcp-timing-probe: ${msg}\nRun with --help for usage.`);
|
|
95
|
+
process.exit(2);
|
|
96
|
+
}
|
|
97
|
+
const num = (name, fallback) => {
|
|
98
|
+
const v = opts[name] === undefined ? fallback : Number(opts[name]);
|
|
99
|
+
if (!Number.isFinite(v) || v < 0) die(`--${name} must be a non-negative number`);
|
|
100
|
+
return v;
|
|
101
|
+
};
|
|
102
|
+
const RUNS = Math.max(1, num("runs", 1));
|
|
103
|
+
const MAX = Math.max(1, num("max", 20));
|
|
104
|
+
const QUIET_MS = num("quiet-ms", 3000);
|
|
105
|
+
const SETTLE_TIMEOUT_MS = num("settle-timeout-ms", 20_000);
|
|
106
|
+
const WAVE_GAP_MS = num("wave-gap-ms", 100);
|
|
107
|
+
const CALL_MAX = num("call-max", 3);
|
|
108
|
+
const NAV_TOOL = opts["navigate-tool"] ?? null;
|
|
109
|
+
const NAV_ARG_TEMPLATE = opts["navigate-arg-json"] ?? (opts.follow.length ? '{"path":"{path}"}' : null);
|
|
110
|
+
if (NAV_ARG_TEMPLATE) {
|
|
111
|
+
try { JSON.parse(NAV_ARG_TEMPLATE.replaceAll("{path}", "x").replaceAll("{url}", "x")); }
|
|
112
|
+
catch (e) { die(`--navigate-arg-json is not valid JSON: ${e.message}`); }
|
|
113
|
+
}
|
|
114
|
+
if (opts.follow.length && !NAV_TOOL) die("--follow needs --navigate-tool");
|
|
115
|
+
if (NAV_TOOL && !NAV_ARG_TEMPLATE) die("--navigate-tool needs --navigate-arg-json (or --follow)");
|
|
116
|
+
const OUT = path.resolve(opts.out ?? "webmcp-timing-out");
|
|
117
|
+
const UA = "webmcp-timing-probe";
|
|
118
|
+
|
|
119
|
+
/* ---------------------------------------------------------------- playwright */
|
|
120
|
+
function loadChromium() {
|
|
121
|
+
const dir = path.resolve(opts.playwright ?? process.cwd());
|
|
122
|
+
const req = createRequire(path.join(dir, "package.json"));
|
|
123
|
+
for (const pkg of ["playwright", "@playwright/test"]) {
|
|
124
|
+
try { return req(pkg).chromium; } catch {}
|
|
125
|
+
}
|
|
126
|
+
die(`cannot find Playwright from ${dir}.\n Install it there (npm i -D playwright) or pass --playwright <dir> whose node_modules has playwright or @playwright/test.`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/* ---------------------------------------------------------------- pages */
|
|
130
|
+
async function fetchText(url) {
|
|
131
|
+
const r = await fetch(url, { headers: { "user-agent": UA } });
|
|
132
|
+
if (!r.ok) throw new Error(`${url}: HTTP ${r.status}`);
|
|
133
|
+
return r.text();
|
|
134
|
+
}
|
|
135
|
+
async function sitemapUrls(url, depth = 0) {
|
|
136
|
+
const xml = await fetchText(url);
|
|
137
|
+
const locs = [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replaceAll("&", "&"));
|
|
138
|
+
if (/<sitemapindex[\s>]/.test(xml) && depth < 3) {
|
|
139
|
+
const out = [];
|
|
140
|
+
for (const m of locs) {
|
|
141
|
+
try { out.push(...(await sitemapUrls(m, depth + 1))); } catch (e) { console.warn(` skip sitemap ${m}: ${e.message}`); }
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
return locs;
|
|
146
|
+
}
|
|
147
|
+
const sampleEvenly = (xs, n) => (xs.length <= n ? xs : Array.from({ length: n }, (_, i) => xs[Math.floor((i * xs.length) / n)]));
|
|
148
|
+
|
|
149
|
+
async function pickPages() {
|
|
150
|
+
const pages = [...opts.url];
|
|
151
|
+
if (opts["urls-file"]) {
|
|
152
|
+
const lines = fs.readFileSync(opts["urls-file"], "utf8").split(/\r?\n/).map((l) => l.trim());
|
|
153
|
+
pages.push(...lines.filter((l) => l && !l.startsWith("#")));
|
|
154
|
+
}
|
|
155
|
+
if (opts.sitemap) {
|
|
156
|
+
const all = [...new Set(await sitemapUrls(opts.sitemap))];
|
|
157
|
+
console.log(`sitemap: ${all.length} URLs, sampling ${Math.min(all.length, MAX)}`);
|
|
158
|
+
pages.push(...sampleEvenly(all, MAX));
|
|
159
|
+
}
|
|
160
|
+
for (const u of pages) {
|
|
161
|
+
try { new URL(u); } catch { die(`not an absolute URL: ${u}`); }
|
|
162
|
+
}
|
|
163
|
+
return [...new Set(pages)];
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/* ---------------------------------------------------------------- the in-page recorder (runs before any script) */
|
|
167
|
+
const INIT = () => {
|
|
168
|
+
if (window.__webmcpProbe) return;
|
|
169
|
+
const rec = (window.__webmcpProbe = { regs: [], events: [], loaf: [], et: [], ctx: false });
|
|
170
|
+
const t = () => performance.now();
|
|
171
|
+
try {
|
|
172
|
+
new PerformanceObserver((l) => { for (const e of l.getEntries()) rec.loaf.push({ start: e.startTime, duration: e.duration, blocking: e.blockingDuration ?? 0 }); })
|
|
173
|
+
.observe({ type: "long-animation-frame", buffered: true });
|
|
174
|
+
} catch {}
|
|
175
|
+
try {
|
|
176
|
+
new PerformanceObserver((l) => { for (const e of l.getEntries()) rec.et.push({ name: e.name, start: e.startTime, duration: e.duration }); })
|
|
177
|
+
.observe({ type: "event", buffered: true, durationThreshold: 16 });
|
|
178
|
+
} catch {}
|
|
179
|
+
const note = (tool, via) => rec.regs.push({
|
|
180
|
+
name: tool?.name,
|
|
181
|
+
t: t(),
|
|
182
|
+
via,
|
|
183
|
+
readOnly: tool?.annotations?.readOnlyHint === true,
|
|
184
|
+
required: (() => { try { const s = typeof tool?.inputSchema === "string" ? JSON.parse(tool.inputSchema) : tool?.inputSchema; return (s?.required ?? []).length; } catch { return -1; } })(),
|
|
185
|
+
});
|
|
186
|
+
const wrap = (ctx) => {
|
|
187
|
+
if (!ctx || ctx.__webmcpProbeWrapped) return;
|
|
188
|
+
ctx.__webmcpProbeWrapped = true;
|
|
189
|
+
rec.ctx = true;
|
|
190
|
+
const reg = ctx.registerTool;
|
|
191
|
+
if (typeof reg === "function") {
|
|
192
|
+
ctx.registerTool = function (tool, options) { note(tool, "registerTool"); return reg.call(this, tool, options); };
|
|
193
|
+
}
|
|
194
|
+
const provide = ctx.provideContext;
|
|
195
|
+
if (typeof provide === "function") {
|
|
196
|
+
ctx.provideContext = function (context, ...rest) {
|
|
197
|
+
for (const tool of context?.tools ?? []) note(tool, "provideContext");
|
|
198
|
+
return provide.call(this, context, ...rest);
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
for (const type of ["toolactivated", "toolcancel"]) {
|
|
202
|
+
try { ctx.addEventListener(type, (e) => rec.events.push({ type, tool: e.toolName, t: t(), on: "modelContext" })); } catch {}
|
|
203
|
+
window.addEventListener(type, (e) => rec.events.push({ type, tool: e.toolName, t: t(), on: "window" }));
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
wrap(document.modelContext ?? navigator.modelContext);
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
/* ---------------------------------------------------------------- helpers */
|
|
210
|
+
const round = (n) => (n == null || !Number.isFinite(n) ? null : Math.round(n * 10) / 10);
|
|
211
|
+
|
|
212
|
+
/** Waits until no tool has registered (after sinceT) for QUIET_MS, or SETTLE_TIMEOUT_MS passes. */
|
|
213
|
+
async function waitSettled(page, sinceT = 0) {
|
|
214
|
+
const started = Date.now();
|
|
215
|
+
for (;;) {
|
|
216
|
+
const s = await page.evaluate(() => ({ now: performance.now(), regs: window.__webmcpProbe?.regs ?? [] }));
|
|
217
|
+
const after = s.regs.filter((r) => r.t >= sinceT);
|
|
218
|
+
const last = after.length ? after[after.length - 1].t : null;
|
|
219
|
+
if (s.now - (last ?? sinceT) >= QUIET_MS) return { settled: true, last };
|
|
220
|
+
if (Date.now() - started > SETTLE_TIMEOUT_MS) return { settled: false, last };
|
|
221
|
+
await page.waitForTimeout(100);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function waves(regs) {
|
|
226
|
+
const out = [];
|
|
227
|
+
for (const r of regs) {
|
|
228
|
+
const w = out[out.length - 1];
|
|
229
|
+
if (w && r.t - w.end <= WAVE_GAP_MS) { w.end = r.t; w.count++; }
|
|
230
|
+
else out.push({ start: r.t, end: r.t, count: 1 });
|
|
231
|
+
}
|
|
232
|
+
return out.map((w) => ({ at: round(w.start), until: round(w.end), tools: w.count }));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Calls one tool through the native surface, with its lifecycle measured in the page. */
|
|
236
|
+
async function callTool(page, name, args) {
|
|
237
|
+
return page.evaluate(async ({ name, args }) => {
|
|
238
|
+
const rec = window.__webmcpProbe;
|
|
239
|
+
const ctx = document.modelContext ?? navigator.modelContext;
|
|
240
|
+
const testing = navigator.modelContextTesting;
|
|
241
|
+
const list = (await (ctx?.getTools?.() ?? testing?.listTools?.() ?? [])) || [];
|
|
242
|
+
const tool = list.find((x) => x.name === name);
|
|
243
|
+
if (!tool) return { error: `no tool ${name} (${list.length} listed)` };
|
|
244
|
+
const evBefore = rec.events.length;
|
|
245
|
+
const t0 = performance.now();
|
|
246
|
+
let result, error;
|
|
247
|
+
try {
|
|
248
|
+
if (ctx?.executeTool) result = await ctx.executeTool(tool, args);
|
|
249
|
+
else if (testing?.executeTool) result = await testing.executeTool(name, JSON.stringify(args));
|
|
250
|
+
else error = "no executeTool on document.modelContext or navigator.modelContextTesting";
|
|
251
|
+
} catch (e) { error = String(e?.message ?? e); }
|
|
252
|
+
const t1 = performance.now();
|
|
253
|
+
await new Promise((r) => setTimeout(r, 300)); // let the observers deliver
|
|
254
|
+
const activated = rec.events.slice(evBefore).filter((e) => e.type === "toolactivated");
|
|
255
|
+
const loaf = rec.loaf.filter((f) => f.start + f.duration >= t0 && f.start <= t1);
|
|
256
|
+
let text;
|
|
257
|
+
try { text = typeof result === "string" ? result : JSON.stringify(result); } catch { text = String(result); }
|
|
258
|
+
return {
|
|
259
|
+
t0, t1,
|
|
260
|
+
ms: t1 - t0,
|
|
261
|
+
activatedAfter: activated.length ? activated[0].t - t0 : null,
|
|
262
|
+
activatedBeforeResolve: activated.length ? t1 - activated[0].t : null,
|
|
263
|
+
activatedOn: activated.map((a) => a.on),
|
|
264
|
+
eventTimingEntries: rec.et.filter((e) => e.start >= t0 && e.start <= t1).length,
|
|
265
|
+
loafCount: loaf.length,
|
|
266
|
+
loafMax: loaf.reduce((m, f) => Math.max(m, f.duration), 0),
|
|
267
|
+
loafBlocking: loaf.reduce((s, f) => s + f.blocking, 0),
|
|
268
|
+
error,
|
|
269
|
+
text: text ?? "",
|
|
270
|
+
};
|
|
271
|
+
}, { name, args });
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Best-effort title from a tool result: a "title" field anywhere in JSON, else "Opened: X", else a heading. */
|
|
275
|
+
function titleFromResult(text) {
|
|
276
|
+
const find = (v, depth = 0) => {
|
|
277
|
+
if (depth > 6 || v == null) return null;
|
|
278
|
+
if (typeof v === "string") {
|
|
279
|
+
if (/^\s*[[{]/.test(v)) { try { return find(JSON.parse(v), depth + 1); } catch {} }
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
if (Array.isArray(v)) { for (const x of v) { const r = find(x, depth + 1); if (r) return r; } return null; }
|
|
283
|
+
if (typeof v === "object") {
|
|
284
|
+
if (typeof v.title === "string" && v.title.trim()) return v.title.trim();
|
|
285
|
+
for (const x of Object.values(v)) { const r = find(x, depth + 1); if (r) return r; }
|
|
286
|
+
}
|
|
287
|
+
return null;
|
|
288
|
+
};
|
|
289
|
+
let parsed = null;
|
|
290
|
+
try { parsed = JSON.parse(text); } catch {}
|
|
291
|
+
const fromJson = find(parsed);
|
|
292
|
+
if (fromJson) return fromJson;
|
|
293
|
+
const flat = typeof parsed === "string" ? parsed : text.replace(/\\n/g, "\n");
|
|
294
|
+
return (flat.match(/Opened:?\s+["“]?([^\n"”\\]+)/) ?? flat.match(/^#{1,3}\s+(.+)$/m) ?? [])[1]?.trim() ?? null;
|
|
295
|
+
}
|
|
296
|
+
const normTitle = (s) => (s ?? "").replace(/\s+/g, " ").trim().toLowerCase();
|
|
297
|
+
|
|
298
|
+
function navArgs(target) {
|
|
299
|
+
const u = new URL(target);
|
|
300
|
+
const json = NAV_ARG_TEMPLATE.replaceAll("{path}", u.pathname + u.search + u.hash).replaceAll("{url}", u.href);
|
|
301
|
+
return JSON.parse(json);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/* ---------------------------------------------------------------- one run of one page */
|
|
305
|
+
async function runPage(browser, url, run, navTarget) {
|
|
306
|
+
const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
|
|
307
|
+
await context.addInitScript(INIT);
|
|
308
|
+
const page = await context.newPage();
|
|
309
|
+
const out = { url, run };
|
|
310
|
+
try {
|
|
311
|
+
await page.goto(url, { waitUntil: "load", timeout: 45_000 });
|
|
312
|
+
const s = await waitSettled(page);
|
|
313
|
+
const data = await page.evaluate(() => {
|
|
314
|
+
const nav = performance.getEntriesByType("navigation")[0];
|
|
315
|
+
const fcp = performance.getEntriesByName("first-contentful-paint")[0];
|
|
316
|
+
const p = window.__webmcpProbe;
|
|
317
|
+
return { regs: p?.regs ?? [], ctx: !!p?.ctx, load: nav?.loadEventEnd ?? null, dcl: nav?.domContentLoadedEventEnd ?? null, fcp: fcp?.startTime ?? null, loaf: p?.loaf ?? [], title: document.title };
|
|
318
|
+
});
|
|
319
|
+
out.title = data.title;
|
|
320
|
+
out.nativeContext = data.ctx;
|
|
321
|
+
out.load = round(data.load);
|
|
322
|
+
out.dcl = round(data.dcl);
|
|
323
|
+
out.fcp = round(data.fcp);
|
|
324
|
+
out.settled = s.settled;
|
|
325
|
+
out.tools = data.regs.length;
|
|
326
|
+
out.toolNames = data.regs.map((r) => r.name);
|
|
327
|
+
out.toolsAtLoad = data.regs.filter((r) => r.t <= data.load).length;
|
|
328
|
+
out.firstRegistration = round(data.regs[0]?.t);
|
|
329
|
+
out.lastRegistration = round(s.last);
|
|
330
|
+
out.settleAfterLoad = s.last == null ? null : round(Math.max(0, s.last - data.load));
|
|
331
|
+
out.waves = waves(data.regs);
|
|
332
|
+
out.registrations = data.regs.map((r) => ({ name: r.name, t: round(r.t), via: r.via, readOnly: r.readOnly }));
|
|
333
|
+
const upTo = s.last ?? data.load;
|
|
334
|
+
out.loadLoafMax = round(data.loaf.filter((f) => f.start <= upTo).reduce((m, f) => Math.max(m, f.duration), 0));
|
|
335
|
+
out.loadLoafCount = data.loaf.filter((f) => f.start <= upTo).length;
|
|
336
|
+
|
|
337
|
+
if (opts["call-readonly"] && data.ctx) {
|
|
338
|
+
out.calls = {};
|
|
339
|
+
const seen = new Set();
|
|
340
|
+
const candidates = data.regs.filter((r) => r.readOnly && r.required === 0 && r.name && r.name !== NAV_TOOL && !seen.has(r.name) && seen.add(r.name));
|
|
341
|
+
for (const r of candidates.slice(0, CALL_MAX)) {
|
|
342
|
+
const c = await callTool(page, r.name, {});
|
|
343
|
+
delete c.t0; delete c.t1;
|
|
344
|
+
c.text = c.text.slice(0, 300);
|
|
345
|
+
for (const k of ["ms", "activatedAfter", "activatedBeforeResolve", "loafMax", "loafBlocking"]) c[k] = round(c[k]);
|
|
346
|
+
out.calls[r.name] = c;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
if (navTarget && NAV_TOOL) {
|
|
351
|
+
const hasTool = data.regs.some((r) => r.name === NAV_TOOL);
|
|
352
|
+
if (!hasTool) {
|
|
353
|
+
out.navigation = { skipped: `the page did not register ${NAV_TOOL}` };
|
|
354
|
+
} else {
|
|
355
|
+
const args = navArgs(navTarget);
|
|
356
|
+
const before = await page.evaluate(() => performance.now());
|
|
357
|
+
let r, crossDocument = false;
|
|
358
|
+
try {
|
|
359
|
+
r = await callTool(page, NAV_TOOL, args);
|
|
360
|
+
} catch (e) {
|
|
361
|
+
// a cross-document navigation destroys the page that made the call: the tool's answer is lost
|
|
362
|
+
crossDocument = true;
|
|
363
|
+
r = { error: String(e?.message ?? e).split("\n")[0], text: "", ms: null, t1: null };
|
|
364
|
+
await page.waitForLoadState("load", { timeout: 45_000 }).catch(() => {});
|
|
365
|
+
}
|
|
366
|
+
if (!crossDocument && r.error?.startsWith("no tool")) {
|
|
367
|
+
out.navigation = { skipped: r.error };
|
|
368
|
+
} else {
|
|
369
|
+
const s2 = await waitSettled(page, crossDocument ? 0 : before + 0.001);
|
|
370
|
+
const after = await page.evaluate((since) => ({
|
|
371
|
+
title: document.title,
|
|
372
|
+
href: location.href,
|
|
373
|
+
regs: (window.__webmcpProbe?.regs ?? []).filter((x) => x.t > since),
|
|
374
|
+
}), crossDocument ? -1 : before);
|
|
375
|
+
const returnedTitle = r.text ? titleFromResult(r.text) : null;
|
|
376
|
+
const a = normTitle(returnedTitle), b = normTitle(after.title);
|
|
377
|
+
out.navigation = {
|
|
378
|
+
target: opts.follow.length ? navTarget : null,
|
|
379
|
+
args,
|
|
380
|
+
crossDocument,
|
|
381
|
+
toolMs: round(r.ms),
|
|
382
|
+
error: r.error ?? null,
|
|
383
|
+
returnedTitle,
|
|
384
|
+
finalTitle: after.title,
|
|
385
|
+
titleMatches: returnedTitle ? (a === b || b.startsWith(a) || a.startsWith(b)) : null,
|
|
386
|
+
arrivedAt: after.href,
|
|
387
|
+
newPageTools: after.regs.length,
|
|
388
|
+
settled: s2.settled,
|
|
389
|
+
newToolsSettledAfterCall: crossDocument || s2.last == null ? null : round(s2.last - before),
|
|
390
|
+
lateTools: crossDocument || r.t1 == null ? null : after.regs.filter((x) => x.t > r.t1).length,
|
|
391
|
+
lateToolNames: crossDocument || r.t1 == null ? [] : after.regs.filter((x) => x.t > r.t1).map((x) => x.name),
|
|
392
|
+
resultExcerpt: r.text.slice(0, 300),
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
} catch (e) {
|
|
398
|
+
out.error = String(e?.message ?? e).split("\n")[0];
|
|
399
|
+
} finally {
|
|
400
|
+
await context.close();
|
|
401
|
+
}
|
|
402
|
+
return out;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/* ---------------------------------------------------------------- main */
|
|
406
|
+
const median = (xs) => {
|
|
407
|
+
const v = xs.filter((x) => typeof x === "number").sort((a, b) => a - b);
|
|
408
|
+
return v.length ? v[Math.floor((v.length - 1) / 2)] : null;
|
|
409
|
+
};
|
|
410
|
+
|
|
411
|
+
const pages = await pickPages();
|
|
412
|
+
const jobs = [];
|
|
413
|
+
if (opts.follow.length) {
|
|
414
|
+
for (const u of pages) jobs.push({ url: u, nav: null });
|
|
415
|
+
for (const f of opts.follow) jobs.push({ url: f.from, nav: f.to });
|
|
416
|
+
} else {
|
|
417
|
+
for (const u of pages) jobs.push({ url: u, nav: NAV_TOOL ? u : null });
|
|
418
|
+
}
|
|
419
|
+
if (!jobs.length) die("no pages: give --url, --urls-file, --sitemap or --follow");
|
|
420
|
+
|
|
421
|
+
const chromium = loadChromium();
|
|
422
|
+
fs.mkdirSync(OUT, { recursive: true });
|
|
423
|
+
let browser;
|
|
424
|
+
try {
|
|
425
|
+
browser = await chromium.launch({
|
|
426
|
+
channel: "chrome",
|
|
427
|
+
headless: !opts.headed,
|
|
428
|
+
args: ["--enable-features=WebMCPTesting,WebMCP", "--enable-blink-features=WebMCP,WebMCPTesting"],
|
|
429
|
+
});
|
|
430
|
+
} catch (e) {
|
|
431
|
+
die(`cannot launch installed Chrome (channel "chrome"): ${String(e?.message ?? e).split("\n")[0]}\n Install Google Chrome 158+ (native WebMCP).`);
|
|
432
|
+
}
|
|
433
|
+
const chromeVersion = browser.version();
|
|
434
|
+
console.log(`Chrome ${chromeVersion}; ${jobs.length} page(s) x ${RUNS} run(s); quiet ${QUIET_MS} ms, cap ${SETTLE_TIMEOUT_MS} ms${NAV_TOOL ? `; navigation tool ${NAV_TOOL}` : ""}${opts["call-readonly"] ? "; read-only calls on" : ""}`);
|
|
435
|
+
|
|
436
|
+
const results = [];
|
|
437
|
+
for (const [i, job] of jobs.entries()) {
|
|
438
|
+
for (let run = 1; run <= RUNS; run++) {
|
|
439
|
+
const label = `[${i + 1}/${jobs.length}] run ${run} ${job.url}${job.nav && opts.follow.length ? ` -> ${job.nav}` : ""}`;
|
|
440
|
+
process.stdout.write(`${label} ... `);
|
|
441
|
+
const r = await runPage(browser, job.url, run, job.nav);
|
|
442
|
+
results.push(r);
|
|
443
|
+
if (r.error) console.log(`ERROR ${r.error}`);
|
|
444
|
+
else if (!r.nativeContext) console.log("no document.modelContext (WebMCP not enabled in this Chrome?)");
|
|
445
|
+
else {
|
|
446
|
+
let line = `${r.toolsAtLoad} at load, ${r.tools} final, ${r.waves.length} wave(s), settled ${r.settleAfterLoad ?? "-"} ms after load${r.settled ? "" : " (NOT settled)"}`;
|
|
447
|
+
if (r.navigation?.skipped) line += `; navigation skipped: ${r.navigation.skipped}`;
|
|
448
|
+
else if (r.navigation) line += `; ${NAV_TOOL} ${r.navigation.toolMs ?? "-"} ms, late tools ${r.navigation.lateTools ?? "-"}, title ${r.navigation.titleMatches === true ? "matches" : r.navigation.titleMatches === false ? "DIFFERS" : "not returned"}`;
|
|
449
|
+
console.log(line);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
await browser.close();
|
|
454
|
+
|
|
455
|
+
/* ---------------------------------------------------------------- output */
|
|
456
|
+
const ok = results.filter((r) => !r.error && r.nativeContext);
|
|
457
|
+
const byUrl = new Map();
|
|
458
|
+
for (const r of ok) (byUrl.get(r.url) ?? byUrl.set(r.url, []).get(r.url)).push(r);
|
|
459
|
+
const perPage = [...byUrl.entries()].map(([url, rs]) => ({
|
|
460
|
+
url,
|
|
461
|
+
runs: rs.length,
|
|
462
|
+
toolsAtLoad: median(rs.map((r) => r.toolsAtLoad)),
|
|
463
|
+
tools: median(rs.map((r) => r.tools)),
|
|
464
|
+
waves: median(rs.map((r) => r.waves.length)),
|
|
465
|
+
firstWaveTools: median(rs.map((r) => r.waves[0]?.tools ?? 0)),
|
|
466
|
+
firstRegistration: median(rs.map((r) => r.firstRegistration)),
|
|
467
|
+
load: median(rs.map((r) => r.load)),
|
|
468
|
+
lastRegistration: median(rs.map((r) => r.lastRegistration)),
|
|
469
|
+
settleAfterLoad: median(rs.map((r) => r.settleAfterLoad)),
|
|
470
|
+
unsettledRuns: rs.filter((r) => !r.settled).length,
|
|
471
|
+
}));
|
|
472
|
+
const navs = ok.filter((r) => r.navigation && !r.navigation.skipped).map((r) => ({ from: r.url, run: r.run, ...r.navigation }));
|
|
473
|
+
const calls = ok.flatMap((r) => Object.entries(r.calls ?? {}).map(([tool, c]) => ({ url: r.url, run: r.run, tool, ...c })));
|
|
474
|
+
|
|
475
|
+
fs.writeFileSync(path.join(OUT, "results.json"), JSON.stringify({
|
|
476
|
+
when: new Date().toISOString(),
|
|
477
|
+
chrome: chromeVersion,
|
|
478
|
+
settings: { runs: RUNS, quietMs: QUIET_MS, settleTimeoutMs: SETTLE_TIMEOUT_MS, waveGapMs: WAVE_GAP_MS, navigateTool: NAV_TOOL, navigateArgs: NAV_ARG_TEMPLATE, callReadonly: !!opts["call-readonly"] },
|
|
479
|
+
perPage, navigation: navs, calls, raw: results,
|
|
480
|
+
}, null, 2));
|
|
481
|
+
|
|
482
|
+
const pathOf = (u) => { try { const x = new URL(u); return x.host + x.pathname; } catch { return u; } };
|
|
483
|
+
const cell = (v) => (v == null ? "-" : String(v).replace(/\|/g, "\\|"));
|
|
484
|
+
const md = [];
|
|
485
|
+
md.push("# WebMCP registration timing", "");
|
|
486
|
+
md.push(`Chrome ${chromeVersion}, ${new Date().toISOString()}. ${RUNS} run(s) per page; medians shown. Settled = no registration for ${QUIET_MS} ms (cap ${SETTLE_TIMEOUT_MS} ms); waves split at gaps > ${WAVE_GAP_MS} ms. Times in ms from navigation start.`, "");
|
|
487
|
+
md.push("| Page | Tools at load | Final tools | Waves | First wave (tools @ ms) | Load | Last registration | Settle after load | Unsettled runs |");
|
|
488
|
+
md.push("|---|---:|---:|---:|---:|---:|---:|---:|---:|");
|
|
489
|
+
for (const p of perPage) md.push(`| ${cell(pathOf(p.url))} | ${cell(p.toolsAtLoad)} | ${cell(p.tools)} | ${cell(p.waves)} | ${p.firstRegistration == null ? "-" : `${p.firstWaveTools} @ ${p.firstRegistration}`} | ${cell(p.load)} | ${cell(p.lastRegistration)} | ${cell(p.settleAfterLoad)} | ${p.unsettledRuns} |`);
|
|
490
|
+
const failed = results.filter((r) => r.error || !r.nativeContext);
|
|
491
|
+
if (failed.length) {
|
|
492
|
+
md.push("", "Failed or no WebMCP:", "");
|
|
493
|
+
for (const r of failed) md.push(`- ${r.url} (run ${r.run}): ${r.error ?? "no document.modelContext"}`);
|
|
494
|
+
}
|
|
495
|
+
if (NAV_TOOL) {
|
|
496
|
+
md.push("", `## Navigation race (${NAV_TOOL})`, "");
|
|
497
|
+
md.push("Late tools = tools of the new page that registered after the tool call resolved (0 = the tool waited for them).", "");
|
|
498
|
+
if (navs.length) {
|
|
499
|
+
md.push("| From | Target / args | Run | Tool ms | Returned title | Final title | Title matches | New page tools | Late tools | Settled after call |");
|
|
500
|
+
md.push("|---|---|---:|---:|---|---|---|---:|---:|---:|");
|
|
501
|
+
for (const n of navs) md.push(`| ${cell(pathOf(n.from))} | ${cell(n.target ? pathOf(n.target) : JSON.stringify(n.args))} | ${n.run} | ${cell(n.toolMs)} | ${cell(n.returnedTitle)} | ${cell(n.finalTitle)} | ${n.titleMatches == null ? "-" : n.titleMatches ? "yes" : "NO"} | ${cell(n.newPageTools)} | ${cell(n.lateTools)} | ${cell(n.newToolsSettledAfterCall)} |`);
|
|
502
|
+
if (navs.some((n) => n.crossDocument)) md.push("", "Cross-document navigations lose the tool's answer (the calling page is gone); late tools cannot be measured for them.");
|
|
503
|
+
}
|
|
504
|
+
const skipped = ok.filter((r) => r.navigation?.skipped);
|
|
505
|
+
for (const r of skipped) md.push(`- skipped on ${r.url} (run ${r.run}): ${r.navigation.skipped}`);
|
|
506
|
+
}
|
|
507
|
+
if (calls.length) {
|
|
508
|
+
md.push("", "## Read-only tool calls", "");
|
|
509
|
+
md.push("| Page | Tool | Call ms | toolactivated after call | Activated before resolve | Event Timing entries | LoAF count | LoAF max | Error |");
|
|
510
|
+
md.push("|---|---|---:|---:|---:|---:|---:|---:|---|");
|
|
511
|
+
for (const c of calls) md.push(`| ${cell(pathOf(c.url))} | ${cell(c.tool)} | ${cell(c.ms)} | ${cell(c.activatedAfter)} | ${cell(c.activatedBeforeResolve)} | ${c.eventTimingEntries} | ${c.loafCount} | ${cell(c.loafMax)} | ${cell(c.error)} |`);
|
|
512
|
+
}
|
|
513
|
+
fs.writeFileSync(path.join(OUT, "summary.md"), md.join("\n") + "\n");
|
|
514
|
+
console.log(`\nwrote ${path.join(OUT, "results.json")}\nwrote ${path.join(OUT, "summary.md")}`);
|