browser-devtools-mcp 0.2.9 → 0.2.11
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/dist/cli/runner.js +5 -5
- package/dist/{core-76RLSP3N.js → core-7AI7DXNU.js} +1 -1
- package/dist/core-S6EFRNAR.js +1139 -0
- package/dist/core-SWCBNNLF.js +13 -0
- package/dist/daemon-server.js +1 -1
- package/dist/index.js +2 -2
- package/package.json +1 -1
- package/dist/core-3LSHIFWY.js +0 -13
- package/dist/core-QJWWV2SC.js +0 -1139
package/dist/core-QJWWV2SC.js
DELETED
|
@@ -1,1139 +0,0 @@
|
|
|
1
|
-
import{AMAZON_BEDROCK_ENABLE,AMAZON_BEDROCK_IMAGE_EMBED_MODEL_ID,AMAZON_BEDROCK_TEXT_EMBED_MODEL_ID,AMAZON_BEDROCK_VISION_MODEL_ID,AWS_PROFILE,AWS_REGION,BROWSER_CONSOLE_MESSAGES_BUFFER_SIZE,BROWSER_EXECUTABLE_PATH,BROWSER_HEADLESS_ENABLE,BROWSER_HTTP_REQUESTS_BUFFER_SIZE,BROWSER_LOCALE,BROWSER_PERSISTENT_ENABLE,BROWSER_PERSISTENT_USER_DATA_DIR,BROWSER_USE_INSTALLED_ON_SYSTEM,ConsoleMessageLevel,ConsoleMessageLevelName,FIGMA_ACCESS_TOKEN,FIGMA_API_BASE_URL,HttpMethod,HttpResourceType,NODE_CONSOLE_MESSAGES_BUFFER_SIZE,OTEL_ASSETS_DIR,OTEL_ENABLE,OTEL_EXPORTER_HTTP_HEADERS,OTEL_EXPORTER_HTTP_URL,OTEL_EXPORTER_TYPE,OTEL_INSTRUMENTATION_USER_INTERACTION_EVENTS,OTEL_SERVICE_NAME,OTEL_SERVICE_VERSION,PLATFORM,SourceMapResolver,V8Api,__name,addWatchExpression,clearWatchExpressions,createProbe,debug,detachDebugging,enableDebugging,evaluateInNode,getConsoleMessages,getExceptionBreakpoint,getSnapshotStats,getSnapshots,getSnapshotsByProbe,getStoreKey,hasSourceMaps,isDebuggingEnabled,listProbes,listWatchExpressions,removeProbe,removeWatchExpression,resolveSourceLocation,setExceptionBreakpoint,toJson,warn}from"./core-3LSHIFWY.js";import{z}from"zod";var TakeAriaSnapshot=class{static{__name(this,"TakeAriaSnapshot")}name(){return"a11y_take-aria-snapshot"}description(){return`
|
|
2
|
-
Captures an ARIA (accessibility) snapshot of the current page or a specific element.
|
|
3
|
-
If a selector is provided, the snapshot is scoped to that element; otherwise, the entire page is captured.
|
|
4
|
-
The output includes the page URL, title, and a YAML-formatted accessibility tree.
|
|
5
|
-
|
|
6
|
-
**UI Debugging Usage:**
|
|
7
|
-
- Use in combination with "a11y_take-ax-tree-snapshot" tool for comprehensive UI analysis
|
|
8
|
-
- Provides semantic structure and accessibility roles
|
|
9
|
-
- Helps identify accessibility issues and page hierarchy problems
|
|
10
|
-
`}inputSchema(){return{selector:z.string().describe("CSS selector for element to take snapshot.").optional()}}outputSchema(){return{output:z.string().describe("Includes the page URL, title, and a YAML-formatted accessibility tree.")}}async handle(context,args){let snapshot=await context.page.locator(args.selector||"body").ariaSnapshot();return{output:`
|
|
11
|
-
- Page URL: ${context.page.url()}
|
|
12
|
-
- Page Title: ${await context.page.title()}
|
|
13
|
-
- Page/Component Snapshot:
|
|
14
|
-
\`\`\`yaml
|
|
15
|
-
${snapshot}
|
|
16
|
-
\`\`\`
|
|
17
|
-
`.trim()}}};import{z as z2}from"zod";var DEFAULT_INCLUDE_STYLES=!0,DEFAULT_INCLUDE_RUNTIME_VISUAL=!0,DEFAULT_CHECK_OCCLUSION=!1,DEFAULT_ONLY_VISIBLE=!1,DEFAULT_ONLY_IN_VIEWPORT=!1,DEFAULT_TEXT_PREVIEW_MAX_LENGTH=80,DEFAULT_STYLE_PROPERTIES=["display","visibility","opacity","pointer-events","position","z-index","color","background-color","border-color","border-width","border-style","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-decoration-line","white-space","overflow","overflow-x","overflow-y","transform","cursor"],DEFAULT_INTERESTING_ROLES=new Set(["button","link","textbox","checkbox","radio","combobox","switch","tab","menuitem","dialog","heading","listbox","listitem","option"]),INTERNAL_CONCURRENCY=12,INTERNAL_SAFETY_CAP=2e3;function attrsToObj(attrs){let result={};if(!attrs)return result;for(let i=0;i<attrs.length;i+=2){let key=String(attrs[i]),value=String(attrs[i+1]??"");result[key]=value}return result}__name(attrsToObj,"attrsToObj");var TakeAxTreeSnapshot=class{static{__name(this,"TakeAxTreeSnapshot")}name(){return"accessibility_take-ax-tree-snapshot"}description(){return`
|
|
18
|
-
Captures a UI-focused snapshot by combining Chromium's Accessibility (AX) tree with runtime visual diagnostics.
|
|
19
|
-
|
|
20
|
-
Use this tool to detect UI issues like:
|
|
21
|
-
- Elements that exist semantically (AX role/name) but are visually hidden or off-screen
|
|
22
|
-
- Wrong layout/geometry (bounding box, viewport intersection)
|
|
23
|
-
- Styling issues (optional computed style subset)
|
|
24
|
-
- Overlap / stacking / occlusion issues (enable "checkOcclusion")
|
|
25
|
-
|
|
26
|
-
**UI Debugging Usage:**
|
|
27
|
-
- ALWAYS use "checkOcclusion:true" when investigating UI/layout problems
|
|
28
|
-
- Provides precise bounding boxes for overlap detection
|
|
29
|
-
- Use alongside "a11y_take-aria-snapshot" tool for complete UI analysis
|
|
30
|
-
|
|
31
|
-
Important notes for AI-driven UI debugging:
|
|
32
|
-
- "boundingBox" comes from "getBoundingClientRect()" (viewport coords). It represents the layout box, not every painted pixel
|
|
33
|
-
(e.g. shadows/pseudo-elements may extend beyond it).
|
|
34
|
-
- If something looks visible but clicks fail, enable "checkOcclusion". This samples multiple points (center + corners)
|
|
35
|
-
and uses "elementFromPoint()" to identify if another element is actually on top.
|
|
36
|
-
- When not occluded, "topElement" is null (even if "elementFromPoint" returns the element itself or its descendant).
|
|
37
|
-
- "selectorHint" is a best-effort locator (prefers "data-testid" / "data-selector" / "id"). It may not be unique.
|
|
38
|
-
- Use "onlyVisible" / "onlyInViewport" to reduce output when focusing on what the user currently sees.
|
|
39
|
-
`.trim()}inputSchema(){return{roles:z2.array(z2.enum(["button","link","textbox","checkbox","radio","combobox","switch","tab","menuitem","dialog","heading","listbox","listitem","option"])).describe("Optional role allowlist. If omitted, a built-in set of interactive roles is used.").optional(),includeStyles:z2.boolean().describe("Whether to include computed CSS styles for each node. Styles are extracted via runtime getComputedStyle().").optional().default(DEFAULT_INCLUDE_STYLES),includeRuntimeVisual:z2.boolean().describe("Whether to compute runtime visual information (bounding box, visibility, viewport).").optional().default(DEFAULT_INCLUDE_RUNTIME_VISUAL),checkOcclusion:z2.boolean().describe("If true, checks whether each element is visually occluded by another element using elementFromPoint() sampled at multiple points. Disabled by default.").optional().default(DEFAULT_CHECK_OCCLUSION),onlyVisible:z2.boolean().describe("If true, only visually visible nodes are returned.").optional().default(DEFAULT_ONLY_VISIBLE),onlyInViewport:z2.boolean().describe("If true, only nodes intersecting the viewport are returned.").optional().default(DEFAULT_ONLY_IN_VIEWPORT),textPreviewMaxLength:z2.number().int().positive().describe("Maximum length of the text preview extracted from each element.").optional().default(DEFAULT_TEXT_PREVIEW_MAX_LENGTH),styleProperties:z2.array(z2.string()).describe("List of CSS computed style properties to extract.").optional().default([...DEFAULT_STYLE_PROPERTIES])}}outputSchema(){return{url:z2.string().describe("The current page URL at the time the AX snapshot was captured."),title:z2.string().describe("The document title of the page at the time of the snapshot."),axNodeCount:z2.number().int().nonnegative().describe("Total number of nodes returned by Chromium Accessibility.getFullAXTree before filtering."),candidateCount:z2.number().int().nonnegative().describe("Number of DOM-backed AX nodes that passed role filtering before enrichment."),enrichedCount:z2.number().int().nonnegative().describe("Number of nodes included in the final enriched snapshot output."),truncatedBySafetyCap:z2.boolean().describe("Indicates whether the result set was truncated by an internal safety cap to prevent excessive output size."),nodes:z2.array(z2.object({axNodeId:z2.string().describe("Unique identifier of the accessibility node within the AX tree."),parentAxNodeId:z2.string().nullable().describe("Parent AX node id in the full AX tree. Null if this node is a root."),childAxNodeIds:z2.array(z2.string()).describe("Child AX node ids in the full AX tree (may include nodes not present in the filtered output)."),role:z2.string().nullable().describe("ARIA role of the accessibility node (e.g. button, link, textbox)."),name:z2.string().nullable().describe("Accessible name computed by the browser accessibility engine."),ignored:z2.boolean().nullable().describe("Whether the accessibility node is marked as ignored."),backendDOMNodeId:z2.number().int().describe("Chromium backend DOM node identifier used to map AX nodes to DOM elements."),domNodeId:z2.number().int().nullable().describe("Resolved DOM nodeId from CDP if available; may be null because nodeId is not guaranteed to be stable/resolved."),frameId:z2.string().nullable().describe("Frame identifier if the node belongs to an iframe or subframe."),localName:z2.string().nullable().describe("Lowercased DOM tag name of the mapped element (e.g. div, button, input)."),id:z2.string().nullable().describe("DOM id attribute of the mapped element."),className:z2.string().nullable().describe("DOM class attribute of the mapped element."),selectorHint:z2.string().nullable().describe("Best-effort selector hint for targeting this element (prefers data-testid/data-selector/id)."),textPreview:z2.string().nullable().describe("Short preview of rendered text content or aria-label, truncated to the configured maximum length."),value:z2.any().nullable().describe("Raw AX value payload associated with the node, if present."),description:z2.any().nullable().describe("Raw AX description payload associated with the node, if present."),properties:z2.array(z2.any()).nullable().describe("Additional AX properties exposed by the accessibility tree."),styles:z2.record(z2.string(),z2.string()).optional().describe("Subset of computed CSS styles for the element as string key-value pairs."),runtime:z2.object({boundingBox:z2.object({x:z2.number().describe("X coordinate of the element relative to the viewport."),y:z2.number().describe("Y coordinate of the element relative to the viewport."),width:z2.number().describe("Width of the element in CSS pixels."),height:z2.number().describe("Height of the element in CSS pixels.")}).nullable().describe("Bounding box computed at runtime using getBoundingClientRect."),isVisible:z2.boolean().describe("Whether the element is considered visually visible (display, visibility, opacity, and size)."),isInViewport:z2.boolean().describe("Whether the element intersects the current viewport."),occlusion:z2.object({samplePoints:z2.array(z2.object({x:z2.number().describe("Sample point X (viewport coordinates) used for occlusion testing."),y:z2.number().describe("Sample point Y (viewport coordinates) used for occlusion testing."),hit:z2.boolean().describe("True if elementFromPoint at this point returned a different element that is not a descendant.")})).describe("Sample points used for occlusion detection (center + corners)."),isOccluded:z2.boolean().describe("True if at least one sample point is covered by another element."),topElement:z2.object({localName:z2.string().nullable().describe("Tag name of the occluding element."),id:z2.string().nullable().describe("DOM id of the occluding element (may be null if none)."),className:z2.string().nullable().describe("DOM class of the occluding element (may be null if none)."),selectorHint:z2.string().nullable().describe("Best-effort selector hint for the occluding element."),boundingBox:z2.object({x:z2.number().describe("X coordinate of the occluding element bounding box."),y:z2.number().describe("Y coordinate of the occluding element bounding box."),width:z2.number().describe("Width of the occluding element bounding box."),height:z2.number().describe("Height of the occluding element bounding box.")}).nullable().describe("Bounding box of the occluding element (if available).")}).nullable().describe("Identity and geometry of the occluding element. Null when not occluded."),intersection:z2.object({x:z2.number().describe("Intersection rect X."),y:z2.number().describe("Intersection rect Y."),width:z2.number().describe("Intersection rect width."),height:z2.number().describe("Intersection rect height."),area:z2.number().describe("Intersection rect area in CSS pixels squared.")}).nullable().describe("Intersection box between this element and the occluding element. Null if not occluded or cannot compute.")}).optional().describe("Occlusion detection results. Only present when checkOcclusion=true.")}).optional().describe("Runtime-derived visual information representing how the element is actually rendered.")})).describe("List of enriched DOM-backed AX nodes combining accessibility metadata with visual diagnostics.")}}async handle(context,args){let page=context.page,includeRuntimeVisual=args.includeRuntimeVisual??DEFAULT_INCLUDE_RUNTIME_VISUAL,includeStyles=args.includeStyles??DEFAULT_INCLUDE_STYLES,checkOcclusion=args.checkOcclusion??DEFAULT_CHECK_OCCLUSION,onlyVisible=args.onlyVisible??DEFAULT_ONLY_VISIBLE,onlyInViewport=args.onlyInViewport??DEFAULT_ONLY_IN_VIEWPORT;if((onlyVisible||onlyInViewport)&&!includeRuntimeVisual)throw new Error("onlyVisible/onlyInViewport require includeRuntimeVisual=true.");if(checkOcclusion&&!includeRuntimeVisual)throw new Error("checkOcclusion requires includeRuntimeVisual=true.");let textMax=args.textPreviewMaxLength??DEFAULT_TEXT_PREVIEW_MAX_LENGTH,stylePropsRaw=args.styleProperties&&args.styleProperties.length>0?args.styleProperties:DEFAULT_STYLE_PROPERTIES,stylePropsLower=Array.from(stylePropsRaw).map(p=>p.toLowerCase()),roleAllow=args.roles&&args.roles.length>0?new Set(args.roles):new Set(Array.from(DEFAULT_INTERESTING_ROLES)),cdp=await page.context().newCDPSession(page);try{await cdp.send("DOM.enable"),await cdp.send("Accessibility.enable"),includeRuntimeVisual&&await cdp.send("Runtime.enable");let axResponse=await cdp.send("Accessibility.getFullAXTree"),axNodes=axResponse.nodes??axResponse,parentByChildId=new Map,childIdsByNodeId=new Map;for(let n of axNodes){let nodeIdStr=String(n.nodeId),childIds=(n.childIds??[]).map(cid=>String(cid));childIdsByNodeId.set(nodeIdStr,childIds);for(let childIdStr of childIds)parentByChildId.set(childIdStr,nodeIdStr)}let candidates=axNodes.filter(n=>{if(typeof n.backendDOMNodeId!="number")return!1;let roleValue=n.role?.value??null;return roleValue?roleAllow.has(String(roleValue)):!1}),candidateCount=candidates.length,truncatedBySafetyCap=candidates.length>INTERNAL_SAFETY_CAP;truncatedBySafetyCap&&(candidates=candidates.slice(0,INTERNAL_SAFETY_CAP));let queue=[...candidates],nodesOut=[],objectIds=[],worker=__name(async()=>{for(;queue.length>0;){let ax=queue.shift();if(!ax)return;let axNodeIdStr=String(ax.nodeId),parentAxNodeId=parentByChildId.get(axNodeIdStr)??null,childAxNodeIds=childIdsByNodeId.get(axNodeIdStr)??[],backendDOMNodeId=ax.backendDOMNodeId,domNodeId=null,localName=null,id=null,className=null,objectId=null;try{let node=(await cdp.send("DOM.describeNode",{backendNodeId:backendDOMNodeId}))?.node;if(node){let nodeIdCandidate=node.nodeId;typeof nodeIdCandidate=="number"&&nodeIdCandidate>0?domNodeId=nodeIdCandidate:domNodeId=null,localName=node.localName??(node.nodeName?String(node.nodeName).toLowerCase():null);let attrObj=attrsToObj(node.attributes);id=attrObj.id??null,className=attrObj.class??null}}catch{}if(includeRuntimeVisual)try{objectId=(await cdp.send("DOM.resolveNode",{backendNodeId:backendDOMNodeId}))?.object?.objectId??null}catch{}let roleStr=ax.role?.value?String(ax.role.value):null,nameStr=ax.name?.value?String(ax.name.value):null,ignoredVal=typeof ax.ignored=="boolean"?ax.ignored:null,item={axNodeId:axNodeIdStr,parentAxNodeId,childAxNodeIds,role:roleStr,name:nameStr,ignored:ignoredVal,backendDOMNodeId,domNodeId,frameId:ax.frameId??null,localName,id,className,selectorHint:null,textPreview:null,value:ax.value??null,description:ax.description??null,properties:Array.isArray(ax.properties)?ax.properties:null},index=nodesOut.push(item)-1;objectIds[index]=objectId}},"worker"),workers=Array.from({length:INTERNAL_CONCURRENCY},()=>worker());if(await Promise.all(workers),includeRuntimeVisual){let globalObjectId=(await cdp.send("Runtime.evaluate",{expression:"globalThis",returnByValue:!1}))?.result?.objectId;if(globalObjectId){let runtimeArgs=objectIds.map(oid=>oid?{objectId:oid}:{value:null}),values=(await cdp.send("Runtime.callFunctionOn",{objectId:globalObjectId,returnByValue:!0,functionDeclaration:`
|
|
40
|
-
function(textMax, includeStyles, styleProps, checkOcclusion, ...els) {
|
|
41
|
-
function selectorHintFor(el) {
|
|
42
|
-
if (!(el instanceof Element)) { return null; }
|
|
43
|
-
|
|
44
|
-
const dt = el.getAttribute('data-testid')
|
|
45
|
-
|| el.getAttribute('data-test-id')
|
|
46
|
-
|| el.getAttribute('data-test');
|
|
47
|
-
|
|
48
|
-
if (dt && dt.trim()) { return '[data-testid="' + dt.replace(/"/g, '\\\\\\"') + '"]'; }
|
|
49
|
-
|
|
50
|
-
const ds = el.getAttribute('data-selector');
|
|
51
|
-
if (ds && ds.trim()) { return '[data-selector="' + ds.replace(/"/g, '\\\\\\"') + '"]'; }
|
|
52
|
-
|
|
53
|
-
if (el.id) { return '#' + CSS.escape(el.id); }
|
|
54
|
-
|
|
55
|
-
return el.tagName.toLowerCase();
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function textPreviewFor(el) {
|
|
59
|
-
if (!(el instanceof Element)) { return null; }
|
|
60
|
-
|
|
61
|
-
const aria = el.getAttribute('aria-label');
|
|
62
|
-
if (aria && aria.trim()) { return aria.trim().slice(0, textMax); }
|
|
63
|
-
|
|
64
|
-
const txt = (el.innerText || el.textContent || '').trim();
|
|
65
|
-
if (!txt) { return null; }
|
|
66
|
-
|
|
67
|
-
return txt.slice(0, textMax);
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
function pickStyles(el) {
|
|
71
|
-
if (!includeStyles) { return undefined; }
|
|
72
|
-
if (!(el instanceof Element)) { return undefined; }
|
|
73
|
-
|
|
74
|
-
const s = getComputedStyle(el);
|
|
75
|
-
const out = {};
|
|
76
|
-
|
|
77
|
-
for (let i = 0; i < styleProps.length; i++) {
|
|
78
|
-
const prop = styleProps[i];
|
|
79
|
-
try { out[prop] = s.getPropertyValue(prop); } catch {}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
return out;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function intersectRects(a, b) {
|
|
86
|
-
const x1 = Math.max(a.left, b.left);
|
|
87
|
-
const y1 = Math.max(a.top, b.top);
|
|
88
|
-
const x2 = Math.min(a.right, b.right);
|
|
89
|
-
const y2 = Math.min(a.bottom, b.bottom);
|
|
90
|
-
|
|
91
|
-
const w = Math.max(0, x2 - x1);
|
|
92
|
-
const h = Math.max(0, y2 - y1);
|
|
93
|
-
|
|
94
|
-
return {
|
|
95
|
-
x: x1,
|
|
96
|
-
y: y1,
|
|
97
|
-
width: w,
|
|
98
|
-
height: h,
|
|
99
|
-
area: w * h,
|
|
100
|
-
};
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
function occlusionInfoFor(el) {
|
|
104
|
-
if (!(el instanceof Element)) {
|
|
105
|
-
return {
|
|
106
|
-
samplePoints: [],
|
|
107
|
-
isOccluded: false,
|
|
108
|
-
topElement: null,
|
|
109
|
-
intersection: null,
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
const r = el.getBoundingClientRect();
|
|
114
|
-
const hasBox = Number.isFinite(r.left) && Number.isFinite(r.top) && r.width > 0 && r.height > 0;
|
|
115
|
-
|
|
116
|
-
if (!hasBox) {
|
|
117
|
-
return {
|
|
118
|
-
samplePoints: [],
|
|
119
|
-
isOccluded: false,
|
|
120
|
-
topElement: null,
|
|
121
|
-
intersection: null,
|
|
122
|
-
};
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// Sample center + 4 corners (inset) to better detect partial occlusion / overlap.
|
|
126
|
-
const inset = Math.max(1, Math.min(6, Math.floor(Math.min(r.width, r.height) / 4)));
|
|
127
|
-
const points = [
|
|
128
|
-
{ x: r.left + r.width / 2, y: r.top + r.height / 2 }, // center
|
|
129
|
-
{ x: r.left + inset, y: r.top + inset }, // top-left
|
|
130
|
-
{ x: r.right - inset, y: r.top + inset }, // top-right
|
|
131
|
-
{ x: r.left + inset, y: r.bottom - inset }, // bottom-left
|
|
132
|
-
{ x: r.right - inset, y: r.bottom - inset }, // bottom-right
|
|
133
|
-
];
|
|
134
|
-
|
|
135
|
-
let chosenTop = null;
|
|
136
|
-
let chosenTopRect = null;
|
|
137
|
-
let chosenIntersection = null;
|
|
138
|
-
let anyHit = false;
|
|
139
|
-
|
|
140
|
-
const samples = [];
|
|
141
|
-
|
|
142
|
-
for (const p of points) {
|
|
143
|
-
const topEl = document.elementFromPoint(p.x, p.y);
|
|
144
|
-
|
|
145
|
-
// Consider it "hit" only if topEl is not the element itself and not a descendant.
|
|
146
|
-
const hit = !!(topEl && topEl !== el && !el.contains(topEl));
|
|
147
|
-
|
|
148
|
-
samples.push({ x: p.x, y: p.y, hit });
|
|
149
|
-
|
|
150
|
-
if (hit) {
|
|
151
|
-
anyHit = true;
|
|
152
|
-
|
|
153
|
-
// Prefer the top element with the largest intersection area with this element's rect.
|
|
154
|
-
const topRect = topEl.getBoundingClientRect();
|
|
155
|
-
const inter = intersectRects(r, topRect);
|
|
156
|
-
|
|
157
|
-
if (!chosenTop || (chosenIntersection && inter.area > chosenIntersection.area)) {
|
|
158
|
-
chosenTop = topEl;
|
|
159
|
-
chosenTopRect = topRect;
|
|
160
|
-
chosenIntersection = inter;
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
// If not occluded, DO NOT return topElement at all (prevents "self occlusion" noise).
|
|
166
|
-
if (!anyHit || !chosenTop) {
|
|
167
|
-
return {
|
|
168
|
-
samplePoints: samples,
|
|
169
|
-
isOccluded: false,
|
|
170
|
-
topElement: null,
|
|
171
|
-
intersection: null,
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
const id = chosenTop.id ? chosenTop.id : null;
|
|
176
|
-
const className = chosenTop.getAttribute('class') ? chosenTop.getAttribute('class') : null;
|
|
177
|
-
|
|
178
|
-
return {
|
|
179
|
-
samplePoints: samples,
|
|
180
|
-
isOccluded: true,
|
|
181
|
-
topElement: {
|
|
182
|
-
localName: chosenTop.tagName ? chosenTop.tagName.toLowerCase() : null,
|
|
183
|
-
id: id,
|
|
184
|
-
className: className,
|
|
185
|
-
selectorHint: selectorHintFor(chosenTop),
|
|
186
|
-
boundingBox: chosenTopRect ? {
|
|
187
|
-
x: chosenTopRect.x,
|
|
188
|
-
y: chosenTopRect.y,
|
|
189
|
-
width: chosenTopRect.width,
|
|
190
|
-
height: chosenTopRect.height,
|
|
191
|
-
} : null,
|
|
192
|
-
},
|
|
193
|
-
intersection: chosenIntersection ? {
|
|
194
|
-
x: chosenIntersection.x,
|
|
195
|
-
y: chosenIntersection.y,
|
|
196
|
-
width: chosenIntersection.width,
|
|
197
|
-
height: chosenIntersection.height,
|
|
198
|
-
area: chosenIntersection.area,
|
|
199
|
-
} : null,
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const vw = innerWidth;
|
|
204
|
-
const vh = innerHeight;
|
|
205
|
-
|
|
206
|
-
return els.map((el) => {
|
|
207
|
-
if (!(el instanceof Element)) {
|
|
208
|
-
return {
|
|
209
|
-
selectorHint: null,
|
|
210
|
-
textPreview: null,
|
|
211
|
-
styles: undefined,
|
|
212
|
-
runtime: {
|
|
213
|
-
boundingBox: null,
|
|
214
|
-
isVisible: false,
|
|
215
|
-
isInViewport: false,
|
|
216
|
-
occlusion: checkOcclusion ? {
|
|
217
|
-
samplePoints: [],
|
|
218
|
-
isOccluded: false,
|
|
219
|
-
topElement: null,
|
|
220
|
-
intersection: null,
|
|
221
|
-
} : undefined,
|
|
222
|
-
},
|
|
223
|
-
};
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
const r = el.getBoundingClientRect();
|
|
227
|
-
const s = getComputedStyle(el);
|
|
228
|
-
|
|
229
|
-
const isVisible =
|
|
230
|
-
s.display !== 'none'
|
|
231
|
-
&& s.visibility !== 'hidden'
|
|
232
|
-
&& parseFloat(s.opacity || '1') > 0
|
|
233
|
-
&& r.width > 0
|
|
234
|
-
&& r.height > 0;
|
|
235
|
-
|
|
236
|
-
const isInViewport =
|
|
237
|
-
r.right > 0
|
|
238
|
-
&& r.bottom > 0
|
|
239
|
-
&& r.left < vw
|
|
240
|
-
&& r.top < vh;
|
|
241
|
-
|
|
242
|
-
const occlusion = checkOcclusion ? occlusionInfoFor(el) : undefined;
|
|
243
|
-
|
|
244
|
-
return {
|
|
245
|
-
selectorHint: selectorHintFor(el),
|
|
246
|
-
textPreview: textPreviewFor(el),
|
|
247
|
-
styles: pickStyles(el),
|
|
248
|
-
runtime: {
|
|
249
|
-
boundingBox: {
|
|
250
|
-
x: r.x,
|
|
251
|
-
y: r.y,
|
|
252
|
-
width: r.width,
|
|
253
|
-
height: r.height,
|
|
254
|
-
},
|
|
255
|
-
isVisible: isVisible,
|
|
256
|
-
isInViewport: isInViewport,
|
|
257
|
-
occlusion: occlusion,
|
|
258
|
-
},
|
|
259
|
-
};
|
|
260
|
-
});
|
|
261
|
-
}
|
|
262
|
-
`,arguments:[{value:textMax},{value:includeStyles},{value:stylePropsLower},{value:checkOcclusion},...runtimeArgs]}))?.result?.value??[];for(let i=0;i<nodesOut.length;i++){let v=values[i];v&&(nodesOut[i].selectorHint=v.selectorHint??null,nodesOut[i].textPreview=v.textPreview??null,v.styles&&(nodesOut[i].styles=v.styles),v.runtime&&(nodesOut[i].runtime=v.runtime))}}}let finalNodes=nodesOut;return(onlyVisible||onlyInViewport)&&(finalNodes=finalNodes.filter(n=>!(!n.runtime||onlyVisible&&!n.runtime.isVisible||onlyInViewport&&!n.runtime.isInViewport))),{url:String(page.url()),title:String(await page.title()),axNodeCount:axNodes.length,candidateCount,enrichedCount:finalNodes.length,truncatedBySafetyCap,nodes:finalNodes}}finally{await cdp.detach().catch(()=>{})}}};var tools=[new TakeAriaSnapshot,new TakeAxTreeSnapshot];import{z as z3}from"zod";var DEFAULT_MAX_HTML_LENGTH=5e4,GetAsHtml=class{static{__name(this,"GetAsHtml")}name(){return"content_get-as-html"}description(){return`
|
|
263
|
-
Gets the HTML content of the current page.
|
|
264
|
-
By default, all <script> tags are removed from the output unless "removeScripts" is explicitly set to "false".
|
|
265
|
-
`}inputSchema(){return{selector:z3.string().describe("CSS selector to limit the HTML content to a specific container.").optional(),removeScripts:z3.boolean().describe('Remove all script tags from the HTML (default: "true").').optional().default(!0),removeComments:z3.boolean().describe('Remove all HTML comments (default: "false").').optional().default(!1),removeStyles:z3.boolean().describe('Remove all style tags from the HTML (default: "false").').optional().default(!1),removeMeta:z3.boolean().describe('Remove all meta tags from the HTML (default: "false").').optional().default(!1),cleanHtml:z3.boolean().describe('Perform comprehensive HTML cleaning (default: "false").').optional().default(!1),minify:z3.boolean().describe('Minify the HTML output (default: "false").').optional().default(!1),maxLength:z3.number().int().positive().describe(`Maximum number of characters to return (default: "${DEFAULT_MAX_HTML_LENGTH}").`).optional().default(DEFAULT_MAX_HTML_LENGTH)}}outputSchema(){return{output:z3.string().describe("The requested HTML content of the page.")}}async handle(context,args){let{selector,removeScripts,removeComments,removeStyles,removeMeta,minify,cleanHtml,maxLength}=args,htmlContent;if(selector){let element=await context.page.$(selector);if(!element)throw new Error(`Element with selector "${selector}" not found`);htmlContent=await element.evaluate(el=>el.outerHTML)}else htmlContent=await context.page.content();let shouldRemoveScripts=removeScripts||cleanHtml,shouldRemoveComments=removeComments||cleanHtml,shouldRemoveStyles=removeStyles||cleanHtml,shouldRemoveMeta=removeMeta||cleanHtml;(shouldRemoveScripts||shouldRemoveComments||shouldRemoveStyles||shouldRemoveMeta||minify)&&(htmlContent=await context.page.evaluate(params=>{let html=params.html,removeScripts2=params.removeScripts,removeComments2=params.removeComments,removeStyles2=params.removeStyles,removeMeta2=params.removeMeta,minify2=params.minify,template=document.createElement("template");template.innerHTML=html;let root=template.content;if(removeScripts2&&root.querySelectorAll("script").forEach(script=>script.remove()),removeStyles2&&root.querySelectorAll("style").forEach(style=>style.remove()),removeMeta2&&root.querySelectorAll("meta").forEach(meta=>meta.remove()),removeComments2){let removeComments3=__name(node=>{let childNodes=node.childNodes;for(let i=childNodes.length-1;i>=0;i--){let child=childNodes[i];child.nodeType===8?node.removeChild(child):child.nodeType===1&&removeComments3(child)}},"removeComments");removeComments3(root)}let result=template.innerHTML;return minify2&&(result=result.replace(/>\s+</g,"><").trim()),result},{html:htmlContent,removeScripts:shouldRemoveScripts,removeComments:shouldRemoveComments,removeStyles:shouldRemoveStyles,removeMeta:shouldRemoveMeta,minify}));let output=htmlContent;return output.length>maxLength&&(output=output.slice(0,maxLength)+`
|
|
266
|
-
<!-- Output truncated due to size limits -->`),{output}}};import{z as z4}from"zod";var DEFAULT_MAX_TEXT_LENGTH=5e4,GetAsText=class{static{__name(this,"GetAsText")}name(){return"content_get-as-text"}description(){return"Gets the visible text content of the current page."}inputSchema(){return{selector:z4.string().describe("CSS selector to limit the text content to a specific container.").optional(),maxLength:z4.number().int().positive().describe(`Maximum number of characters to return (default: "${DEFAULT_MAX_TEXT_LENGTH}").`).optional().default(DEFAULT_MAX_TEXT_LENGTH)}}outputSchema(){return{output:z4.string().describe("The requested text content of the page.")}}async handle(context,args){let{selector,maxLength}=args,output=await context.page.evaluate(params=>{let selector2=params.selector,root=selector2?document.querySelector(selector2):document.body;if(!root)throw new Error(`Element with selector "${selector2}" not found`);let walker=document.createTreeWalker(root,NodeFilter.SHOW_TEXT,{acceptNode:__name(node2=>{let style=window.getComputedStyle(node2.parentElement);return style.display!=="none"&&style.visibility!=="hidden"?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT},"acceptNode")}),text="",node;for(;node=walker.nextNode();){let trimmedText=node.textContent?.trim();trimmedText&&(text+=trimmedText+`
|
|
267
|
-
`)}return text.trim()},{selector});return output.length>maxLength&&(output=output.slice(0,maxLength)+`
|
|
268
|
-
[Output truncated due to size limits]`),{output}}};function getEnumKeyTuples(enumObj){let values=Object.keys(enumObj).filter(key=>isNaN(Number(key))).map(key=>enumObj[key]);if(values.length===0)throw new Error("Enum has no values");return values}__name(getEnumKeyTuples,"getEnumKeyTuples");function createEnumTransformer(enumObj,opts){let values=Object.keys(enumObj).filter(k=>isNaN(Number(k))).map(k=>enumObj[k]),caseInsensitive=opts?.caseInsensitive??!0,lookup=new Map(values.map(v=>[caseInsensitive?v.toLowerCase():v,v]));return value=>{let key=caseInsensitive?value.toLowerCase():value,found=lookup.get(key);if(found===void 0)throw new Error(`Invalid enum value: "${value}"`);return found}}__name(createEnumTransformer,"createEnumTransformer");function formattedTimeForFilename(date=new Date){let pad=__name(n=>String(n).padStart(2,"0"),"pad");return date.getFullYear()+pad(date.getMonth()+1)+pad(date.getDate())+"-"+pad(date.getHours())+pad(date.getMinutes())+pad(date.getSeconds())}__name(formattedTimeForFilename,"formattedTimeForFilename");import os from"node:os";import path from"node:path";import{z as z5}from"zod";var SizeUnit=(SizeUnit2=>(SizeUnit2.PIXEL="px",SizeUnit2.INCH="in",SizeUnit2.CENTIMETER="cm",SizeUnit2.MILLIMETER="mm",SizeUnit2))(SizeUnit||{}),PageFormat=(PageFormat2=>(PageFormat2.LETTER="Letter",PageFormat2.LEGAL="Legal",PageFormat2.TABLOID="Tabloid",PageFormat2.LEDGER="Ledger",PageFormat2.A0="A0",PageFormat2.A1="A1",PageFormat2.A2="A2",PageFormat2.A3="A3",PageFormat2.A4="A4",PageFormat2.A5="A5",PageFormat2.A6="A6",PageFormat2))(PageFormat||{}),DEFAULT_NAME="page",DEFAULT_MARGIN="1cm",DEFAULT_FORMAT="A4",DEFAULT_MARGINS={top:DEFAULT_MARGIN,right:DEFAULT_MARGIN,bottom:DEFAULT_MARGIN,left:DEFAULT_MARGIN},SaveAsPdf=class{static{__name(this,"SaveAsPdf")}name(){return"content_save-as-pdf"}description(){return"Saves the current page as a PDF file."}inputSchema(){return{outputPath:z5.string().describe("Directory path where PDF will be saved. By default OS tmp directory is used.").optional().default(os.tmpdir()),name:z5.string().describe(`Name of the save/export. Default value is "${DEFAULT_NAME}". Note that final saved/exported file name is in the "{name}-{time}.pdf" format in which "{time}" is in the "YYYYMMDD-HHmmss" format.`).optional().default(DEFAULT_NAME),format:z5.enum(getEnumKeyTuples(PageFormat)).transform(createEnumTransformer(PageFormat)).describe(`Page format. Valid values are: ${getEnumKeyTuples(PageFormat)}.`).optional().default(DEFAULT_FORMAT),printBackground:z5.boolean().describe('Whether to print background graphics (default: "false").').optional().default(!1),margin:z5.object({top:z5.string().describe("Top margin.").default(DEFAULT_MARGIN),right:z5.string().describe("Right margin.").default(DEFAULT_MARGIN),bottom:z5.string().describe("Bottom margin.").default(DEFAULT_MARGIN),left:z5.string().describe("Left margin.").default(DEFAULT_MARGIN)}).describe(`Page margins. Numeric margin values labeled with units ("100px", "10cm", etc ...). Unlabeled values are treated as pixels. Valid units are: ${getEnumKeyTuples(SizeUnit)}.`).optional()}}outputSchema(){return{filePath:z5.string().describe("Full path of the saved PDF file.")}}async handle(context,args){let filename=`${args.name||DEFAULT_NAME}-${formattedTimeForFilename()}.pdf`,filePath=path.resolve(args.outputPath,filename),options={path:filePath,format:args.format,printBackground:args.printBackground,margin:args.margin||DEFAULT_MARGINS};return await context.page.pdf(options),{filePath}}};import os2 from"node:os";import path2 from"node:path";import jpegjs from"jpeg-js";import{PNG}from"pngjs";import{z as z6}from"zod";var ScreenshotType=(ScreenshotType2=>(ScreenshotType2.PNG="png",ScreenshotType2.JPEG="jpeg",ScreenshotType2))(ScreenshotType||{}),DEFAULT_SCREENSHOT_NAME="screenshot",DEFAULT_SCREENSHOT_TYPE="png",DEFAULT_SCREENSHOT_QUALITY=100,TakeScreenshot=class{static{__name(this,"TakeScreenshot")}name(){return"content_take-screenshot"}description(){return`Takes a screenshot of the current page or a specific element.
|
|
269
|
-
The screenshot is ALWAYS saved to the file system; the file path is returned.
|
|
270
|
-
By default, image data is NOT included in the response (includeBase64 defaults to false).
|
|
271
|
-
**Prefer ARIA or AX tree snapshots for structure/layout/accessibility; use this tool only when you truly need to see the visual appearance of the UI.**
|
|
272
|
-
Do NOT set includeBase64 to true unless the assistant cannot read the file from the returned path (e.g. remote server, container). When in doubt, omit includeBase64 or set it to false.`}inputSchema(){return{outputPath:z6.string().describe("Directory path where screenshot will be saved. By default OS tmp directory is used.").optional().default(os2.tmpdir()),name:z6.string().describe(`Name of the screenshot. Default value is "${DEFAULT_SCREENSHOT_NAME}". Note that final saved/exported file name is in the "{name}-{time}.{type}" format in which "{time}" is in the "YYYYMMDD-HHmmss" format.`).optional().default(DEFAULT_SCREENSHOT_NAME),selector:z6.string().describe("CSS selector for element to take screenshot.").optional(),fullPage:z6.boolean().describe('Whether to take a screenshot of the full scrollable page, instead of the currently visible viewport (default: "false").').optional().default(!1),type:z6.enum(getEnumKeyTuples(ScreenshotType)).transform(createEnumTransformer(ScreenshotType)).describe(`Page format. Valid values are: ${getEnumKeyTuples(ScreenshotType)}`).optional().default(DEFAULT_SCREENSHOT_TYPE),quality:z6.number().int().min(0).max(DEFAULT_SCREENSHOT_QUALITY).describe("The quality of the image, between 0-100. Not applicable to png images.").optional(),includeBase64:z6.boolean().describe("If true, includes base64 image data in the response (increases payload size). Default is false. The screenshot is always saved to disk; use the returned file path to read it. Set to true ONLY when the assistant cannot access the MCP server file system (e.g. remote/container). Avoid setting to true otherwise.").optional().default(!1)}}outputSchema(){return{filePath:z6.string().describe("Full path of the saved screenshot file."),image:z6.object({data:z6.any().describe("Base64-encoded image data."),mimeType:z6.string().describe("MIME type of the image.")}).optional().describe('Image data included only when "includeBase64" input parameter is set to true.')}}_scaleImageToSize(image,size){let{data:src,width:w1,height:h1}=image,w2=Math.max(1,Math.floor(size.width)),h2=Math.max(1,Math.floor(size.height));if(w1===w2&&h1===h2)return image;if(w1<=0||h1<=0)throw new Error("Invalid input image");if(size.width<=0||size.height<=0||!isFinite(size.width)||!isFinite(size.height))throw new Error("Invalid output dimensions");let clamp=__name((v,lo,hi)=>v<lo?lo:v>hi?hi:v,"clamp"),weights=__name((t,o)=>{let t2=t*t,t3=t2*t;o[0]=-.5*t+1*t2-.5*t3,o[1]=1-2.5*t2+1.5*t3,o[2]=.5*t+2*t2-1.5*t3,o[3]=-.5*t2+.5*t3},"weights"),srcRowStride=w1*4,dstRowStride=w2*4,xOff=new Int32Array(w2*4),xW=new Float32Array(w2*4),wx=new Float32Array(4),xScale=w1/w2;for(let x=0;x<w2;x++){let sx=(x+.5)*xScale-.5,sxi=Math.floor(sx),t=sx-sxi;weights(t,wx);let b=x*4,i0=clamp(sxi-1,0,w1-1),i1=clamp(sxi+0,0,w1-1),i2=clamp(sxi+1,0,w1-1),i3=clamp(sxi+2,0,w1-1);xOff[b+0]=i0<<2,xOff[b+1]=i1<<2,xOff[b+2]=i2<<2,xOff[b+3]=i3<<2,xW[b+0]=wx[0],xW[b+1]=wx[1],xW[b+2]=wx[2],xW[b+3]=wx[3]}let yRow=new Int32Array(h2*4),yW=new Float32Array(h2*4),wy=new Float32Array(4),yScale=h1/h2;for(let y=0;y<h2;y++){let sy=(y+.5)*yScale-.5,syi=Math.floor(sy),t=sy-syi;weights(t,wy);let b=y*4,j0=clamp(syi-1,0,h1-1),j1=clamp(syi+0,0,h1-1),j2=clamp(syi+1,0,h1-1),j3=clamp(syi+2,0,h1-1);yRow[b+0]=j0*srcRowStride,yRow[b+1]=j1*srcRowStride,yRow[b+2]=j2*srcRowStride,yRow[b+3]=j3*srcRowStride,yW[b+0]=wy[0],yW[b+1]=wy[1],yW[b+2]=wy[2],yW[b+3]=wy[3]}let dst=new Uint8Array(w2*h2*4);for(let y=0;y<h2;y++){let yb=y*4,rb0=yRow[yb+0],rb1=yRow[yb+1],rb2=yRow[yb+2],rb3=yRow[yb+3],wy0=yW[yb+0],wy1=yW[yb+1],wy2=yW[yb+2],wy3=yW[yb+3],dstBase=y*dstRowStride;for(let x=0;x<w2;x++){let xb=x*4,xo0=xOff[xb+0],xo1=xOff[xb+1],xo2=xOff[xb+2],xo3=xOff[xb+3],wx0=xW[xb+0],wx1=xW[xb+1],wx2=xW[xb+2],wx3=xW[xb+3],di=dstBase+(x<<2);for(let c=0;c<4;c++){let r0=src[rb0+xo0+c]*wx0+src[rb0+xo1+c]*wx1+src[rb0+xo2+c]*wx2+src[rb0+xo3+c]*wx3,r1=src[rb1+xo0+c]*wx0+src[rb1+xo1+c]*wx1+src[rb1+xo2+c]*wx2+src[rb1+xo3+c]*wx3,r2=src[rb2+xo0+c]*wx0+src[rb2+xo1+c]*wx1+src[rb2+xo2+c]*wx2+src[rb2+xo3+c]*wx3,r3=src[rb3+xo0+c]*wx0+src[rb3+xo1+c]*wx1+src[rb3+xo2+c]*wx2+src[rb3+xo3+c]*wx3,v=r0*wy0+r1*wy1+r2*wy2+r3*wy3;dst[di+c]=v<0?0:v>255?255:v|0}}}return{data:Buffer.from(dst.buffer),width:w2,height:h2}}_scaleImageToFitMessage(buffer,screenshotType){let MAX_PIXELS=12058624e-1,MAX_LINEAR_SIZE=1568,image=screenshotType==="png"?PNG.sync.read(buffer):jpegjs.decode(buffer,{maxMemoryUsageInMB:512}),pixels=image.width*image.height,shrink=Math.min(MAX_LINEAR_SIZE/image.width,MAX_LINEAR_SIZE/image.height,Math.sqrt(MAX_PIXELS/pixels));shrink>1&&(shrink=1);let width=image.width*shrink|0,height=image.height*shrink|0,scaledImage=this._scaleImageToSize(image,{width,height}),result,currentType=screenshotType,quality=screenshotType==="png"?75:70;screenshotType==="png"?(result=jpegjs.encode(scaledImage,quality).data,currentType="jpeg"):result=jpegjs.encode(scaledImage,quality).data;let iterations=0,MAX_ITERATIONS=5;for(;result.length>819200&&iterations<MAX_ITERATIONS;)quality=Math.max(50,quality-10),quality<=50&&result.length>819200&&(shrink*=.85,width=Math.max(200,image.width*shrink|0),height=Math.max(200,image.height*shrink|0),scaledImage=this._scaleImageToSize(image,{width,height})),result=jpegjs.encode(scaledImage,quality).data,iterations++;return result}async handle(context,args){let screenshotType=args.type||DEFAULT_SCREENSHOT_TYPE,filename=`${args.name||DEFAULT_SCREENSHOT_NAME}-${formattedTimeForFilename()}.${screenshotType}`,filePath=path2.resolve(args.outputPath,filename),quality=screenshotType==="png"?void 0:args.quality??DEFAULT_SCREENSHOT_QUALITY,options={path:filePath,type:screenshotType,fullPage:!!args.fullPage,quality};if(args.selector){let element=await context.page.$(args.selector);if(!element)throw new Error(`Element not found: ${args.selector}`);options.element=element}let screenshot=await context.page.screenshot(options),result={filePath};return args.includeBase64&&(result.image={data:this._scaleImageToFitMessage(screenshot,screenshotType),mimeType:`image/${screenshotType}`}),result}};var tools2=[new GetAsHtml,new GetAsText,new SaveAsPdf,new TakeScreenshot];import{z as z7}from"zod";var DEFAULT_DEBUG_CONFIG={maxSnapshots:1e3,maxCallStackDepth:20,maxFramesWithScopes:5,maxAsyncStackSegments:10,maxFramesPerAsyncSegment:10,maxDOMMutations:100,maxDOMHtmlSnippetLength:200,maxPendingRequests:1e3,maxResponseBodyLength:1e4,networkCleanupTimeoutMs:5e3},STORE_BY_CONTEXT=new WeakMap;function _generateId(){let t=Date.now(),r=Math.floor(Math.random()*1e6);return`${t.toString(36)}-${r.toString(36)}`}__name(_generateId,"_generateId");function _evaluateHitCondition(hitCondition,hitCount){try{let condition=hitCondition.trim();return/^[=<>!%]/.test(condition)&&(condition=`hitCount ${condition}`),!!new Function("hitCount",`return (${condition});`)(hitCount)}catch{return!1}}__name(_evaluateHitCondition,"_evaluateHitCondition");async function _evaluateWatchExpressionsOnFrame(v8Api,callFrameId,watchExpressions){let results={};for(let watch of watchExpressions.values())try{let result=await v8Api.evaluateOnCallFrame(callFrameId,watch.expression);if(result.exceptionDetails)results[watch.expression]=`[Error: ${result.exceptionDetails.text||"Evaluation failed"}]`;else{let value=await v8Api.extractValueDeep(result.result,2);results[watch.expression]=value}}catch(e){results[watch.expression]=`[Error: ${e.message||"Unknown error"}]`}return results}__name(_evaluateWatchExpressionsOnFrame,"_evaluateWatchExpressionsOnFrame");function _ensureStore(ctx,page,v8Options,config){let existing=STORE_BY_CONTEXT.get(ctx);if(existing)return existing;let v8Api=new V8Api(page,v8Options),sourceMapResolver=new SourceMapResolver(page),mergedConfig={...DEFAULT_DEBUG_CONFIG,...config},store={v8Api,sourceMapResolver,probes:new Map,watchExpressions:new Map,domBreakpoints:new Map,networkBreakpoints:new Map,snapshots:[],snapshotSequence:0,config:mergedConfig,enabled:!1,sourceMapsLoaded:!1,exceptionBreakpoint:"none",networkInterceptionEnabled:!1,recentDOMMutations:[]};return STORE_BY_CONTEXT.set(ctx,store),store}__name(_ensureStore,"_ensureStore");function _getStore(ctx){return STORE_BY_CONTEXT.get(ctx)}__name(_getStore,"_getStore");async function _captureScopes(v8Api,callFrame,maxDepth=3){let scopeSnapshots=[];for(let scope of callFrame.scopeChain)if(!(scope.type==="global"||scope.type==="script"||scope.type==="with"||scope.type==="eval"||scope.type==="wasm-expression-stack")){if(scopeSnapshots.length>=maxDepth)break;try{let variables=await v8Api.getScopeVariables(scope),scopeVariables=[];for(let[name,value]of Object.entries(variables))scopeVariables.push({name,value,type:typeof value});scopeSnapshots.push({type:scope.type,name:scope.name,variables:scopeVariables})}catch{}}return scopeSnapshots}__name(_captureScopes,"_captureScopes");async function _callFrameToSnapshot(v8Api,frame,captureScopes,sourceMapResolver){let scopes=[];captureScopes&&(scopes=await _captureScopes(v8Api,frame));let originalLocation;if(sourceMapResolver){let resolved=sourceMapResolver.generatedToOriginal(frame.location.scriptId,frame.location.lineNumber,frame.location.columnNumber??0);resolved&&(originalLocation={source:resolved.source,line:resolved.line+1,column:resolved.column!==void 0?resolved.column+1:void 0,name:resolved.name})}return{functionName:frame.functionName||"(anonymous)",url:frame.url||"",lineNumber:frame.location.lineNumber+1,columnNumber:frame.location.columnNumber!==void 0?frame.location.columnNumber+1:void 0,scriptId:frame.location.scriptId,scopes,originalLocation}}__name(_callFrameToSnapshot,"_callFrameToSnapshot");function _convertAsyncStackTrace(asyncTrace,sourceMapResolver,maxSegments,maxFramesPerSegment){if(!asyncTrace)return;let maxSegs=maxSegments??DEFAULT_DEBUG_CONFIG.maxAsyncStackSegments,maxFrames=maxFramesPerSegment??DEFAULT_DEBUG_CONFIG.maxFramesPerAsyncSegment,segments=[],currentTrace=asyncTrace,segmentCount=0;for(;currentTrace&&segmentCount<maxSegs;){let asyncFrames=[];for(let frame of currentTrace.callFrames.slice(0,maxFrames)){let originalLocation;if(sourceMapResolver){let resolved=sourceMapResolver.generatedToOriginal(frame.location.scriptId,frame.location.lineNumber,frame.location.columnNumber??0);resolved&&(originalLocation={source:resolved.source,line:resolved.line+1,column:resolved.column!==void 0?resolved.column+1:void 0,name:resolved.name})}asyncFrames.push({functionName:frame.functionName||"(anonymous)",url:frame.url||"",lineNumber:frame.location.lineNumber+1,columnNumber:frame.location.columnNumber!==void 0?frame.location.columnNumber+1:void 0,originalLocation})}asyncFrames.length>0&&segments.push({description:currentTrace.description,callFrames:asyncFrames}),currentTrace=currentTrace.parent,segmentCount++}if(segments.length!==0)return{segments}}__name(_convertAsyncStackTrace,"_convertAsyncStackTrace");async function enableDebugging2(ctx,page,options){let store=_ensureStore(ctx,page,options?.v8Options,options?.config);if(!store.enabled){await store.v8Api.enable(),store.v8Api.on("scriptParsed",script=>{store.sourceMapResolver.registerScript(script)});for(let script of store.v8Api.getScripts())store.sourceMapResolver.registerScript(script);store.v8Api.on("paused",async event=>{let startTime=Date.now();try{let isException=event.reason==="exception"||event.reason==="promiseRejection",isDOMBreakpoint=event.reason==="DOM",hitBreakpointIds=event.hitBreakpoints||[],hitProbe,hitConditionMet=!0,hitDOMBreakpoint,domChangeInfo;if(isDOMBreakpoint&&event.data){let domData=event.data;for(let domBp of store.domBreakpoints.values())if(domBp.enabled&&(domBp.nodeId===domData.nodeId||!domData.nodeId)){hitDOMBreakpoint=domBp,domChangeInfo={type:domBp.type,selector:domBp.selector,targetNode:domData.targetNode?`<${domData.targetNode.nodeName?.toLowerCase()||"unknown"}>`:void 0,attributeName:domData.attributeName||domBp.attributeName};break}}if(hitDOMBreakpoint&&domChangeInfo)try{let mutationData=await page.evaluate(breakpointId=>{let win=window;if(!win.__domBreakpointMutations)return null;let mutations=win.__domBreakpointMutations;for(let i=mutations.length-1;i>=0;i--)if(mutations[i].breakpointId===breakpointId)return mutations[i];return null},hitDOMBreakpoint.id);mutationData&&(domChangeInfo.oldValue=mutationData.oldValue,domChangeInfo.newValue=mutationData.newValue,domChangeInfo.targetNode=mutationData.targetOuterHTML,mutationData.attributeName&&(domChangeInfo.attributeName=mutationData.attributeName))}catch{}for(let probe of store.probes.values()){if(!probe.enabled)continue;if(probe.v8BreakpointIds.some(id=>hitBreakpointIds.includes(id))){hitProbe=probe,probe.hitCondition&&(hitConditionMet=_evaluateHitCondition(probe.hitCondition,probe.hitCount+1));break}}let shouldCaptureBreakpoint=hitProbe!==void 0&&hitConditionMet,shouldCaptureException=isException&&store.exceptionBreakpoint!=="none",shouldCaptureDOMBreakpoint=hitDOMBreakpoint!==void 0;if(hitProbe&&(hitProbe.hitCount++,hitProbe.lastHitAt=Date.now()),hitDOMBreakpoint&&(hitDOMBreakpoint.hitCount++,hitDOMBreakpoint.lastHitAt=Date.now()),(shouldCaptureBreakpoint||shouldCaptureException||shouldCaptureDOMBreakpoint)&&event.callFrames.length>0){let topFrame=event.callFrames[0],logResult;if(hitProbe&&hitProbe.kind==="logpoint"&&hitProbe.logExpression)try{let evalResult=await store.v8Api.evaluateOnCallFrame(topFrame.callFrameId,hitProbe.logExpression,{returnByValue:!0,generatePreview:!0});logResult=store.v8Api.extractValue(evalResult.result)}catch{logResult="[evaluation error]"}let exceptionInfo;if(isException&&event.data){let excData=event.data;exceptionInfo={type:event.reason==="promiseRejection"?"promiseRejection":"exception",message:excData.description||excData.value||String(excData),name:excData.className,stack:excData.description}}let originalLocation,resolved=store.sourceMapResolver.generatedToOriginal(topFrame.location.scriptId,topFrame.location.lineNumber,topFrame.location.columnNumber??0);resolved&&(originalLocation={source:resolved.source,line:resolved.line+1,column:resolved.column!==void 0?resolved.column+1:void 0,name:resolved.name});let probeId=hitProbe?.id??hitDOMBreakpoint?.id??"__exception__",isLogpoint=hitProbe?.kind==="logpoint",callStack=[];if(!isLogpoint){let framesToProcess=event.callFrames.slice(0,store.config.maxCallStackDepth);for(let i=0;i<framesToProcess.length;i++){let frame=framesToProcess[i],captureScopes=i<store.config.maxFramesWithScopes,snapshotFrame=await _callFrameToSnapshot(store.v8Api,frame,captureScopes,store.sourceMapResolver);callStack.push(snapshotFrame)}}let asyncStackTrace;isLogpoint||(asyncStackTrace=_convertAsyncStackTrace(event.asyncStackTrace,store.sourceMapResolver,store.config.maxAsyncStackSegments,store.config.maxFramesPerAsyncSegment));let watchResults;!isLogpoint&&store.watchExpressions.size>0&&(watchResults=await _evaluateWatchExpressionsOnFrame(store.v8Api,topFrame.callFrameId,store.watchExpressions));let snapshot={id:_generateId(),probeId,timestamp:Date.now(),sequenceNumber:++store.snapshotSequence,url:topFrame.url||"",lineNumber:topFrame.location.lineNumber+1,columnNumber:topFrame.location.columnNumber!==void 0?topFrame.location.columnNumber+1:void 0,originalLocation,exception:exceptionInfo,domChange:domChangeInfo,callStack,asyncStackTrace,logResult,watchResults,captureTimeMs:Date.now()-startTime};store.snapshots.push(snapshot),store.snapshots.length>store.config.maxSnapshots&&store.snapshots.splice(0,store.snapshots.length-store.config.maxSnapshots)}}finally{await store.v8Api.resume()}}),store.enabled=!0,store.sourceMapResolver.loadAllSourceMaps().then(()=>{store.sourceMapsLoaded=!0}).catch(()=>{})}}__name(enableDebugging2,"enableDebugging");function isDebuggingEnabled2(ctx){return _getStore(ctx)?.enabled??!1}__name(isDebuggingEnabled2,"isDebuggingEnabled");async function resolveSourceLocation2(ctx,page,url,line,column=1){let store=_ensureStore(ctx,page);store.enabled||await enableDebugging2(ctx,page);let resolved=await store.sourceMapResolver.resolveLocationByUrl(url,line,column);return resolved?{source:resolved.source,line:resolved.line+1,column:resolved.column+1,name:resolved.name}:null}__name(resolveSourceLocation2,"resolveSourceLocation");async function setExceptionBreakpoint2(ctx,state){let store=_getStore(ctx);if(!store||!store.enabled)throw new Error("Debugging is not enabled");await store.v8Api.setPauseOnExceptions(state),store.exceptionBreakpoint=state}__name(setExceptionBreakpoint2,"setExceptionBreakpoint");function getExceptionBreakpoint2(ctx){return _getStore(ctx)?.exceptionBreakpoint??"none"}__name(getExceptionBreakpoint2,"getExceptionBreakpoint");function hasSourceMaps2(ctx){return _getStore(ctx)?.sourceMapResolver.hasSourceMaps()??!1}__name(hasSourceMaps2,"hasSourceMaps");async function createProbe2(ctx,options){let store=_getStore(ctx);if(!store||!store.enabled)throw new Error("Debugging is not enabled");let probeId=_generateId(),fullCondition;options.condition?fullCondition=`(${options.condition})`:fullCondition="true";let line0based=options.lineNumber-1,column0based=(options.columnNumber??1)-1,resolved=store.sourceMapResolver.originalToGenerated(options.urlPattern,line0based,column0based),breakpointId,resolvedLocationsCount=0;if(resolved)breakpointId=(await store.v8Api.setBreakpoint({scriptId:resolved.scriptId,lineNumber:resolved.location.line,columnNumber:resolved.location.column},fullCondition)).breakpointId,resolvedLocationsCount=1;else{let urlRegex=options.urlPattern.replace(/\\([.*+?^${}()|[\]\\/-])/g,"$1").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*").replace(/\\\?/g,"."),result=await store.v8Api.setBreakpointByUrl({urlRegex,lineNumber:options.lineNumber-1,columnNumber:options.columnNumber?options.columnNumber-1:void 0,condition:fullCondition});breakpointId=result.breakpointId,resolvedLocationsCount=result.locations.length}let probe={id:probeId,kind:options.kind,enabled:!0,urlPattern:options.urlPattern,lineNumber:options.lineNumber,columnNumber:options.columnNumber,condition:options.condition,logExpression:options.logExpression,hitCondition:options.hitCondition,v8BreakpointIds:[breakpointId],resolvedLocations:resolvedLocationsCount,hitCount:0,createdAt:Date.now()};return store.probes.set(probeId,probe),probe}__name(createProbe2,"createProbe");async function removeProbe2(ctx,probeId){let store=_getStore(ctx);if(!store)return!1;let probe=store.probes.get(probeId);if(!probe)return!1;for(let v8Id of probe.v8BreakpointIds)try{await store.v8Api.removeBreakpoint(v8Id)}catch{}return store.probes.delete(probeId),!0}__name(removeProbe2,"removeProbe");function listProbes2(ctx){let store=_getStore(ctx);return store?Array.from(store.probes.values()):[]}__name(listProbes2,"listProbes");function getProbe(ctx,probeId){let store=_getStore(ctx);if(store)return store.probes.get(probeId)}__name(getProbe,"getProbe");function getSnapshots2(ctx){let store=_getStore(ctx);return store?[...store.snapshots]:[]}__name(getSnapshots2,"getSnapshots");function getSnapshotsByProbe2(ctx,probeId){let store=_getStore(ctx);return store?store.snapshots.filter(s=>s.probeId===probeId):[]}__name(getSnapshotsByProbe2,"getSnapshotsByProbe");function clearSnapshotsByProbe(ctx,probeId){let store=_getStore(ctx);if(!store)return 0;let before=store.snapshots.length;return store.snapshots=store.snapshots.filter(s=>s.probeId!==probeId),before-store.snapshots.length}__name(clearSnapshotsByProbe,"clearSnapshotsByProbe");function getSnapshotStats2(ctx){let store=_getStore(ctx);if(!store||store.snapshots.length===0)return{totalSnapshots:0,snapshotsByProbe:{},averageCaptureTimeMs:0};let snapshotsByProbe={},totalCaptureTime=0;for(let snapshot of store.snapshots)snapshotsByProbe[snapshot.probeId]=(snapshotsByProbe[snapshot.probeId]||0)+1,totalCaptureTime+=snapshot.captureTimeMs;return{totalSnapshots:store.snapshots.length,snapshotsByProbe,oldestTimestamp:store.snapshots[0].timestamp,newestTimestamp:store.snapshots[store.snapshots.length-1].timestamp,averageCaptureTimeMs:totalCaptureTime/store.snapshots.length}}__name(getSnapshotStats2,"getSnapshotStats");function addWatchExpression2(ctx,expression){let store=_getStore(ctx);if(!store)throw new Error("Debug store not initialized");let id=_generateId(),watchExpr={id,expression,createdAt:Date.now()};return store.watchExpressions.set(id,watchExpr),watchExpr}__name(addWatchExpression2,"addWatchExpression");function removeWatchExpression2(ctx,watchExpressionId){let store=_getStore(ctx);return store?store.watchExpressions.delete(watchExpressionId):!1}__name(removeWatchExpression2,"removeWatchExpression");function listWatchExpressions2(ctx){let store=_getStore(ctx);return store?Array.from(store.watchExpressions.values()):[]}__name(listWatchExpressions2,"listWatchExpressions");function clearWatchExpressions2(ctx){let store=_getStore(ctx);if(!store)return 0;let count=store.watchExpressions.size;return store.watchExpressions.clear(),count}__name(clearWatchExpressions2,"clearWatchExpressions");async function setDOMBreakpoint(ctx,page,options){let store=_getStore(ctx);if(!store||!store.enabled)throw new Error("Debugging is not enabled");let cdp=await store.v8Api.getCdp();await cdp.send("DOM.enable");let{root}=await cdp.send("DOM.getDocument",{depth:0}),{nodeId}=await cdp.send("DOM.querySelector",{nodeId:root.nodeId,selector:options.selector});if(!nodeId||nodeId===0)throw new Error(`Element not found: ${options.selector}`);let cdpType=options.type==="subtree-modified"?"subtree-modified":options.type==="attribute-modified"?"attribute-modified":"node-removed";await cdp.send("DOMDebugger.setDOMBreakpoint",{nodeId,type:cdpType});let id=_generateId(),domBreakpoint={id,selector:options.selector,type:options.type,attributeName:options.attributeName,enabled:!0,nodeId,hitCount:0,createdAt:Date.now()};return store.domBreakpoints.set(id,domBreakpoint),await page.evaluate(params=>{let selector=params.selector,breakpointId=params.breakpointId,type=params.type,attrName=params.attrName,maxMutations=params.maxMutations,maxHtmlSnippetLength=params.maxHtmlSnippetLength,element=document.querySelector(selector);if(!element)return;let win=window;win.__domBreakpointData=win.__domBreakpointData||{},win.__domBreakpointMutations=win.__domBreakpointMutations||[],win.__domBreakpointData[breakpointId]={selector,type,attrName,currentAttrs:{}};for(let attr of element.attributes)win.__domBreakpointData[breakpointId].currentAttrs[attr.name]=attr.value;let observer=new MutationObserver(mutations=>{for(let mutation of mutations){let target=mutation.target;if(mutation.type==="attributes"){let attrNameChanged=mutation.attributeName||"";if(attrName&&attrName!==attrNameChanged)continue;let mutationRecord={breakpointId,selector,type:"attribute-modified",attributeName:attrNameChanged,oldValue:mutation.oldValue,newValue:target.getAttribute(attrNameChanged),targetOuterHTML:target.outerHTML.substring(0,maxHtmlSnippetLength),timestamp:Date.now()};win.__domBreakpointMutations.push(mutationRecord),win.__domBreakpointMutations.length>maxMutations&&win.__domBreakpointMutations.shift(),win.__domBreakpointData[breakpointId].currentAttrs[attrNameChanged]=target.getAttribute(attrNameChanged)}else if(mutation.type==="childList"){let mutationRecord={breakpointId,selector,type:"subtree-modified",addedNodes:mutation.addedNodes.length,removedNodes:mutation.removedNodes.length,targetOuterHTML:target.outerHTML.substring(0,maxHtmlSnippetLength),timestamp:Date.now()};win.__domBreakpointMutations.push(mutationRecord),win.__domBreakpointMutations.length>maxMutations&&win.__domBreakpointMutations.shift()}}}),config={attributes:type==="attribute-modified",attributeOldValue:type==="attribute-modified",childList:type==="subtree-modified"||type==="node-removed",subtree:type==="subtree-modified"};attrName&&(config.attributeFilter=[attrName]),observer.observe(element,config),win.__domBreakpointObservers=win.__domBreakpointObservers||{},win.__domBreakpointObservers[breakpointId]=observer},{selector:options.selector,breakpointId:id,type:options.type,attrName:options.attributeName,maxMutations:store.config.maxDOMMutations,maxHtmlSnippetLength:store.config.maxDOMHtmlSnippetLength}),domBreakpoint}__name(setDOMBreakpoint,"setDOMBreakpoint");async function removeDOMBreakpoint(ctx,domBreakpointId,page){let store=_getStore(ctx);if(!store)return!1;let domBreakpoint=store.domBreakpoints.get(domBreakpointId);if(!domBreakpoint||!domBreakpoint.nodeId)return!1;try{let cdp=await store.v8Api.getCdp(),cdpType=domBreakpoint.type==="subtree-modified"?"subtree-modified":domBreakpoint.type==="attribute-modified"?"attribute-modified":"node-removed";await cdp.send("DOMDebugger.removeDOMBreakpoint",{nodeId:domBreakpoint.nodeId,type:cdpType})}catch{}if(page)try{await page.evaluate(breakpointId=>{let win=window;win.__domBreakpointObservers&&win.__domBreakpointObservers[breakpointId]&&(win.__domBreakpointObservers[breakpointId].disconnect(),delete win.__domBreakpointObservers[breakpointId]),win.__domBreakpointData&&delete win.__domBreakpointData[breakpointId],win.__domBreakpointMutations&&(win.__domBreakpointMutations=win.__domBreakpointMutations.filter(m=>m.breakpointId!==breakpointId))},domBreakpointId)}catch{}return store.domBreakpoints.delete(domBreakpointId)}__name(removeDOMBreakpoint,"removeDOMBreakpoint");function listDOMBreakpoints(ctx){let store=_getStore(ctx);return store?Array.from(store.domBreakpoints.values()):[]}__name(listDOMBreakpoints,"listDOMBreakpoints");async function clearDOMBreakpoints(ctx,page){let store=_getStore(ctx);if(!store)return 0;let ids=Array.from(store.domBreakpoints.keys());for(let id of ids)await removeDOMBreakpoint(ctx,id,page);return ids.length}__name(clearDOMBreakpoints,"clearDOMBreakpoints");async function _enableNetworkInterception(store,page){if(store.networkInterceptionEnabled)return;let cdp=await store.v8Api.getCdp();await cdp.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]}),cdp.on("Fetch.requestPaused",async event=>{let requestId=event.requestId,requestUrl=event.request.url,method=event.request.method;try{let matchedBreakpoint;for(let bp of store.networkBreakpoints.values()){if(!bp.enabled)continue;let unescapedPattern=bp.urlPattern.replace(/\\([.*+?^${}()|[\]\\/-])/g,"$1");if(new RegExp(unescapedPattern.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")).test(requestUrl)&&!(bp.method&&bp.method.toUpperCase()!==method.toUpperCase())&&bp.timing==="request"){matchedBreakpoint=bp;break}}if(matchedBreakpoint&&matchedBreakpoint.timing==="request"){let requestInfo={url:requestUrl,method,requestHeaders:event.request.headers,requestBody:event.request.postData,resourceType:event.resourceType,timing:"request"},snapshot={id:_generateId(),probeId:matchedBreakpoint.id,timestamp:Date.now(),sequenceNumber:++store.snapshotSequence,url:requestUrl,lineNumber:0,networkRequest:requestInfo,callStack:[],captureTimeMs:0};store.watchExpressions.size>0&&(snapshot.watchResults=await _evaluateWatchExpressions(store,page)),store.snapshots.push(snapshot),store.snapshots.length>store.config.maxSnapshots&&store.snapshots.splice(0,store.snapshots.length-store.config.maxSnapshots),matchedBreakpoint.hitCount++,matchedBreakpoint.lastHitAt=Date.now()}await cdp.send("Fetch.continueRequest",{requestId})}catch{try{await cdp.send("Fetch.continueRequest",{requestId})}catch{}}}),await cdp.send("Network.enable");let pendingRequests=new Map;cdp.on("Network.requestWillBeSent",event=>{if(pendingRequests.set(event.requestId,{method:event.request.method,postData:event.request.postData}),pendingRequests.size>store.config.maxPendingRequests){let firstKey=pendingRequests.keys().next().value;firstKey&&pendingRequests.delete(firstKey)}}),cdp.on("Network.responseReceived",async event=>{let requestId=event.requestId,requestUrl=event.response.url,requestInfo=pendingRequests.get(requestId),method=requestInfo?.method||event.type||"GET",status=event.response.status;for(let bp of store.networkBreakpoints.values()){if(!bp.enabled||bp.timing!=="response")continue;let unescapedPattern=bp.urlPattern.replace(/\\([.*+?^${}()|[\]\\/-])/g,"$1");if(!new RegExp(unescapedPattern.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")).test(requestUrl)||bp.method&&bp.method.toUpperCase()!==method.toUpperCase()||bp.onError&&status<400)continue;let responseBody;try{let bodyResult=await cdp.send("Network.getResponseBody",{requestId});bodyResult.base64Encoded?responseBody=Buffer.from(bodyResult.body,"base64").toString("utf-8"):responseBody=bodyResult.body,responseBody&&responseBody.length>store.config.maxResponseBodyLength&&(responseBody=responseBody.substring(0,store.config.maxResponseBodyLength)+"... [truncated]")}catch{}let networkRequestInfo={url:requestUrl,method,requestBody:requestInfo?.postData,status,statusText:event.response.statusText,responseHeaders:event.response.headers,responseBody,resourceType:event.type,timing:"response"},snapshot={id:_generateId(),probeId:bp.id,timestamp:Date.now(),sequenceNumber:++store.snapshotSequence,url:requestUrl,lineNumber:0,networkRequest:networkRequestInfo,callStack:[],captureTimeMs:0};store.watchExpressions.size>0&&(snapshot.watchResults=await _evaluateWatchExpressions(store,page)),store.snapshots.push(snapshot),store.snapshots.length>store.config.maxSnapshots&&store.snapshots.splice(0,store.snapshots.length-store.config.maxSnapshots),bp.hitCount++,bp.lastHitAt=Date.now(),pendingRequests.delete(requestId);break}}),cdp.on("Network.loadingFinished",event=>{setTimeout(()=>{pendingRequests.delete(event.requestId)},store.config.networkCleanupTimeoutMs)}),store.networkInterceptionEnabled=!0}__name(_enableNetworkInterception,"_enableNetworkInterception");async function _evaluateWatchExpressions(store,page){let results={};for(let watch of store.watchExpressions.values())try{let value=await page.evaluate(expr=>{try{return(0,eval)(expr)}catch(e){return`[Error: ${e.message}]`}},watch.expression);results[watch.expression]=value}catch(e){results[watch.expression]=`[Error: ${e.message}]`}return results}__name(_evaluateWatchExpressions,"_evaluateWatchExpressions");async function setNetworkBreakpoint(ctx,page,options){let store=_getStore(ctx);if(!store||!store.enabled)throw new Error("Debugging is not enabled");await _enableNetworkInterception(store,page);let id=_generateId(),networkBreakpoint={id,urlPattern:options.urlPattern,method:options.method,timing:options.timing||"request",onError:options.onError,enabled:!0,hitCount:0,createdAt:Date.now()};return store.networkBreakpoints.set(id,networkBreakpoint),networkBreakpoint}__name(setNetworkBreakpoint,"setNetworkBreakpoint");function removeNetworkBreakpoint(ctx,networkBreakpointId){let store=_getStore(ctx);return store?store.networkBreakpoints.delete(networkBreakpointId):!1}__name(removeNetworkBreakpoint,"removeNetworkBreakpoint");function listNetworkBreakpoints(ctx){let store=_getStore(ctx);return store?Array.from(store.networkBreakpoints.values()):[]}__name(listNetworkBreakpoints,"listNetworkBreakpoints");function clearNetworkBreakpoints(ctx){let store=_getStore(ctx);if(!store)return 0;let count=store.networkBreakpoints.size;return store.networkBreakpoints.clear(),count}__name(clearNetworkBreakpoints,"clearNetworkBreakpoints");var Status=class{static{__name(this,"Status")}name(){return"debug_status"}description(){return`
|
|
273
|
-
Returns the current debugging status including:
|
|
274
|
-
- Whether debugging is enabled
|
|
275
|
-
- Source map status
|
|
276
|
-
- Exceptionpoint state
|
|
277
|
-
- Count of tracepoints, logpoints, watches, dompoints and netpoints
|
|
278
|
-
- Snapshot statistics
|
|
279
|
-
`}inputSchema(){return{}}outputSchema(){return{enabled:z7.boolean().describe("Whether debugging is enabled"),hasSourceMaps:z7.boolean().describe("Whether source maps are loaded"),exceptionBreakpoint:z7.string().describe("Exceptionpoint state (none, uncaught, all)"),tracepointCount:z7.number().describe("Number of tracepoints"),logpointCount:z7.number().describe("Number of logpoints"),watchExpressionCount:z7.number().describe("Number of watch expressions"),dompointCount:z7.number().describe("Number of dompoints"),netpointCount:z7.number().describe("Number of netpoints"),snapshotStats:z7.object({totalSnapshots:z7.number(),snapshotsByProbe:z7.record(z7.number()),oldestTimestamp:z7.number().optional(),newestTimestamp:z7.number().optional(),averageCaptureTimeMs:z7.number()}).nullable().describe("Snapshot statistics")}}async handle(context,_args){if(!isDebuggingEnabled2(context.browserContext))return{enabled:!1,hasSourceMaps:!1,exceptionBreakpoint:"none",tracepointCount:0,logpointCount:0,watchExpressionCount:0,dompointCount:0,netpointCount:0,snapshotStats:null};let probes=listProbes2(context.browserContext),tracepointCount=probes.filter(p=>p.kind==="tracepoint").length,logpointCount=probes.filter(p=>p.kind==="logpoint").length;return{enabled:!0,hasSourceMaps:hasSourceMaps2(context.browserContext),exceptionBreakpoint:getExceptionBreakpoint2(context.browserContext),tracepointCount,logpointCount,watchExpressionCount:listWatchExpressions2(context.browserContext).length,dompointCount:listDOMBreakpoints(context.browserContext).length,netpointCount:listNetworkBreakpoints(context.browserContext).length,snapshotStats:getSnapshotStats2(context.browserContext)}}};import{z as z8}from"zod";var ResolveSourceLocation=class{static{__name(this,"ResolveSourceLocation")}name(){return"debug_resolve-source-location"}description(){return`
|
|
280
|
-
Resolves a generated/bundled code location to its original source via source maps.
|
|
281
|
-
Useful for translating minified stack traces or bundle line numbers to original TypeScript/JavaScript source.
|
|
282
|
-
|
|
283
|
-
Requires a page with debugging context (debugging is auto-enabled on first use).
|
|
284
|
-
Input: generated script URL, line, column (1-based).
|
|
285
|
-
Output: original source path, line, column when a source map is available.
|
|
286
|
-
`}inputSchema(){return{url:z8.string().describe("Generated script URL (e.g. https://example.com/bundle.js or relative path)"),line:z8.number().int().positive().describe("Line number in generated code (1-based)"),column:z8.number().int().nonnegative().describe("Column number in generated code (1-based, default 1)").optional()}}outputSchema(){return{resolved:z8.boolean().describe("Whether the location was resolved to original source"),source:z8.string().optional().describe("Original source file path"),line:z8.number().optional().describe("Line number in original source (1-based)"),column:z8.number().optional().describe("Column number in original source (1-based)"),name:z8.string().optional().describe("Original identifier name if available")}}async handle(context,args){let resolved=await resolveSourceLocation2(context.browserContext,context.page,args.url,args.line,args.column??1);return resolved?{resolved:!0,source:resolved.source,line:resolved.line,column:resolved.column,name:resolved.name}:{resolved:!1}}};import{z as z9}from"zod";var PutTracepoint=class{static{__name(this,"PutTracepoint")}name(){return"debug_put-tracepoint"}description(){return`
|
|
287
|
-
Puts a non-blocking tracepoint at the specified location.
|
|
288
|
-
When hit, a snapshot of the call stack and local variables is captured
|
|
289
|
-
automatically without pausing execution.
|
|
290
|
-
|
|
291
|
-
The urlPattern matches script URLs. Special characters are auto-escaped.
|
|
292
|
-
Examples:
|
|
293
|
-
- "app.js" matches scripts containing "app.js"
|
|
294
|
-
- "bundle.min.js" matches scripts containing "bundle.min.js"
|
|
295
|
-
|
|
296
|
-
DO NOT escape characters yourself (e.g., don't use "app\\.js").
|
|
297
|
-
|
|
298
|
-
Returns resolvedLocations: number of scripts where the tracepoint was set.
|
|
299
|
-
If 0, the pattern didn't match any loaded scripts.
|
|
300
|
-
`}inputSchema(){return{urlPattern:z9.string().describe('Script URL pattern (e.g., "app.js"). Auto-escaped, do not add backslashes.'),lineNumber:z9.number().int().positive().describe("Line number (1-based)"),columnNumber:z9.number().int().nonnegative().describe("Column number (1-based). Optional.").optional(),condition:z9.string().describe("Conditional expression - only triggers if this evaluates to true").optional(),hitCondition:z9.string().describe('Hit count condition, e.g., "== 5" (5th hit), ">= 10" (10th and after), "% 10 == 0" (every 10th)').optional()}}outputSchema(){return{id:z9.string().describe("Tracepoint ID"),urlPattern:z9.string().describe("URL pattern"),lineNumber:z9.number().describe("Line number"),columnNumber:z9.number().optional().describe("Column number"),condition:z9.string().optional().describe("Condition expression"),hitCondition:z9.string().optional().describe("Hit count condition"),resolvedLocations:z9.number().describe("Number of locations where tracepoint was resolved")}}async handle(context,args){isDebuggingEnabled2(context.browserContext)||await enableDebugging2(context.browserContext,context.page);let probe=await createProbe2(context.browserContext,{kind:"tracepoint",urlPattern:args.urlPattern,lineNumber:args.lineNumber,columnNumber:args.columnNumber,condition:args.condition,hitCondition:args.hitCondition});return{id:probe.id,urlPattern:probe.urlPattern,lineNumber:probe.lineNumber,columnNumber:probe.columnNumber,condition:probe.condition,hitCondition:probe.hitCondition,resolvedLocations:probe.resolvedLocations}}};import{z as z10}from"zod";var RemoveTracepoint=class{static{__name(this,"RemoveTracepoint")}name(){return"debug_remove-tracepoint"}description(){return"Removes a tracepoint by its ID."}inputSchema(){return{id:z10.string().describe("Tracepoint ID to remove")}}outputSchema(){return{success:z10.boolean().describe("Whether the tracepoint was removed"),message:z10.string().describe("Status message")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{success:!1,message:"No active tracepoints"};let probe=getProbe(context.browserContext,args.id);if(!probe||probe.kind!=="tracepoint")return{success:!1,message:`Tracepoint ${args.id} not found`};let removed=await removeProbe2(context.browserContext,args.id);return{success:removed,message:removed?`Tracepoint ${args.id} removed`:"Failed to remove tracepoint"}}};import{z as z11}from"zod";var ListTracepoints=class{static{__name(this,"ListTracepoints")}name(){return"debug_list-tracepoints"}description(){return"Lists all active tracepoints."}inputSchema(){return{}}outputSchema(){return{tracepoints:z11.array(z11.object({id:z11.string(),urlPattern:z11.string(),lineNumber:z11.number(),columnNumber:z11.number().optional(),condition:z11.string().optional(),hitCondition:z11.string().optional(),enabled:z11.boolean(),resolvedLocations:z11.number(),hitCount:z11.number(),lastHitAt:z11.number().optional()})).describe("List of tracepoints"),total:z11.number().describe("Total count")}}async handle(context,_args){if(!isDebuggingEnabled2(context.browserContext))return{tracepoints:[],total:0};let tracepoints=listProbes2(context.browserContext).filter(p=>p.kind==="tracepoint").map(p=>({id:p.id,urlPattern:p.urlPattern,lineNumber:p.lineNumber,columnNumber:p.columnNumber,condition:p.condition,hitCondition:p.hitCondition,enabled:p.enabled,resolvedLocations:p.resolvedLocations,hitCount:p.hitCount,lastHitAt:p.lastHitAt}));return{tracepoints,total:tracepoints.length}}};import{z as z12}from"zod";var ClearTracepoints=class{static{__name(this,"ClearTracepoints")}name(){return"debug_clear-tracepoints"}description(){return"Removes all tracepoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:z12.number().describe("Number of tracepoints cleared"),message:z12.string().describe("Status message")}}async handle(context,_args){if(!isDebuggingEnabled2(context.browserContext))return{clearedCount:0,message:"No tracepoints to clear"};let tracepoints=listProbes2(context.browserContext).filter(p=>p.kind==="tracepoint"),clearedCount=0;for(let tp of tracepoints)await removeProbe2(context.browserContext,tp.id)&&clearedCount++;return{clearedCount,message:`Cleared ${clearedCount} tracepoint(s)`}}};import{z as z13}from"zod";var PutLogpoint=class{static{__name(this,"PutLogpoint")}name(){return"debug_put-logpoint"}description(){return`
|
|
301
|
-
Puts a logpoint at the specified location.
|
|
302
|
-
When the logpoint is hit, the logExpression is evaluated and the result
|
|
303
|
-
is captured in the snapshot's logResult field.
|
|
304
|
-
|
|
305
|
-
Logpoints are lightweight - they only capture the log expression result,
|
|
306
|
-
NOT call stack or watch expressions. Use tracepoints for full debug context.
|
|
307
|
-
|
|
308
|
-
urlPattern matches script URLs (e.g., "app.js"). Auto-escaped, do not add backslashes.
|
|
309
|
-
|
|
310
|
-
logExpression examples:
|
|
311
|
-
- Simple value: "user.name"
|
|
312
|
-
- Template: "\`User: \${user.name}, Age: \${user.age}\`"
|
|
313
|
-
- Object: "{ user, timestamp: Date.now() }"
|
|
314
|
-
|
|
315
|
-
Returns resolvedLocations: 0 means pattern didn't match any loaded scripts.
|
|
316
|
-
`}inputSchema(){return{urlPattern:z13.string().describe('Script URL pattern (e.g., "app.js"). Auto-escaped, do not add backslashes.'),lineNumber:z13.number().int().positive().describe("Line number (1-based)"),logExpression:z13.string().describe("Expression to evaluate and log when hit"),columnNumber:z13.number().int().nonnegative().describe("Column number (1-based). Optional.").optional(),condition:z13.string().describe("Conditional expression - logpoint only hits if this evaluates to true").optional(),hitCondition:z13.string().describe('Hit count condition, e.g., "== 5" (5th hit), ">= 10" (10th and after), "% 10 == 0" (every 10th)').optional()}}outputSchema(){return{id:z13.string().describe("Debug point ID"),urlPattern:z13.string().describe("URL pattern"),lineNumber:z13.number().describe("Line number"),logExpression:z13.string().describe("Log expression"),columnNumber:z13.number().optional().describe("Column number"),condition:z13.string().optional().describe("Condition expression"),hitCondition:z13.string().optional().describe("Hit count condition"),resolvedLocations:z13.number().describe("Number of locations where logpoint was resolved")}}async handle(context,args){isDebuggingEnabled2(context.browserContext)||await enableDebugging2(context.browserContext,context.page);let probe=await createProbe2(context.browserContext,{kind:"logpoint",urlPattern:args.urlPattern,lineNumber:args.lineNumber,logExpression:args.logExpression,columnNumber:args.columnNumber,condition:args.condition,hitCondition:args.hitCondition});return{id:probe.id,urlPattern:probe.urlPattern,lineNumber:probe.lineNumber,logExpression:probe.logExpression||args.logExpression,columnNumber:probe.columnNumber,condition:probe.condition,hitCondition:probe.hitCondition,resolvedLocations:probe.resolvedLocations}}};import{z as z14}from"zod";var RemoveLogpoint=class{static{__name(this,"RemoveLogpoint")}name(){return"debug_remove-logpoint"}description(){return"Removes a logpoint by its ID."}inputSchema(){return{id:z14.string().describe("Logpoint ID to remove")}}outputSchema(){return{success:z14.boolean().describe("Whether the logpoint was removed"),message:z14.string().describe("Status message")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{success:!1,message:"No active logpoints"};let probe=getProbe(context.browserContext,args.id);if(!probe||probe.kind!=="logpoint")return{success:!1,message:`Logpoint ${args.id} not found`};let removed=await removeProbe2(context.browserContext,args.id);return{success:removed,message:removed?`Logpoint ${args.id} removed`:"Failed to remove logpoint"}}};import{z as z15}from"zod";var ListLogpoints=class{static{__name(this,"ListLogpoints")}name(){return"debug_list-logpoints"}description(){return"Lists all active logpoints."}inputSchema(){return{}}outputSchema(){return{logpoints:z15.array(z15.object({id:z15.string(),urlPattern:z15.string(),lineNumber:z15.number(),logExpression:z15.string(),columnNumber:z15.number().optional(),condition:z15.string().optional(),hitCondition:z15.string().optional(),enabled:z15.boolean(),resolvedLocations:z15.number(),hitCount:z15.number(),lastHitAt:z15.number().optional()})).describe("List of logpoints"),total:z15.number().describe("Total count")}}async handle(context,_args){if(!isDebuggingEnabled2(context.browserContext))return{logpoints:[],total:0};let logpoints=listProbes2(context.browserContext).filter(p=>p.kind==="logpoint").map(p=>({id:p.id,urlPattern:p.urlPattern,lineNumber:p.lineNumber,logExpression:p.logExpression||"",columnNumber:p.columnNumber,condition:p.condition,hitCondition:p.hitCondition,enabled:p.enabled,resolvedLocations:p.resolvedLocations,hitCount:p.hitCount,lastHitAt:p.lastHitAt}));return{logpoints,total:logpoints.length}}};import{z as z16}from"zod";var ClearLogpoints=class{static{__name(this,"ClearLogpoints")}name(){return"debug_clear-logpoints"}description(){return"Removes all logpoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:z16.number().describe("Number of logpoints cleared"),message:z16.string().describe("Status message")}}async handle(context,_args){if(!isDebuggingEnabled2(context.browserContext))return{clearedCount:0,message:"No logpoints to clear"};let logpoints=listProbes2(context.browserContext).filter(p=>p.kind==="logpoint"),clearedCount=0;for(let lp of logpoints)await removeProbe2(context.browserContext,lp.id)&&clearedCount++;return{clearedCount,message:`Cleared ${clearedCount} logpoint(s)`}}};import{z as z17}from"zod";var PutExceptionpoint=class{static{__name(this,"PutExceptionpoint")}name(){return"debug_put-exceptionpoint"}description(){return`
|
|
317
|
-
Sets the exception tracepoint state:
|
|
318
|
-
- "none": Don't capture on exceptions
|
|
319
|
-
- "uncaught": Capture only on uncaught exceptions
|
|
320
|
-
- "all": Capture on all exceptions (caught and uncaught)
|
|
321
|
-
|
|
322
|
-
When an exception occurs, a snapshot is captured with exception details.
|
|
323
|
-
`}inputSchema(){return{state:z17.enum(["none","uncaught","all"]).describe("Exception tracepoint state")}}outputSchema(){return{previousState:z17.string().describe("Previous state"),currentState:z17.string().describe("Current state"),message:z17.string().describe("Status message")}}async handle(context,args){isDebuggingEnabled2(context.browserContext)||await enableDebugging2(context.browserContext,context.page);let previousState=getExceptionBreakpoint2(context.browserContext);await setExceptionBreakpoint2(context.browserContext,args.state);let currentState=getExceptionBreakpoint2(context.browserContext);return{previousState,currentState,message:`Exception tracepoint set to: ${currentState}`}}};import{z as z19}from"zod";import{z as z18}from"zod";var OriginalLocationSchema=z18.object({source:z18.string().describe("Original source file path"),line:z18.number().describe("1-based line number"),column:z18.number().optional().describe("1-based column number"),name:z18.string().optional().describe("Original identifier name")}),ScopeVariableSchema=z18.object({name:z18.string().describe("Variable name"),value:z18.any().describe("Variable value"),type:z18.string().describe("Variable type")}),ScopeSnapshotSchema=z18.object({type:z18.string().describe("Scope type (global, local, closure, etc.)"),name:z18.string().optional().describe("Scope name"),variables:z18.array(ScopeVariableSchema).describe("Variables in this scope")}),CallFrameSchema=z18.object({functionName:z18.string().describe("Function name"),url:z18.string().describe("Script URL"),lineNumber:z18.number().describe("1-based line number"),columnNumber:z18.number().optional().describe("1-based column number"),scriptId:z18.string().describe("V8 script ID"),scopes:z18.array(ScopeSnapshotSchema).describe("Variable scopes"),originalLocation:OriginalLocationSchema.optional().describe("Original source location")}),AsyncCallFrameSchema=z18.object({functionName:z18.string().describe("Function name"),url:z18.string().describe("Script URL"),lineNumber:z18.number().describe("1-based line number"),columnNumber:z18.number().optional().describe("1-based column number"),originalLocation:OriginalLocationSchema.optional().describe("Original source location")}),AsyncStackSegmentSchema=z18.object({description:z18.string().optional().describe("Async boundary (Promise.then, setTimeout, etc.)"),callFrames:z18.array(AsyncCallFrameSchema).describe("Frames in this segment")}),AsyncStackTraceSchema=z18.object({segments:z18.array(AsyncStackSegmentSchema).describe("Chain of async segments")}),SnapshotBaseSchema=z18.object({id:z18.string().describe("Snapshot ID"),probeId:z18.string().describe("Probe ID that triggered this snapshot"),timestamp:z18.number().describe("Unix timestamp (ms)"),sequenceNumber:z18.number().describe("Monotonic sequence number for ordering"),url:z18.string().describe("Script URL where snapshot was taken"),lineNumber:z18.number().describe("1-based line number"),columnNumber:z18.number().optional().describe("1-based column number"),originalLocation:OriginalLocationSchema.optional().describe("Original source location"),captureTimeMs:z18.number().describe("Time taken to capture snapshot (ms)")}),TracepointSnapshotSchema=SnapshotBaseSchema.extend({callStack:z18.array(CallFrameSchema).describe("Call stack with local variables"),asyncStackTrace:AsyncStackTraceSchema.optional().describe("Async stack trace"),watchResults:z18.record(z18.any()).optional().describe("Watch expression results")}),LogpointSnapshotSchema=SnapshotBaseSchema.extend({logResult:z18.any().optional().describe("Result of log expression evaluation")}),ExceptionInfoSchema=z18.object({type:z18.enum(["exception","promiseRejection"]).describe("Exception type"),message:z18.string().describe("Exception message"),name:z18.string().optional().describe("Exception name/class"),stack:z18.string().optional().describe("Stack trace string")}),ExceptionpointSnapshotSchema=SnapshotBaseSchema.extend({exception:ExceptionInfoSchema.optional().describe("Exception information"),callStack:z18.array(CallFrameSchema).describe("Call stack at exception"),asyncStackTrace:AsyncStackTraceSchema.optional().describe("Async stack trace"),watchResults:z18.record(z18.any()).optional().describe("Watch expression results")}),DOMChangeInfoSchema=z18.object({type:z18.enum(["subtree-modified","attribute-modified","node-removed"]).describe("DOM mutation type"),selector:z18.string().describe("CSS selector of watched element"),targetNode:z18.string().optional().describe("Outer HTML snippet of target"),attributeName:z18.string().optional().describe("Changed attribute name"),oldValue:z18.string().optional().describe("Previous value"),newValue:z18.string().optional().describe("New value")}),DompointSnapshotSchema=SnapshotBaseSchema.extend({domChange:DOMChangeInfoSchema.optional().describe("DOM change information"),callStack:z18.array(CallFrameSchema).describe("Call stack when DOM changed"),asyncStackTrace:AsyncStackTraceSchema.optional().describe("Async stack trace"),watchResults:z18.record(z18.any()).optional().describe("Watch expression results")}),NetworkRequestInfoSchema=z18.object({url:z18.string().describe("Request URL"),method:z18.string().describe("HTTP method"),requestHeaders:z18.record(z18.string()).optional().describe("Request headers"),requestBody:z18.string().optional().describe("Request body"),status:z18.number().optional().describe("Response status code"),statusText:z18.string().optional().describe("Response status text"),responseHeaders:z18.record(z18.string()).optional().describe("Response headers"),responseBody:z18.string().optional().describe("Response body"),resourceType:z18.string().optional().describe("Resource type (xhr, fetch, etc.)"),timing:z18.enum(["request","response"]).describe("When snapshot was taken"),duration:z18.number().optional().describe("Request duration (ms)"),error:z18.string().optional().describe("Error message if failed")}),NetpointSnapshotSchema=SnapshotBaseSchema.extend({networkRequest:NetworkRequestInfoSchema.optional().describe("Network request/response info")});var GetTracepointSnapshots=class{static{__name(this,"GetTracepointSnapshots")}name(){return"debug_get-tracepoint-snapshots"}description(){return`
|
|
324
|
-
Retrieves snapshots captured by tracepoints.
|
|
325
|
-
|
|
326
|
-
Each snapshot contains:
|
|
327
|
-
- Call stack with local variables
|
|
328
|
-
- Async stack trace (if available)
|
|
329
|
-
- Original source location (if source maps loaded)
|
|
330
|
-
- Watch expression results
|
|
331
|
-
`}inputSchema(){return{probeId:z19.string().describe("Filter by specific tracepoint ID").optional(),fromSequence:z19.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:z19.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:z19.array(TracepointSnapshotSchema).describe("Array of tracepoint snapshots"),total:z19.number().describe("Total number of matching snapshots")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{snapshots:[],total:0};let snapshots;if(args.probeId)snapshots=getSnapshotsByProbe2(context.browserContext,args.probeId);else{let tracepointIds=new Set(listProbes2(context.browserContext).filter(p=>p.kind==="tracepoint").map(p=>p.id));snapshots=getSnapshots2(context.browserContext).filter(s=>tracepointIds.has(s.probeId))}args.fromSequence!==void 0&&(snapshots=snapshots.filter(s=>s.sequenceNumber>args.fromSequence));let total=snapshots.length;return args.limit&&snapshots.length>args.limit&&(snapshots=snapshots.slice(0,args.limit)),{snapshots,total}}};import{z as z20}from"zod";var ClearTracepointSnapshots=class{static{__name(this,"ClearTracepointSnapshots")}name(){return"debug_clear-tracepoint-snapshots"}description(){return"Clears snapshots captured by tracepoints. Optionally filter by specific tracepoint ID."}inputSchema(){return{probeId:z20.string().describe("Clear only snapshots for this tracepoint ID").optional()}}outputSchema(){return{clearedCount:z20.number().describe("Number of snapshots cleared"),message:z20.string().describe("Status message")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{clearedCount:0,message:"No snapshots to clear"};let clearedCount=0;if(args.probeId)clearedCount=clearSnapshotsByProbe(context.browserContext,args.probeId);else{let tracepointIds=listProbes2(context.browserContext).filter(p=>p.kind==="tracepoint").map(p=>p.id);for(let id of tracepointIds)clearedCount+=clearSnapshotsByProbe(context.browserContext,id)}return{clearedCount,message:`Cleared ${clearedCount} tracepoint snapshot(s)`}}};import{z as z21}from"zod";var GetLogpointSnapshots=class{static{__name(this,"GetLogpointSnapshots")}name(){return"debug_get-logpoint-snapshots"}description(){return`
|
|
332
|
-
Retrieves snapshots captured by logpoints.
|
|
333
|
-
|
|
334
|
-
Each snapshot contains:
|
|
335
|
-
- Log expression result
|
|
336
|
-
- Original source location (if source maps loaded)
|
|
337
|
-
- Timestamp and sequence number
|
|
338
|
-
|
|
339
|
-
Note: Logpoints do NOT capture call stack or watch expressions.
|
|
340
|
-
Use tracepoints if you need full debug context.
|
|
341
|
-
`}inputSchema(){return{probeId:z21.string().describe("Filter by specific logpoint ID").optional(),fromSequence:z21.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:z21.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:z21.array(LogpointSnapshotSchema).describe("Array of logpoint snapshots"),total:z21.number().describe("Total number of matching snapshots")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{snapshots:[],total:0};let snapshots;if(args.probeId)snapshots=getSnapshotsByProbe2(context.browserContext,args.probeId);else{let logpointIds=new Set(listProbes2(context.browserContext).filter(p=>p.kind==="logpoint").map(p=>p.id));snapshots=getSnapshots2(context.browserContext).filter(s=>logpointIds.has(s.probeId))}args.fromSequence!==void 0&&(snapshots=snapshots.filter(s=>s.sequenceNumber>args.fromSequence));let total=snapshots.length;return args.limit&&snapshots.length>args.limit&&(snapshots=snapshots.slice(0,args.limit)),{snapshots:snapshots.map(s=>({id:s.id,probeId:s.probeId,timestamp:s.timestamp,sequenceNumber:s.sequenceNumber,url:s.url,lineNumber:s.lineNumber,columnNumber:s.columnNumber,originalLocation:s.originalLocation,captureTimeMs:s.captureTimeMs,logResult:s.logResult})),total}}};import{z as z22}from"zod";var ClearLogpointSnapshots=class{static{__name(this,"ClearLogpointSnapshots")}name(){return"debug_clear-logpoint-snapshots"}description(){return"Clears snapshots captured by logpoints. Optionally filter by specific logpoint ID."}inputSchema(){return{probeId:z22.string().describe("Clear only snapshots for this logpoint ID").optional()}}outputSchema(){return{clearedCount:z22.number().describe("Number of snapshots cleared"),message:z22.string().describe("Status message")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{clearedCount:0,message:"No snapshots to clear"};let clearedCount=0;if(args.probeId)clearedCount=clearSnapshotsByProbe(context.browserContext,args.probeId);else{let logpointIds=listProbes2(context.browserContext).filter(p=>p.kind==="logpoint").map(p=>p.id);for(let id of logpointIds)clearedCount+=clearSnapshotsByProbe(context.browserContext,id)}return{clearedCount,message:`Cleared ${clearedCount} logpoint snapshot(s)`}}};import{z as z23}from"zod";var GetExceptionpointSnapshots=class{static{__name(this,"GetExceptionpointSnapshots")}name(){return"debug_get-exceptionpoint-snapshots"}description(){return`
|
|
342
|
-
Retrieves snapshots captured by exceptionpoints.
|
|
343
|
-
|
|
344
|
-
Each snapshot contains:
|
|
345
|
-
- Exception info (type, message, stack)
|
|
346
|
-
- Call stack with local variables at exception point
|
|
347
|
-
- Async stack trace (if available)
|
|
348
|
-
- Original source location (if source maps loaded)
|
|
349
|
-
- Watch expression results
|
|
350
|
-
`}inputSchema(){return{fromSequence:z23.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:z23.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:z23.array(ExceptionpointSnapshotSchema).describe("Array of exceptionpoint snapshots"),total:z23.number().describe("Total number of matching snapshots")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{snapshots:[],total:0};let snapshots=getSnapshotsByProbe2(context.browserContext,"__exception__");args.fromSequence!==void 0&&(snapshots=snapshots.filter(s=>s.sequenceNumber>args.fromSequence));let total=snapshots.length;return args.limit&&snapshots.length>args.limit&&(snapshots=snapshots.slice(0,args.limit)),{snapshots,total}}};import{z as z24}from"zod";var ClearExceptionpointSnapshots=class{static{__name(this,"ClearExceptionpointSnapshots")}name(){return"debug_clear-exceptionpoint-snapshots"}description(){return"Clears all snapshots captured by exceptionpoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:z24.number().describe("Number of snapshots cleared"),message:z24.string().describe("Status message")}}async handle(context,_args){if(!isDebuggingEnabled2(context.browserContext))return{clearedCount:0,message:"No snapshots to clear"};let clearedCount=clearSnapshotsByProbe(context.browserContext,"__exception__");return{clearedCount,message:`Cleared ${clearedCount} exceptionpoint snapshot(s)`}}};import{z as z25}from"zod";var GetDompointSnapshots=class{static{__name(this,"GetDompointSnapshots")}name(){return"debug_get-dompoint-snapshots"}description(){return`
|
|
351
|
-
Retrieves snapshots captured by dompoints.
|
|
352
|
-
|
|
353
|
-
Each snapshot contains:
|
|
354
|
-
- DOM change info (mutation type, target, old/new values)
|
|
355
|
-
- Call stack with local variables (if triggered during JS execution)
|
|
356
|
-
- Async stack trace (if available)
|
|
357
|
-
- Original source location (if source maps loaded)
|
|
358
|
-
- Watch expression results
|
|
359
|
-
`}inputSchema(){return{probeId:z25.string().describe("Filter by specific dompoint ID").optional(),fromSequence:z25.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:z25.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:z25.array(DompointSnapshotSchema).describe("Array of dompoint snapshots"),total:z25.number().describe("Total number of matching snapshots")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{snapshots:[],total:0};let snapshots;if(args.probeId)snapshots=getSnapshotsByProbe2(context.browserContext,args.probeId);else{let dompointIds=new Set(listDOMBreakpoints(context.browserContext).map(d=>d.id));snapshots=getSnapshots2(context.browserContext).filter(s=>dompointIds.has(s.probeId))}args.fromSequence!==void 0&&(snapshots=snapshots.filter(s=>s.sequenceNumber>args.fromSequence));let total=snapshots.length;return args.limit&&snapshots.length>args.limit&&(snapshots=snapshots.slice(0,args.limit)),{snapshots,total}}};import{z as z26}from"zod";var ClearDompointSnapshots=class{static{__name(this,"ClearDompointSnapshots")}name(){return"debug_clear-dompoint-snapshots"}description(){return"Clears snapshots captured by dompoints. If probeId is specified, only clears snapshots for that dompoint."}inputSchema(){return{probeId:z26.string().describe("Optional dompoint ID to clear snapshots for").optional()}}outputSchema(){return{clearedCount:z26.number().describe("Number of snapshots cleared"),message:z26.string().describe("Status message")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{clearedCount:0,message:"No snapshots to clear"};let clearedCount=0;if(args.probeId)clearedCount=clearSnapshotsByProbe(context.browserContext,args.probeId);else{let dompoints=listDOMBreakpoints(context.browserContext);for(let dompoint of dompoints)clearedCount+=clearSnapshotsByProbe(context.browserContext,dompoint.id)}return{clearedCount,message:`Cleared ${clearedCount} dompoint snapshot(s)`}}};import{z as z27}from"zod";var GetNetpointSnapshots=class{static{__name(this,"GetNetpointSnapshots")}name(){return"debug_get-netpoint-snapshots"}description(){return`
|
|
360
|
-
Retrieves snapshots captured by netpoints.
|
|
361
|
-
|
|
362
|
-
Each snapshot contains:
|
|
363
|
-
- Network request info (URL, method, headers, body)
|
|
364
|
-
- Response info (status, headers, body) when available
|
|
365
|
-
- Timing information
|
|
366
|
-
`}inputSchema(){return{probeId:z27.string().describe("Filter by specific netpoint ID").optional(),fromSequence:z27.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:z27.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:z27.array(NetpointSnapshotSchema).describe("Array of netpoint snapshots"),total:z27.number().describe("Total number of matching snapshots")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{snapshots:[],total:0};let snapshots;if(args.probeId)snapshots=getSnapshotsByProbe2(context.browserContext,args.probeId);else{let netpointIds=new Set(listNetworkBreakpoints(context.browserContext).map(n=>n.id));snapshots=getSnapshots2(context.browserContext).filter(s=>netpointIds.has(s.probeId))}args.fromSequence!==void 0&&(snapshots=snapshots.filter(s=>s.sequenceNumber>args.fromSequence));let total=snapshots.length;return args.limit&&snapshots.length>args.limit&&(snapshots=snapshots.slice(0,args.limit)),{snapshots,total}}};import{z as z28}from"zod";var ClearNetpointSnapshots=class{static{__name(this,"ClearNetpointSnapshots")}name(){return"debug_clear-netpoint-snapshots"}description(){return"Clears snapshots captured by netpoints. If probeId is specified, only clears snapshots for that netpoint."}inputSchema(){return{probeId:z28.string().describe("Optional netpoint ID to clear snapshots for").optional()}}outputSchema(){return{clearedCount:z28.number().describe("Number of snapshots cleared"),message:z28.string().describe("Status message")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{clearedCount:0,message:"No snapshots to clear"};let clearedCount=0;if(args.probeId)clearedCount=clearSnapshotsByProbe(context.browserContext,args.probeId);else{let netpoints=listNetworkBreakpoints(context.browserContext);for(let netpoint of netpoints)clearedCount+=clearSnapshotsByProbe(context.browserContext,netpoint.id)}return{clearedCount,message:`Cleared ${clearedCount} netpoint snapshot(s)`}}};import{z as z29}from"zod";var AddWatch=class{static{__name(this,"AddWatch")}name(){return"debug_add-watch"}description(){return`
|
|
367
|
-
Adds a watch expression to be evaluated at every breakpoint hit.
|
|
368
|
-
Watch expression results are included in the snapshot's watchResults field.
|
|
369
|
-
|
|
370
|
-
Examples:
|
|
371
|
-
- "user.name"
|
|
372
|
-
- "this.state"
|
|
373
|
-
- "items.length"
|
|
374
|
-
- "JSON.stringify(config)"
|
|
375
|
-
|
|
376
|
-
Watch expressions are evaluated in the context of the paused frame.
|
|
377
|
-
`}inputSchema(){return{expression:z29.string().describe("JavaScript expression to watch")}}outputSchema(){return{id:z29.string().describe("Watch expression ID"),expression:z29.string().describe("The watch expression"),message:z29.string().describe("Status message")}}async handle(context,args){isDebuggingEnabled2(context.browserContext)||await enableDebugging2(context.browserContext,context.page);let watch=addWatchExpression2(context.browserContext,args.expression);return{id:watch.id,expression:watch.expression,message:`Watch expression added: ${args.expression}`}}};import{z as z30}from"zod";var RemoveWatch=class{static{__name(this,"RemoveWatch")}name(){return"debug_remove-watch"}description(){return`
|
|
378
|
-
Removes a watch expression by its ID.
|
|
379
|
-
Use debug_list-watches to get the IDs of active watch expressions.
|
|
380
|
-
`}inputSchema(){return{id:z30.string().describe("Watch expression ID to remove")}}outputSchema(){return{success:z30.boolean().describe("Whether the watch was removed"),message:z30.string().describe("Status message")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{success:!1,message:"Debugging is not active"};let removed=removeWatchExpression2(context.browserContext,args.id);return{success:removed,message:removed?`Watch expression ${args.id} removed`:`Watch expression ${args.id} not found`}}};import{z as z31}from"zod";var ListWatches=class{static{__name(this,"ListWatches")}name(){return"debug_list-watches"}description(){return`
|
|
381
|
-
Lists all active watch expressions.
|
|
382
|
-
`}inputSchema(){return{}}outputSchema(){return{watches:z31.array(z31.object({id:z31.string(),expression:z31.string(),createdAt:z31.number()})).describe("List of watch expressions"),total:z31.number().describe("Total count")}}async handle(context,_args){if(!isDebuggingEnabled2(context.browserContext))return{watches:[],total:0};let watches=listWatchExpressions2(context.browserContext).map(w=>({id:w.id,expression:w.expression,createdAt:w.createdAt}));return{watches,total:watches.length}}};import{z as z32}from"zod";var ClearWatches=class{static{__name(this,"ClearWatches")}name(){return"debug_clear-watches"}description(){return`
|
|
383
|
-
Removes all watch expressions.
|
|
384
|
-
`}inputSchema(){return{}}outputSchema(){return{clearedCount:z32.number().describe("Number of watch expressions cleared"),message:z32.string().describe("Status message")}}async handle(context,_args){if(!isDebuggingEnabled2(context.browserContext))return{clearedCount:0,message:"No watch expressions to clear"};let clearedCount=clearWatchExpressions2(context.browserContext);return{clearedCount,message:`Cleared ${clearedCount} watch expression(s)`}}};import{z as z33}from"zod";var PutDompoint=class{static{__name(this,"PutDompoint")}name(){return"debug_put-dompoint"}description(){return`
|
|
385
|
-
Puts a DOM tracepoint that triggers when the element changes.
|
|
386
|
-
|
|
387
|
-
Types:
|
|
388
|
-
- "subtree-modified": Triggers when children are added/removed
|
|
389
|
-
- "attribute-modified": Triggers when attributes change
|
|
390
|
-
- "node-removed": Triggers when the element is removed
|
|
391
|
-
|
|
392
|
-
When triggered, a snapshot is captured with DOM change info.
|
|
393
|
-
|
|
394
|
-
Example:
|
|
395
|
-
- selector: "#myButton", type: "attribute-modified", attributeName: "disabled"
|
|
396
|
-
- selector: ".list-container", type: "subtree-modified"
|
|
397
|
-
`}inputSchema(){return{selector:z33.string().describe("CSS selector for the target element"),type:z33.enum(["subtree-modified","attribute-modified","node-removed"]).describe("Type of DOM change to monitor"),attributeName:z33.string().describe("For attribute-modified: specific attribute to monitor").optional()}}outputSchema(){return{id:z33.string().describe("Dompoint ID"),selector:z33.string().describe("CSS selector"),type:z33.string().describe("Dompoint type"),attributeName:z33.string().optional().describe("Monitored attribute"),nodeId:z33.number().optional().describe("CDP node ID"),message:z33.string().describe("Status message")}}async handle(context,args){isDebuggingEnabled2(context.browserContext)||await enableDebugging2(context.browserContext,context.page);let domBreakpoint=await setDOMBreakpoint(context.browserContext,context.page,{selector:args.selector,type:args.type,attributeName:args.attributeName});return{id:domBreakpoint.id,selector:domBreakpoint.selector,type:domBreakpoint.type,attributeName:domBreakpoint.attributeName,nodeId:domBreakpoint.nodeId,message:`Dompoint set on "${args.selector}" for ${args.type}`}}};import{z as z34}from"zod";var RemoveDompoint=class{static{__name(this,"RemoveDompoint")}name(){return"debug_remove-dompoint"}description(){return"Removes a dompoint by its ID."}inputSchema(){return{id:z34.string().describe("Dompoint ID to remove")}}outputSchema(){return{success:z34.boolean().describe("Whether the dompoint was removed"),message:z34.string().describe("Status message")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{success:!1,message:"No active dompoints"};let removed=await removeDOMBreakpoint(context.browserContext,args.id,context.page);return{success:removed,message:removed?`Dompoint ${args.id} removed`:`Dompoint ${args.id} not found`}}};import{z as z35}from"zod";var ListDompoints=class{static{__name(this,"ListDompoints")}name(){return"debug_list-dompoints"}description(){return"Lists all active dompoints."}inputSchema(){return{}}outputSchema(){return{dompoints:z35.array(z35.object({id:z35.string(),selector:z35.string(),type:z35.string(),attributeName:z35.string().optional(),enabled:z35.boolean(),hitCount:z35.number(),lastHitAt:z35.number().optional()})).describe("List of dompoints"),total:z35.number().describe("Total count")}}async handle(context,_args){if(!isDebuggingEnabled2(context.browserContext))return{dompoints:[],total:0};let dompoints=listDOMBreakpoints(context.browserContext).map(bp=>({id:bp.id,selector:bp.selector,type:bp.type,attributeName:bp.attributeName,enabled:bp.enabled,hitCount:bp.hitCount,lastHitAt:bp.lastHitAt}));return{dompoints,total:dompoints.length}}};import{z as z36}from"zod";var ClearDompoints=class{static{__name(this,"ClearDompoints")}name(){return"debug_clear-dompoints"}description(){return"Removes all dompoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:z36.number().describe("Number of dompoints cleared"),message:z36.string().describe("Status message")}}async handle(context,_args){if(!isDebuggingEnabled2(context.browserContext))return{clearedCount:0,message:"No dompoints to clear"};let clearedCount=await clearDOMBreakpoints(context.browserContext,context.page);return{clearedCount,message:`Cleared ${clearedCount} dompoint(s)`}}};import{z as z37}from"zod";var PutNetpoint=class{static{__name(this,"PutNetpoint")}name(){return"debug_put-netpoint"}description(){return`
|
|
398
|
-
Puts a network tracepoint that triggers on matching HTTP requests.
|
|
399
|
-
|
|
400
|
-
When triggered, a snapshot is captured with request/response details including:
|
|
401
|
-
- URL, method, headers
|
|
402
|
-
- Request body (for request timing)
|
|
403
|
-
- Response status, headers, body (for response timing)
|
|
404
|
-
|
|
405
|
-
Parameters:
|
|
406
|
-
- urlPattern: Glob pattern to match URLs (e.g., "**/api/**")
|
|
407
|
-
- method: Optional HTTP method filter (GET, POST, etc.)
|
|
408
|
-
- timing: "request" (before sent) or "response" (after received)
|
|
409
|
-
- onError: Only trigger on error responses (4xx, 5xx)
|
|
410
|
-
|
|
411
|
-
Examples:
|
|
412
|
-
- urlPattern: "**/api/users/**", timing: "response"
|
|
413
|
-
- urlPattern: "**/graphql", method: "POST", timing: "request"
|
|
414
|
-
`}inputSchema(){return{urlPattern:z37.string().describe("Glob pattern to match request URLs"),method:z37.string().describe("HTTP method filter (GET, POST, PUT, DELETE, etc.)").optional(),timing:z37.enum(["request","response"]).describe('When to trigger: "request" or "response". Default: "request"').optional().default("request"),onError:z37.boolean().describe("Only trigger on error responses (4xx, 5xx)").optional()}}outputSchema(){return{id:z37.string().describe("Netpoint ID"),urlPattern:z37.string().describe("URL pattern"),method:z37.string().optional().describe("HTTP method filter"),timing:z37.string().describe("Trigger timing"),onError:z37.boolean().optional().describe("Error-only filter"),message:z37.string().describe("Status message")}}async handle(context,args){isDebuggingEnabled2(context.browserContext)||await enableDebugging2(context.browserContext,context.page);let networkBreakpoint=await setNetworkBreakpoint(context.browserContext,context.page,{urlPattern:args.urlPattern,method:args.method,timing:args.timing||"request",onError:args.onError});return{id:networkBreakpoint.id,urlPattern:networkBreakpoint.urlPattern,method:networkBreakpoint.method,timing:networkBreakpoint.timing,onError:networkBreakpoint.onError,message:`Netpoint set for ${args.urlPattern} on ${args.timing||"request"}`}}};import{z as z38}from"zod";var RemoveNetpoint=class{static{__name(this,"RemoveNetpoint")}name(){return"debug_remove-netpoint"}description(){return"Removes a netpoint by its ID."}inputSchema(){return{id:z38.string().describe("Netpoint ID to remove")}}outputSchema(){return{success:z38.boolean().describe("Whether the netpoint was removed"),message:z38.string().describe("Status message")}}async handle(context,args){if(!isDebuggingEnabled2(context.browserContext))return{success:!1,message:"No active netpoints"};let removed=removeNetworkBreakpoint(context.browserContext,args.id);return{success:removed,message:removed?`Netpoint ${args.id} removed`:`Netpoint ${args.id} not found`}}};import{z as z39}from"zod";var ListNetpoints=class{static{__name(this,"ListNetpoints")}name(){return"debug_list-netpoints"}description(){return"Lists all active netpoints."}inputSchema(){return{}}outputSchema(){return{netpoints:z39.array(z39.object({id:z39.string(),urlPattern:z39.string(),method:z39.string().optional(),timing:z39.string(),onError:z39.boolean().optional(),enabled:z39.boolean(),hitCount:z39.number(),lastHitAt:z39.number().optional()})).describe("List of netpoints"),total:z39.number().describe("Total count")}}async handle(context,_args){if(!isDebuggingEnabled2(context.browserContext))return{netpoints:[],total:0};let netpoints=listNetworkBreakpoints(context.browserContext).map(bp=>({id:bp.id,urlPattern:bp.urlPattern,method:bp.method,timing:bp.timing,onError:bp.onError,enabled:bp.enabled,hitCount:bp.hitCount,lastHitAt:bp.lastHitAt}));return{netpoints,total:netpoints.length}}};import{z as z40}from"zod";var ClearNetpoints=class{static{__name(this,"ClearNetpoints")}name(){return"debug_clear-netpoints"}description(){return"Removes all netpoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:z40.number().describe("Number of netpoints cleared"),message:z40.string().describe("Status message")}}async handle(context,_args){if(!isDebuggingEnabled2(context.browserContext))return{clearedCount:0,message:"No netpoints to clear"};let clearedCount=clearNetworkBreakpoints(context.browserContext);return{clearedCount,message:`Cleared ${clearedCount} netpoint(s)`}}};var tools3=[new Status,new ResolveSourceLocation,new PutTracepoint,new RemoveTracepoint,new ListTracepoints,new ClearTracepoints,new PutLogpoint,new RemoveLogpoint,new ListLogpoints,new ClearLogpoints,new PutExceptionpoint,new GetTracepointSnapshots,new ClearTracepointSnapshots,new GetLogpointSnapshots,new ClearLogpointSnapshots,new GetExceptionpointSnapshots,new ClearExceptionpointSnapshots,new GetDompointSnapshots,new ClearDompointSnapshots,new GetNetpointSnapshots,new ClearNetpointSnapshots,new AddWatch,new RemoveWatch,new ListWatches,new ClearWatches,new PutDompoint,new RemoveDompoint,new ListDompoints,new ClearDompoints,new PutNetpoint,new RemoveNetpoint,new ListNetpoints,new ClearNetpoints];import sharp from"sharp";import ssim from"ssim.js";var DEFAULT_GRAYSCALE=!1,DEFAULT_BLUR=10;function _clamp01(v){return Number.isFinite(v)?Math.max(0,Math.min(1,v)):0}__name(_clamp01,"_clamp01");async function _loadNormalized(input,canvasWidth,canvasHeight,mode){let img;if(mode==="semantic"){img=sharp(input).resize(canvasWidth,canvasHeight,{fit:"cover",position:"centre"});let w=Math.max(1,Math.floor(canvasWidth/2)),h=Math.max(1,Math.floor(canvasHeight/2));img=img.resize(w,h,{fit:"cover",position:"centre"}).grayscale(DEFAULT_GRAYSCALE).blur(DEFAULT_BLUR)}else img=sharp(input).resize(canvasWidth,canvasHeight,{fit:"cover",position:"centre"});let out=await img.ensureAlpha().raw().toBuffer({resolveWithObject:!0});return{data:new Uint8ClampedArray(out.data.buffer,out.data.byteOffset,out.data.byteLength),width:out.info.width,height:out.info.height}}__name(_loadNormalized,"_loadNormalized");function _computeSsim(a,b){let details=ssim({data:a.data,width:a.width,height:a.height},{data:b.data,width:b.width,height:b.height}),rawScore=Number(details.mssim??details.ssim??0);return _clamp01(rawScore)}__name(_computeSsim,"_computeSsim");async function compare(page,figma,options){let mode=options?.mode??"semantic",canvasWidth=options?.canvasWidth,canvasHeight=options?.canvasHeight;if(typeof canvasWidth!="number"||!Number.isFinite(canvasWidth)||canvasWidth<=0||typeof canvasHeight!="number"||!Number.isFinite(canvasHeight)||canvasHeight<=0){let figmaMeta=await sharp(figma.image).metadata();if(canvasWidth=figmaMeta.width??0,canvasHeight=figmaMeta.height??0,canvasWidth<=0||canvasHeight<=0)throw new Error("Failed to read Figma image dimensions.")}let figmaImg=await _loadNormalized(figma.image,canvasWidth,canvasHeight,mode),pageImg=await _loadNormalized(page.image,canvasWidth,canvasHeight,mode);return{score:_computeSsim(figmaImg,pageImg)}}__name(compare,"compare");function dot(a,b){let n=Math.min(a.length,b.length),s=0;for(let i=0;i<n;i++)s+=a[i]*b[i];return s}__name(dot,"dot");function norm(a){let s=0;for(let i=0;i<a.length;i++){let x=a[i];s+=x*x}return Math.sqrt(s)}__name(norm,"norm");function l2Normalize(v){let n=norm(v);if(n===0)return v.slice();let out=new Array(v.length);for(let i=0;i<v.length;i++)out[i]=v[i]/n;return out}__name(l2Normalize,"l2Normalize");function cosineSimilarity(a,b,normalize){if(normalize){let na=l2Normalize(a),nb=l2Normalize(b);return dot(na,nb)}let denom=norm(a)*norm(b);return denom===0?0:dot(a,b)/denom}__name(cosineSimilarity,"cosineSimilarity");import{BedrockRuntimeClient,InvokeModelCommand}from"@aws-sdk/client-bedrock-runtime";import{fromIni}from"@aws-sdk/credential-providers";import sharp2 from"sharp";var DEFAULT_MAX_DIMENSION=1024,DEFAULT_JPEG_QUALITY=90,DEFAULT_AMAZON_BEDROCK_TITAN_OUTPUT_EMBEDDING_LENGTH=1024;async function _prepareImage(buf,imageType,opt){let img=sharp2(buf),maxDim=opt?.maxDim||DEFAULT_MAX_DIMENSION;if(img=img.resize({width:maxDim,height:maxDim,fit:"inside",withoutEnlargement:!0}),imageType==="png")return await img.png().toBuffer();let jpegQuality=opt?.jpegQuality||DEFAULT_JPEG_QUALITY;return await img.jpeg({quality:jpegQuality}).toBuffer()}__name(_prepareImage,"_prepareImage");var SUPPORTED_AMAZON_BEDROCK_IMAGE_EMBED_MODEL_IDS=new Set(["amazon.titan-embed-image-v1"]),DEFAULT_AMAZON_BEDROCK_IMAGE_EMBED_MODEL_ID="amazon.titan-embed-image-v1",_bedrockClient;function _isAwsBedrockActive(){return AMAZON_BEDROCK_ENABLE&&!!AWS_REGION}__name(_isAwsBedrockActive,"_isAwsBedrockActive");function _getOrCreateBedrockClient(){if(_bedrockClient)return _bedrockClient;let region=AWS_REGION;if(!region)return;let profile=AWS_PROFILE;return profile?(_bedrockClient=new BedrockRuntimeClient({region,credentials:fromIni({profile})}),_bedrockClient):(_bedrockClient=new BedrockRuntimeClient({region}),_bedrockClient)}__name(_getOrCreateBedrockClient,"_getOrCreateBedrockClient");async function _embedImageWithAmazonBedrockTitan(ss,client,opt,modelId){let bodyObj={inputImage:(await _prepareImage(ss.image,ss.type,opt)).toString("base64"),embeddingConfig:{outputEmbeddingLength:DEFAULT_AMAZON_BEDROCK_TITAN_OUTPUT_EMBEDDING_LENGTH}},cmd=new InvokeModelCommand({modelId,contentType:"application/json",accept:"application/json",body:Buffer.from(JSON.stringify(bodyObj),"utf-8")}),resp=await client.send(cmd),raw=resp?.body instanceof Uint8Array?resp.body:new Uint8Array(resp?.body??[]),text=Buffer.from(raw).toString("utf-8"),parsed;try{parsed=text?JSON.parse(text):{}}catch{throw new Error(`Amazon Bedrock Titan returned non-JSON response for embeddings: ${text.slice(0,300)}`)}let emb=parsed?.embedding??parsed?.embeddings?.[0]??parsed?.outputEmbedding??parsed?.vector;if(!Array.isArray(emb)||emb.length===0||typeof emb[0]!="number")throw new Error(`Unexpected Amazon Bedrock Titan image embedding response format: ${text.slice(0,500)}`);return emb}__name(_embedImageWithAmazonBedrockTitan,"_embedImageWithAmazonBedrockTitan");async function _embedImageWithAmazonBedrock(ss,opt,client){let modelId=opt?.modelId??AMAZON_BEDROCK_IMAGE_EMBED_MODEL_ID??DEFAULT_AMAZON_BEDROCK_IMAGE_EMBED_MODEL_ID;if(!SUPPORTED_AMAZON_BEDROCK_IMAGE_EMBED_MODEL_IDS.has(modelId))throw new Error(`Unsupported Amazon Bedrock image embedding model id: ${modelId}`);return await _embedImageWithAmazonBedrockTitan(ss,client,opt,modelId)}__name(_embedImageWithAmazonBedrock,"_embedImageWithAmazonBedrock");async function _embedImage(ss,opt){if(_isAwsBedrockActive()){let client=_getOrCreateBedrockClient();return client?_embedImageWithAmazonBedrock(ss,opt,client):void 0}}__name(_embedImage,"_embedImage");async function compare2(page,figma,options){let normalize=typeof options?.normalize=="boolean"?options.normalize:!0,figmaVec=await _embedImage(figma,options);if(!figmaVec)return;let pageVec=await _embedImage(page,options);return pageVec?{score:cosineSimilarity(figmaVec,pageVec,normalize)}:void 0}__name(compare2,"compare");import{BedrockRuntimeClient as BedrockRuntimeClient2,InvokeModelCommand as InvokeModelCommand2}from"@aws-sdk/client-bedrock-runtime";import{fromIni as fromIni2}from"@aws-sdk/credential-providers";import sharp3 from"sharp";var UI_DESCRIBE_PROMPT=`
|
|
415
|
-
You are analyzing a UI screenshot to compare it against another UI.
|
|
416
|
-
|
|
417
|
-
Your goal is to produce a STRUCTURAL LAYOUT FINGERPRINT that remains stable
|
|
418
|
-
even when real data, text values, or content change.
|
|
419
|
-
|
|
420
|
-
Write a concise but highly informative description using the rules below.
|
|
421
|
-
|
|
422
|
-
GENERAL RULES
|
|
423
|
-
- Describe WHAT EXISTS and WHERE IT IS, not how it looks visually.
|
|
424
|
-
- Prefer explicit structure and hierarchy over natural language.
|
|
425
|
-
- Be consistent and deterministic in wording.
|
|
426
|
-
- Do NOT describe colors, fonts, themes, or exact text.
|
|
427
|
-
- Do NOT include user data, names, numbers, timestamps, or labels.
|
|
428
|
-
|
|
429
|
-
LAYOUT STRUCTURE
|
|
430
|
-
Describe the UI from top to bottom:
|
|
431
|
-
|
|
432
|
-
1) PAGE REGIONS
|
|
433
|
-
- Identify major regions in order:
|
|
434
|
-
- top header / app bar
|
|
435
|
-
- left or right sidebar
|
|
436
|
-
- main content area
|
|
437
|
-
- footer (if present)
|
|
438
|
-
|
|
439
|
-
2) REGION DETAILS
|
|
440
|
-
For EACH region, describe:
|
|
441
|
-
- Position (top / left / right / center / full-width)
|
|
442
|
-
- Layout type (row, column, grid, split, stacked)
|
|
443
|
-
- Whether it is fixed or scrollable
|
|
444
|
-
- Primary purpose (navigation, content, controls, metadata)
|
|
445
|
-
|
|
446
|
-
3) COMPONENT INVENTORY
|
|
447
|
-
List the components that exist, grouped by region:
|
|
448
|
-
- navigation menus
|
|
449
|
-
- tabs
|
|
450
|
-
- tables (rows/columns, header present or not)
|
|
451
|
-
- lists (vertical/horizontal, item density: sparse/medium/dense)
|
|
452
|
-
- cards (count: single / few / many)
|
|
453
|
-
- forms (inline / multi-section)
|
|
454
|
-
- modals, drawers, overlays (present or not)
|
|
455
|
-
|
|
456
|
-
4) HIERARCHY & RELATIONSHIPS
|
|
457
|
-
Explicitly mention:
|
|
458
|
-
- parent \u2192 child relationships
|
|
459
|
-
- repeated patterns (e.g. "repeating card list", "uniform table rows")
|
|
460
|
-
- alignment relationships (sidebar + main content, header spanning all columns)
|
|
461
|
-
|
|
462
|
-
5) ABSENCE IS SIGNAL
|
|
463
|
-
If something is NOT present, state it explicitly when relevant:
|
|
464
|
-
- no sidebar
|
|
465
|
-
- no table
|
|
466
|
-
- no modal
|
|
467
|
-
- no pagination
|
|
468
|
-
|
|
469
|
-
FORMAT
|
|
470
|
-
- Use short bullet-style sentences.
|
|
471
|
-
- Use consistent phrasing across similar structures.
|
|
472
|
-
- Avoid synonyms (always say \u201Csidebar\u201D, not sometimes \u201Cside panel\u201D).
|
|
473
|
-
- Keep the output under ~30 lines.
|
|
474
|
-
|
|
475
|
-
Return plain text only. No markdown.
|
|
476
|
-
`;function _resolvePrompt(opt){return opt?.prompt??UI_DESCRIBE_PROMPT.trim()}__name(_resolvePrompt,"_resolvePrompt");function _resolveMaxDim(opt){return typeof opt?.maxDim=="number"&&opt.maxDim>0?Math.floor(opt.maxDim):1024}__name(_resolveMaxDim,"_resolveMaxDim");function _resolveImageFormat(opt){return opt?.imageFormat==="jpeg"?"jpeg":"png"}__name(_resolveImageFormat,"_resolveImageFormat");function _resolveJpegQuality(opt){let q=opt?.jpegQuality;return typeof q=="number"&&q>=50&&q<=100?Math.floor(q):90}__name(_resolveJpegQuality,"_resolveJpegQuality");async function _preprocessImage(buf,opt){let maxDim=_resolveMaxDim(opt),format=_resolveImageFormat(opt),jpegQuality=_resolveJpegQuality(opt),img=sharp3(buf).resize({width:maxDim,height:maxDim,fit:"inside",withoutEnlargement:!0}),out,mimeType;return format==="png"?(out=await img.png().toBuffer(),mimeType="image/png"):(out=await img.jpeg({quality:jpegQuality}).toBuffer(),mimeType="image/jpeg"),{bytes:out,mimeType}}__name(_preprocessImage,"_preprocessImage");var SUPPORTED_AMAZON_BEDROCK_TEXT_EMBED_MODEL_IDS=new Set(["amazon.titan-embed-text-v2:0"]),DEFAULT_AMAZON_BEDROCK_TEXT_EMBED_MODEL_ID="amazon.titan-embed-text-v2:0",SUPPORTED_AMAZON_BEDROCK_VISION_MODEL_IDS=new Set(["anthropic.claude-3-haiku-20240307-v1","anthropic.claude-3-sonnet-20240229-v1:0","anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-7-sonnet-20250219-v1:0","anthropic.claude-3-opus-20240229-v1:0","anthropic.claude-haiku-4-5-20251001-v1:0","anthropic.claude-opus-4-1-20250805-v1:0","anthropic.claude-opus-4-5-20251101-v1:0"]),DEFAULT_AMAZON_BEDROCK_VISION_MODEL_ID="anthropic.claude-3-sonnet-20240229-v1:0",_bedrockClient2;function _isAwsBedrockActive2(){return AMAZON_BEDROCK_ENABLE&&!!AWS_REGION}__name(_isAwsBedrockActive2,"_isAwsBedrockActive");function _getOrCreateBedrockClient2(){if(_bedrockClient2)return _bedrockClient2;let region=AWS_REGION;if(!region)return;let profile=AWS_PROFILE;return profile?(_bedrockClient2=new BedrockRuntimeClient2({region,credentials:fromIni2({profile})}),_bedrockClient2):(_bedrockClient2=new BedrockRuntimeClient2({region}),_bedrockClient2)}__name(_getOrCreateBedrockClient2,"_getOrCreateBedrockClient");async function _invokeBedrock(client,modelId,payload){let cmd=new InvokeModelCommand2({modelId,contentType:"application/json",accept:"application/json",body:Buffer.from(JSON.stringify(payload))}),resp=await client.send(cmd),raw=Buffer.from(resp.body).toString("utf-8");return JSON.parse(raw)}__name(_invokeBedrock,"_invokeBedrock");async function _describeUIWithAmazonBedrockClaude(ss,opt,client,modelId){let{bytes,mimeType}=await _preprocessImage(ss.image,opt),payload={anthropic_version:"bedrock-2023-05-31",max_tokens:1e4,temperature:0,messages:[{role:"user",content:[{type:"text",text:_resolvePrompt(opt)},{type:"image",source:{type:"base64",media_type:mimeType,data:bytes.toString("base64")}}]}]},parsed=await _invokeBedrock(client,modelId,payload),text=parsed?.content?.[0]?.text??parsed?.output_text??parsed?.completion;if(!text||!text.trim())throw new Error("Amazon Bedrock Claude returned empty description.");return text.trim()}__name(_describeUIWithAmazonBedrockClaude,"_describeUIWithAmazonBedrockClaude");async function _embedTextWithAmazonBedrockTitan(text,client,modelId){let emb=(await _invokeBedrock(client,modelId,{inputText:text}))?.embedding;if(!Array.isArray(emb)||typeof emb[0]!="number")throw new Error("Unexpected embedding response for Amazon Bedrock Titan text embedding.");return emb}__name(_embedTextWithAmazonBedrockTitan,"_embedTextWithAmazonBedrockTitan");async function _describeUIWithAmazonBedrock(ss,opt,client){let modelId=opt?.visionModelId??AMAZON_BEDROCK_VISION_MODEL_ID??DEFAULT_AMAZON_BEDROCK_VISION_MODEL_ID;if(!SUPPORTED_AMAZON_BEDROCK_VISION_MODEL_IDS.has(modelId))throw new Error(`Unsupported Amazon Bedrock vision model id: ${modelId}`);return await _describeUIWithAmazonBedrockClaude(ss,opt,client,modelId)}__name(_describeUIWithAmazonBedrock,"_describeUIWithAmazonBedrock");async function _embedTextWithAmazonBedrock(text,opt,client){let modelId=opt?.textEmbedModelId??AMAZON_BEDROCK_TEXT_EMBED_MODEL_ID??DEFAULT_AMAZON_BEDROCK_TEXT_EMBED_MODEL_ID;if(!SUPPORTED_AMAZON_BEDROCK_TEXT_EMBED_MODEL_IDS.has(modelId))throw new Error(`Unsupported Amazon Bedrock text embedding model id: ${modelId}`);return await _embedTextWithAmazonBedrockTitan(text,client,modelId)}__name(_embedTextWithAmazonBedrock,"_embedTextWithAmazonBedrock");async function _describeUI(ss,opt){if(_isAwsBedrockActive2()){let client=_getOrCreateBedrockClient2();return client?_describeUIWithAmazonBedrock(ss,opt,client):void 0}}__name(_describeUI,"_describeUI");async function _embedTextVector(text,opt){if(_isAwsBedrockActive2()){let client=_getOrCreateBedrockClient2();return client?_embedTextWithAmazonBedrock(text,opt,client):void 0}}__name(_embedTextVector,"_embedTextVector");async function compare3(page,figma,options){let normalize=typeof options?.normalize=="boolean"?options.normalize:!0,figmaDesc=await _describeUI(figma,options);if(!figmaDesc)return;let pageDesc=await _describeUI(page,options);if(!pageDesc)return;let figmaVec=await _embedTextVector(figmaDesc,options);if(!figmaVec)return;let pageVec=await _embedTextVector(pageDesc,options);return pageVec?{score:cosineSimilarity(figmaVec,pageVec,normalize)}:void 0}__name(compare3,"compare");var DEFAULT_MSSIM_WEIGHT=.25,DEFAULT_VECTOR_EMBEDDING_WEIGHT=.5,DEFAULT_TEXT_EMBEDDING_WEIGHT=.25;function _clamp012(v){return Number.isFinite(v)?Math.max(0,Math.min(1,v)):0}__name(_clamp012,"_clamp01");function _weightOrDefault(v,def){return typeof v=="number"&&Number.isFinite(v)&&v>0?v:def}__name(_weightOrDefault,"_weightOrDefault");async function compareWithNotes(page,figma,options){let notes=[],wMssim=_weightOrDefault(options?.weights?.mssim,DEFAULT_MSSIM_WEIGHT),wVector=_weightOrDefault(options?.weights?.vectorEmbedding,DEFAULT_VECTOR_EMBEDDING_WEIGHT),wText=_weightOrDefault(options?.weights?.textEmbedding,DEFAULT_TEXT_EMBEDDING_WEIGHT),mssimRes=await compare(page,figma,options?.mssim),mssimScore=_clamp012(mssimRes.score);notes.push(`mssim=${mssimScore.toFixed(5)}`);let imageScore;try{let res=await compare2(page,figma,options?.imageEmbedding);res&&typeof res.score=="number"?(imageScore=_clamp012(res.score),notes.push(`image-embedding=${imageScore.toFixed(5)}`)):notes.push("image-embedding=skipped (inactive)")}catch(err){notes.push(`image-embedding=skipped (${err instanceof Error?err.message:String(err)})`)}let textScore;try{let res=await compare3(page,figma,options?.textEmbedding);res&&typeof res.score=="number"?(textScore=_clamp012(res.score),notes.push(`text-embedding=${textScore.toFixed(5)}`)):notes.push("text-embedding=skipped (inactive)")}catch(err){notes.push(`text-embedding=skipped (${err instanceof Error?err.message:String(err)})`)}let parts=[{name:"mssim",score:mssimScore,weight:wMssim}];typeof imageScore=="number"&&parts.push({name:"image-embedding",score:imageScore,weight:wVector}),typeof textScore=="number"&&parts.push({name:"text-embedding",score:textScore,weight:wText});let totalWeight=parts.reduce((s,p)=>s+p.weight,0),combined=totalWeight>0?parts.reduce((s,p)=>s+p.score*(p.weight/totalWeight),0):0,score=_clamp012(combined);return notes.push(`combined=${score.toFixed(5)} (signals=${parts.map(p=>p.name).join(", ")})`),{score,notes}}__name(compareWithNotes,"compareWithNotes");import crypto from"node:crypto";function _requireFigmaToken(){let token=FIGMA_ACCESS_TOKEN;if(!token)throw new Error("No Figma access token configured");return token}__name(_requireFigmaToken,"_requireFigmaToken");function _mimeTypeFor(format){return format==="jpg"?{mimeType:"image/jpeg",type:"jpeg"}:{mimeType:"image/png",type:"png"}}__name(_mimeTypeFor,"_mimeTypeFor");function _buildCacheKey(req){let h=crypto.createHash("sha256");return h.update(req.fileKey),h.update("|"),h.update(req.nodeId),h.update("|"),h.update(req.format??"png"),h.update("|"),h.update(String(req.scale??2)),h.digest("hex").slice(0,24)}__name(_buildCacheKey,"_buildCacheKey");async function _fetchJson(url,token){let res=await fetch(url,{method:"GET",headers:{"X-Figma-Token":token,Accept:"application/json"}}),text=await res.text(),json;try{json=text?JSON.parse(text):{}}catch{throw new Error(`Figma API returned non-JSON response (status=${res.status}). Body: ${text.slice(0,500)}`)}if(!res.ok){let msg=typeof json?.err=="string"?json.err:`Figma API error (status=${res.status})`;throw new Error(msg)}return json}__name(_fetchJson,"_fetchJson");async function _fetchBinary(url){let res=await fetch(url,{method:"GET"});if(!res.ok){let t=await res.text().catch(()=>"");throw new Error(`Failed to download Figma rendered image (status=${res.status}): ${t.slice(0,300)}`)}let ab=await res.arrayBuffer();return Buffer.from(ab)}__name(_fetchBinary,"_fetchBinary");async function getFigmaDesignScreenshot(req){let token=_requireFigmaToken(),format=req.format??"png",scale=typeof req.scale=="number"&&req.scale>0?req.scale:2,{mimeType,type}=_mimeTypeFor(format),base=FIGMA_API_BASE_URL,fileKey=req.fileKey,nodeId=req.nodeId,url=`${base}/images/${encodeURIComponent(fileKey)}?ids=${encodeURIComponent(nodeId)}&format=${encodeURIComponent(format)}&scale=${encodeURIComponent(String(scale))}`,imgResp=await _fetchJson(url,token),imageUrl=imgResp.images?.[nodeId];if(!imageUrl){let err=typeof imgResp.err=="string"&&imgResp.err.trim()?imgResp.err:"Figma did not return an image URL for the given nodeId.";throw new Error(err)}let image=await _fetchBinary(imageUrl),cacheKey=_buildCacheKey(req),out={image,mimeType,type,cacheKey};return req.includeId===!0&&(out.nodeId=nodeId,out.fileKey=fileKey),out}__name(getFigmaDesignScreenshot,"getFigmaDesignScreenshot");import{z as z41}from"zod";var DEFAULT_SCREENSHOT_TYPE2="png",DEFAULT_FULL_PAGE=!0,DEFAULT_MSSIM_MODE="semantic",ComparePageWithDesign=class{static{__name(this,"ComparePageWithDesign")}name(){return"figma_compare-page-with-design"}description(){return`
|
|
477
|
-
Compares the CURRENT PAGE UI against a Figma design snapshot and returns a combined similarity score.
|
|
478
|
-
|
|
479
|
-
What this tool does:
|
|
480
|
-
1) Fetches a raster snapshot from Figma (frame/node screenshot)
|
|
481
|
-
2) Takes a screenshot of the live browser page (full page or a specific selector)
|
|
482
|
-
3) Computes multiple similarity signals and combines them into one score:
|
|
483
|
-
- MSSIM (structural similarity; always available)
|
|
484
|
-
- Image embedding similarity (optional; may be skipped if provider is not configured)
|
|
485
|
-
- Vision\u2192text\u2192text embedding similarity (optional; may be skipped if provider is not configured)
|
|
486
|
-
|
|
487
|
-
How to use it effectively:
|
|
488
|
-
- Prefer 'semantic' MSSIM mode when comparing Figma sample data vs real data (less sensitive to text/value differences).
|
|
489
|
-
- Use 'raw' MSSIM mode only when you expect near pixel-identical output.
|
|
490
|
-
- If you suspect layout/structure mismatch, run with fullPage=true first, then retry with a selector for the problematic region.
|
|
491
|
-
- Notes explain which signals were used or skipped; skipped signals usually mean missing cloud configuration (e.g. AWS_REGION, inference profile, etc).
|
|
492
|
-
|
|
493
|
-
This tool is designed for UI regression checks, design parity checks, and "does this page still match the intended layout?" validation.
|
|
494
|
-
`.trim()}inputSchema(){return{figmaFileKey:z41.string().min(1).describe("Figma file key (the part after /file/ in Figma URL)."),figmaNodeId:z41.string().min(1).describe('Figma node id to render (frame/component node id like "12:34").'),selector:z41.string().optional().describe("Optional CSS selector to compare only a specific region of the page."),fullPage:z41.boolean().optional().default(DEFAULT_FULL_PAGE).describe("If true, captures the full scrollable page. Ignored when selector is provided."),figmaScale:z41.number().int().positive().optional().describe("Optional scale factor for Figma raster export (e.g. 1, 2, 3)."),figmaFormat:z41.enum(["png","jpg"]).optional().describe("Optional raster format for Figma snapshot."),weights:z41.object({mssim:z41.number().positive().optional().describe("Weight for MSSIM signal."),imageEmbedding:z41.number().positive().optional().describe("Weight for image embedding signal."),textEmbedding:z41.number().positive().optional().describe("Weight for vision\u2192text\u2192text embedding signal.")}).optional().describe("Optional weights to combine signals. Only active signals participate."),mssimMode:z41.enum(["raw","semantic"]).optional().default(DEFAULT_MSSIM_MODE).describe("MSSIM mode. semantic is more robust for real-data vs design-data comparisons."),maxDim:z41.number().int().positive().optional().describe("Optional preprocessing max dimension forwarded to compare pipeline."),jpegQuality:z41.number().int().min(50).max(100).optional().describe("Optional JPEG quality forwarded to compare pipeline (used only when JPEG encoding is selected internally).")}}outputSchema(){return{score:z41.number().describe("Combined similarity score in the range [0..1]. Higher means more similar."),notes:z41.array(z41.string()).describe("Human-readable notes explaining which signals were used and their individual scores."),meta:z41.object({pageUrl:z41.string().describe("URL of the page that was compared."),pageTitle:z41.string().describe("Title of the page that was compared."),figmaFileKey:z41.string().describe("Figma file key used for the design snapshot."),figmaNodeId:z41.string().describe("Figma node id used for the design snapshot."),selector:z41.string().nullable().describe("Selector used for page screenshot, if any. Null means full page."),fullPage:z41.boolean().describe("Whether the page screenshot was full-page."),pageImageType:z41.enum(["png","jpeg"]).describe("Image type of the captured page screenshot."),figmaImageType:z41.enum(["png","jpeg"]).describe("Image type of the captured Figma snapshot.")}).describe("Metadata about what was compared.")}}async handle(context,args){let pageUrl=String(context.page.url()),pageTitle=String(await context.page.title()),figmaFormat=args.figmaFormat??"png",figmaScale=typeof args.figmaScale=="number"?args.figmaScale:void 0,figmaSnapshot=await getFigmaDesignScreenshot({fileKey:args.figmaFileKey,nodeId:args.figmaNodeId,format:figmaFormat,scale:figmaScale}),pagePng;if(typeof args.selector=="string"&&args.selector.trim()){let selector=args.selector.trim(),locator=context.page.locator(selector);if(await locator.count()===0)throw new Error(`Element not found for selector: ${selector}`);pagePng=await locator.first().screenshot({type:DEFAULT_SCREENSHOT_TYPE2})}else{let fullPage=args.fullPage!==!1;pagePng=await context.page.screenshot({type:DEFAULT_SCREENSHOT_TYPE2,fullPage})}let pageSs={image:pagePng,type:"png",name:"page"},figmaSs={image:figmaSnapshot.image,type:figmaSnapshot.type==="jpeg"?"jpeg":"png",name:"figma"},result=await compareWithNotes(pageSs,figmaSs,{weights:args.weights?{mssim:args.weights.mssim,vectorEmbedding:args.weights.imageEmbedding,textEmbedding:args.weights.textEmbedding}:void 0,mssim:{mode:args.mssimMode??DEFAULT_MSSIM_MODE},imageEmbedding:{maxDim:args.maxDim,jpegQuality:typeof args.jpegQuality=="number"?args.jpegQuality:void 0},textEmbedding:{maxDim:args.maxDim,jpegQuality:typeof args.jpegQuality=="number"?args.jpegQuality:void 0}});return{score:result.score,notes:result.notes,meta:{pageUrl,pageTitle,figmaFileKey:args.figmaFileKey,figmaNodeId:args.figmaNodeId,selector:typeof args.selector=="string"&&args.selector.trim()?args.selector.trim():null,fullPage:typeof args.selector=="string"&&args.selector.trim()?!1:args.fullPage!==!1,pageImageType:"png",figmaImageType:figmaSnapshot.type}}}};var tools4=[new ComparePageWithDesign];import{z as z42}from"zod";var DEFAULT_SELECTOR_TIMEOUT_MS=1e4,Click=class{static{__name(this,"Click")}name(){return"interaction_click"}description(){return"Clicks an element on the page."}inputSchema(){return{selector:z42.string().describe("CSS selector for the element to click."),timeoutMs:z42.number().int().positive().optional().describe("Timeout in ms to wait for the element (default 10000). Use a shorter value (e.g. 5000) to fail faster if the selector might be invalid.")}}outputSchema(){return{}}async handle(context,args){let timeout=args.timeoutMs??DEFAULT_SELECTOR_TIMEOUT_MS;return await(await context.page.waitForSelector(args.selector,{state:"visible",timeout})).click(),{}}};import{z as z43}from"zod";var DEFAULT_SELECTOR_TIMEOUT_MS2=1e4,Drag=class{static{__name(this,"Drag")}name(){return"interaction_drag"}description(){return"Drags an element to a target location."}inputSchema(){return{sourceSelector:z43.string().describe("CSS selector for the element to drag."),targetSelector:z43.string().describe("CSS selector for the target location."),timeoutMs:z43.number().int().positive().optional().describe("Timeout in ms to wait for source and target elements (default 10000). Use a shorter value (e.g. 5000) to fail faster if selectors might be invalid.")}}outputSchema(){return{}}async handle(context,args){let timeout=args.timeoutMs??DEFAULT_SELECTOR_TIMEOUT_MS2,sourceElement=await context.page.waitForSelector(args.sourceSelector,{state:"visible",timeout}),targetElement=await context.page.waitForSelector(args.targetSelector,{state:"visible",timeout}),sourceBound=await sourceElement.boundingBox(),targetBound=await targetElement.boundingBox();if(!sourceBound||!targetBound)throw new Error("Could not get element positions for drag operation");return await context.page.mouse.move(sourceBound.x+sourceBound.width/2,sourceBound.y+sourceBound.height/2),await context.page.mouse.down(),await context.page.mouse.move(targetBound.x+targetBound.width/2,targetBound.y+targetBound.height/2),await context.page.mouse.up(),{}}};import{z as z44}from"zod";var DEFAULT_SELECTOR_TIMEOUT_MS3=1e4,Fill=class{static{__name(this,"Fill")}name(){return"interaction_fill"}description(){return"Fills out an input field."}inputSchema(){return{selector:z44.string().describe("CSS selector for the input field."),value:z44.string().describe("Value to fill."),timeoutMs:z44.number().int().positive().optional().describe("Timeout in ms to wait for the element (default 10000). Use a shorter value (e.g. 5000) to fail faster if the selector might be invalid.")}}outputSchema(){return{}}async handle(context,args){let timeout=args.timeoutMs??DEFAULT_SELECTOR_TIMEOUT_MS3;return await(await context.page.waitForSelector(args.selector,{state:"visible",timeout})).fill(args.value),{}}};import{z as z45}from"zod";var DEFAULT_SELECTOR_TIMEOUT_MS4=1e4,Hover=class{static{__name(this,"Hover")}name(){return"interaction_hover"}description(){return"Hovers an element on the page."}inputSchema(){return{selector:z45.string().describe("CSS selector for the element to hover."),timeoutMs:z45.number().int().positive().optional().describe("Timeout in ms to wait for the element (default 10000). Use a shorter value (e.g. 5000) to fail faster if the selector might be invalid.")}}outputSchema(){return{}}async handle(context,args){let timeout=args.timeoutMs??DEFAULT_SELECTOR_TIMEOUT_MS4;return await(await context.page.waitForSelector(args.selector,{state:"visible",timeout})).hover(),{}}};import{z as z46}from"zod";var DEFAULT_REPEAT_INTERVAL_MS=50,MIN_REPEAT_INTERVAL_MS=10,DEFAULT_SELECTOR_TIMEOUT_MS5=1e4,PressKey=class{static{__name(this,"PressKey")}name(){return"interaction_press-key"}description(){return`
|
|
495
|
-
Presses a keyboard key with optional "hold" and auto-repeat behavior.
|
|
496
|
-
|
|
497
|
-
Key facts:
|
|
498
|
-
- keyboard.press(key, { delay }) does NOT trigger OS-style auto-repeat.
|
|
499
|
-
- Some UI behaviors (especially scrolling) require repeated keydown events.
|
|
500
|
-
- Use repeat=true + holdMs to approximate real keyboard holding.
|
|
501
|
-
|
|
502
|
-
Execution logic:
|
|
503
|
-
- If selector is provided, the element is focused first.
|
|
504
|
-
- If holdMs is omitted or repeat=false:
|
|
505
|
-
\u2192 a single keyboard.press() is executed.
|
|
506
|
-
- If holdMs is provided AND repeat=true:
|
|
507
|
-
\u2192 keyboard.press() is called repeatedly until holdMs elapses.
|
|
508
|
-
`.trim()}inputSchema(){return{key:z46.string().describe('Keyboard key to press (e.g. "Enter", "ArrowDown", "a").'),selector:z46.string().describe("Optional CSS selector to focus before sending the key.").optional(),holdMs:z46.number().int().min(0).describe("Optional duration in milliseconds to hold the key. With repeat=true, this is the total repeat duration.").optional(),repeat:z46.boolean().optional().default(!1).describe("If true, simulates key auto-repeat by pressing the key repeatedly (useful for scrolling)."),repeatIntervalMs:z46.number().int().min(MIN_REPEAT_INTERVAL_MS).optional().default(DEFAULT_REPEAT_INTERVAL_MS).describe("Interval between repeated key presses in ms (only when repeat=true)."),timeoutMs:z46.number().int().positive().optional().describe("Timeout in ms to wait for the element when selector is provided (default 10000). Use a shorter value to fail faster if the selector might be invalid.")}}outputSchema(){return{}}async handle(context,args){if(args.selector){let timeout=args.timeoutMs??DEFAULT_SELECTOR_TIMEOUT_MS5;await(await context.page.waitForSelector(args.selector,{state:"visible",timeout})).focus()}let holdMs=args.holdMs??0,repeat=args.repeat===!0;if(holdMs<=0||repeat===!1)return await context.page.keyboard.press(args.key,holdMs>0?{delay:holdMs}:void 0),{};let repeatIntervalMs=typeof args.repeatIntervalMs=="number"&&Number.isFinite(args.repeatIntervalMs)&&args.repeatIntervalMs>=MIN_REPEAT_INTERVAL_MS?Math.floor(args.repeatIntervalMs):DEFAULT_REPEAT_INTERVAL_MS,startMs=Date.now();for(;Date.now()-startMs<holdMs;)await context.page.keyboard.press(args.key),await context.page.waitForTimeout(repeatIntervalMs);return{}}};import{z as z47}from"zod";var MIN_VIEWPORT_WIDTH=200,MIN_VIEWPORT_HEIGHT=200,ResizeViewport=class{static{__name(this,"ResizeViewport")}name(){return"interaction_resize-viewport"}description(){return`
|
|
509
|
-
Resizes the PAGE VIEWPORT using Playwright viewport emulation (page.setViewportSize).
|
|
510
|
-
|
|
511
|
-
This affects:
|
|
512
|
-
- window.innerWidth / window.innerHeight
|
|
513
|
-
- CSS media queries (responsive layouts)
|
|
514
|
-
- Layout, rendering and screenshots
|
|
515
|
-
|
|
516
|
-
Notes:
|
|
517
|
-
- This does NOT resize the OS-level browser window.
|
|
518
|
-
- Runtime switching to viewport=null (binding to real window size) is not supported by Playwright.
|
|
519
|
-
If you need real window-driven responsive behavior, start the BrowserContext with viewport: null
|
|
520
|
-
and use the window resize tool instead.
|
|
521
|
-
`.trim()}inputSchema(){return{width:z47.number().int().min(MIN_VIEWPORT_WIDTH).describe("Target viewport width in CSS pixels."),height:z47.number().int().min(MIN_VIEWPORT_HEIGHT).describe("Target viewport height in CSS pixels.")}}outputSchema(){return{requested:z47.object({width:z47.number().int().describe("Requested viewport width (CSS pixels)."),height:z47.number().int().describe("Requested viewport height (CSS pixels).")}).describe("Requested viewport configuration."),viewport:z47.object({innerWidth:z47.number().int().describe("window.innerWidth after resize (CSS pixels)."),innerHeight:z47.number().int().describe("window.innerHeight after resize (CSS pixels)."),outerWidth:z47.number().int().describe("window.outerWidth after resize (CSS pixels)."),outerHeight:z47.number().int().describe("window.outerHeight after resize (CSS pixels)."),devicePixelRatio:z47.number().describe("window.devicePixelRatio after resize.")}).describe("Viewport metrics observed inside the page after resizing.")}}async handle(context,args){await context.page.setViewportSize({width:args.width,height:args.height});let metrics=await context.page.evaluate(()=>({innerWidth:window.innerWidth,innerHeight:window.innerHeight,outerWidth:window.outerWidth,outerHeight:window.outerHeight,devicePixelRatio:window.devicePixelRatio}));return{requested:{width:args.width,height:args.height},viewport:{innerWidth:Number(metrics.innerWidth),innerHeight:Number(metrics.innerHeight),outerWidth:Number(metrics.outerWidth),outerHeight:Number(metrics.outerHeight),devicePixelRatio:Number(metrics.devicePixelRatio)}}}};import{z as z48}from"zod";var MIN_WINDOW_WIDTH=200,MIN_WINDOW_HEIGHT=200,ResizeWindow=class{static{__name(this,"ResizeWindow")}name(){return"interaction_resize-window"}description(){return`
|
|
522
|
-
Resizes the REAL BROWSER WINDOW (OS-level window) for the current page using Chrome DevTools Protocol (CDP).
|
|
523
|
-
|
|
524
|
-
This tool works best on Chromium-based browsers (Chromium/Chrome/Edge).
|
|
525
|
-
It is especially useful in headful sessions when you run with viewport emulation disabled (viewport: null),
|
|
526
|
-
so the page layout follows the OS window size.
|
|
527
|
-
|
|
528
|
-
Important:
|
|
529
|
-
- If Playwright viewport emulation is enabled (viewport is NOT null), resizing the OS window may not change page layout.
|
|
530
|
-
- On non-Chromium browsers (Firefox/WebKit), CDP is not available and this tool will fail.
|
|
531
|
-
`.trim()}inputSchema(){return{width:z48.number().int().min(MIN_WINDOW_WIDTH).optional().describe('Target window width in pixels (required when state="normal").'),height:z48.number().int().min(MIN_WINDOW_HEIGHT).optional().describe('Target window height in pixels (required when state="normal").'),state:z48.enum(["normal","maximized","minimized","fullscreen"]).optional().default("normal").describe('Target window state. If not "normal", width/height may be ignored by the browser.')}}outputSchema(){return{requested:z48.object({width:z48.number().int().nullable().describe("Requested window width (pixels). Null if not provided."),height:z48.number().int().nullable().describe("Requested window height (pixels). Null if not provided."),state:z48.enum(["normal","maximized","minimized","fullscreen"]).describe("Requested window state.")}).describe("Requested window change parameters."),before:z48.object({windowId:z48.number().int().describe("CDP window id for the current target."),state:z48.string().nullable().describe("Window state before resizing."),left:z48.number().int().nullable().describe("Window left position before resizing."),top:z48.number().int().nullable().describe("Window top position before resizing."),width:z48.number().int().nullable().describe("Window width before resizing."),height:z48.number().int().nullable().describe("Window height before resizing.")}).describe("Window bounds before resizing."),after:z48.object({windowId:z48.number().int().describe("CDP window id for the current target."),state:z48.string().nullable().describe("Window state after resizing."),left:z48.number().int().nullable().describe("Window left position after resizing."),top:z48.number().int().nullable().describe("Window top position after resizing."),width:z48.number().int().nullable().describe("Window width after resizing."),height:z48.number().int().nullable().describe("Window height after resizing.")}).describe("Window bounds after resizing."),viewport:z48.object({innerWidth:z48.number().int().describe("window.innerWidth after resizing (CSS pixels)."),innerHeight:z48.number().int().describe("window.innerHeight after resizing (CSS pixels)."),outerWidth:z48.number().int().describe("window.outerWidth after resizing (CSS pixels)."),outerHeight:z48.number().int().describe("window.outerHeight after resizing (CSS pixels)."),devicePixelRatio:z48.number().describe("window.devicePixelRatio after resizing.")}).describe("Page viewport metrics after resizing (helps verify responsive behavior).")}}async handle(context,args){let state=args.state??"normal",width=args.width,height=args.height;if(state==="normal"&&(typeof width!="number"||typeof height!="number"))throw new Error('state="normal" requires both width and height.');let page=context.page,cdp=await page.context().newCDPSession(page);try{let info=await cdp.send("Browser.getWindowForTarget",{}),windowId=Number(info.windowId),beforeBounds=info.bounds??{},before={windowId,state:typeof beforeBounds.windowState=="string"?beforeBounds.windowState:null,left:typeof beforeBounds.left=="number"?beforeBounds.left:null,top:typeof beforeBounds.top=="number"?beforeBounds.top:null,width:typeof beforeBounds.width=="number"?beforeBounds.width:null,height:typeof beforeBounds.height=="number"?beforeBounds.height:null},boundsToSet={};state!=="normal"?boundsToSet.windowState=state:(boundsToSet.windowState="normal",boundsToSet.width=width,boundsToSet.height=height),await cdp.send("Browser.setWindowBounds",{windowId,bounds:boundsToSet});let afterBounds=(await cdp.send("Browser.getWindowForTarget",{})).bounds??{},after={windowId,state:typeof afterBounds.windowState=="string"?afterBounds.windowState:null,left:typeof afterBounds.left=="number"?afterBounds.left:null,top:typeof afterBounds.top=="number"?afterBounds.top:null,width:typeof afterBounds.width=="number"?afterBounds.width:null,height:typeof afterBounds.height=="number"?afterBounds.height:null},metrics=await page.evaluate(()=>({innerWidth:window.innerWidth,innerHeight:window.innerHeight,outerWidth:window.outerWidth,outerHeight:window.outerHeight,devicePixelRatio:window.devicePixelRatio})),viewport={innerWidth:Number(metrics.innerWidth),innerHeight:Number(metrics.innerHeight),outerWidth:Number(metrics.outerWidth),outerHeight:Number(metrics.outerHeight),devicePixelRatio:Number(metrics.devicePixelRatio)};return{requested:{width:typeof width=="number"?width:null,height:typeof height=="number"?height:null,state},before,after,viewport}}catch(e){let msg=String(e?.message??e);throw new Error(`Failed to resize real browser window via CDP. This tool works best on Chromium-based browsers. Original error: ${msg}`)}finally{await cdp.detach().catch(()=>{})}}};import{z as z49}from"zod";var DEFAULT_SELECTOR_TIMEOUT_MS6=1e4,Select=class{static{__name(this,"Select")}name(){return"interaction_select"}description(){return"Select an element on the page with the given value"}inputSchema(){return{selector:z49.string().describe("CSS selector for element to select."),value:z49.string().describe("Value to select."),timeoutMs:z49.number().int().positive().optional().describe("Timeout in ms to wait for the element (default 10000). Use a shorter value (e.g. 5000) to fail faster if the selector might be invalid.")}}outputSchema(){return{}}async handle(context,args){let timeout=args.timeoutMs??DEFAULT_SELECTOR_TIMEOUT_MS6;return await(await context.page.waitForSelector(args.selector,{state:"visible",timeout})).selectOption(args.value),{}}};import{z as z50}from"zod";var DEFAULT_BEHAVIOR="auto",DEFAULT_MODE="by",Scroll=class{static{__name(this,"Scroll")}name(){return"interaction_scroll"}description(){return`
|
|
532
|
-
Scrolls the page viewport or a specific scrollable element.
|
|
533
|
-
|
|
534
|
-
Modes:
|
|
535
|
-
- 'by': Scrolls by a relative delta (dx/dy) from the current scroll position.
|
|
536
|
-
- 'to': Scrolls to an absolute scroll position (x/y).
|
|
537
|
-
- 'top': Scrolls to the very top.
|
|
538
|
-
- 'bottom': Scrolls to the very bottom.
|
|
539
|
-
- 'left': Scrolls to the far left.
|
|
540
|
-
- 'right': Scrolls to the far right.
|
|
541
|
-
|
|
542
|
-
Use this tool to:
|
|
543
|
-
- Reveal content below the fold
|
|
544
|
-
- Jump to the top/bottom without knowing exact positions
|
|
545
|
-
- Bring elements into view before clicking
|
|
546
|
-
- Inspect lazy-loaded content that appears on scroll
|
|
547
|
-
`.trim()}inputSchema(){return{mode:z50.enum(["by","to","top","bottom","left","right"]).optional().default(DEFAULT_MODE).describe('Scroll mode. "by" uses dx/dy, "to" uses x/y, and top/bottom/left/right jump to edges.'),selector:z50.string().optional().describe("Optional CSS selector for a scrollable container. If omitted, scrolls the document viewport."),dx:z50.number().optional().describe('Horizontal scroll delta in pixels (used when mode="by"). Default: 0.'),dy:z50.number().optional().describe('Vertical scroll delta in pixels (used when mode="by"). Default: 0.'),x:z50.number().optional().describe('Absolute horizontal scroll position in pixels (used when mode="to").'),y:z50.number().optional().describe('Absolute vertical scroll position in pixels (used when mode="to").'),behavior:z50.enum(["auto","smooth"]).optional().default(DEFAULT_BEHAVIOR).describe('Native scroll behavior. Use "auto" for deterministic automation.')}}outputSchema(){return{mode:z50.enum(["by","to","top","bottom","left","right"]).describe("The scroll mode used."),selector:z50.string().nullable().describe("The selector of the scroll container if provided; otherwise null (document viewport)."),behavior:z50.enum(["auto","smooth"]).describe("The scroll behavior used."),before:z50.object({x:z50.number().describe("ScrollLeft before scrolling."),y:z50.number().describe("ScrollTop before scrolling."),scrollWidth:z50.number().describe("Total scrollable width before scrolling."),scrollHeight:z50.number().describe("Total scrollable height before scrolling."),clientWidth:z50.number().describe("Viewport/container client width before scrolling."),clientHeight:z50.number().describe("Viewport/container client height before scrolling.")}).describe("Scroll metrics before the scroll action."),after:z50.object({x:z50.number().describe("ScrollLeft after scrolling."),y:z50.number().describe("ScrollTop after scrolling."),scrollWidth:z50.number().describe("Total scrollable width after scrolling."),scrollHeight:z50.number().describe("Total scrollable height after scrolling."),clientWidth:z50.number().describe("Viewport/container client width after scrolling."),clientHeight:z50.number().describe("Viewport/container client height after scrolling.")}).describe("Scroll metrics after the scroll action."),canScrollX:z50.boolean().describe("Whether horizontal scrolling is possible (scrollWidth > clientWidth)."),canScrollY:z50.boolean().describe("Whether vertical scrolling is possible (scrollHeight > clientHeight)."),maxScrollX:z50.number().describe("Maximum horizontal scrollLeft (scrollWidth - clientWidth)."),maxScrollY:z50.number().describe("Maximum vertical scrollTop (scrollHeight - clientHeight)."),isAtLeft:z50.boolean().describe("Whether the scroll position is at the far left."),isAtRight:z50.boolean().describe("Whether the scroll position is at the far right."),isAtTop:z50.boolean().describe("Whether the scroll position is at the very top."),isAtBottom:z50.boolean().describe("Whether the scroll position is at the very bottom.")}}async handle(context,args){let mode=args.mode??DEFAULT_MODE,selector=args.selector,behavior=args.behavior??DEFAULT_BEHAVIOR,dx=args.dx??0,dy=args.dy??0,x=args.x,y=args.y;if(mode==="to"&&typeof x!="number"&&typeof y!="number")throw new Error('mode="to" requires at least one of x or y.');if(mode==="by"&&dx===0&&dy===0)throw new Error('mode="by" requires dx and/or dy to be non-zero.');let result=await context.page.evaluate(params=>{let modeEval=params.modeEval,selectorEval=params.selectorEval,dxEval=params.dxEval,dyEval=params.dyEval,xEval=params.xEval,yEval=params.yEval,behaviorEval=params.behaviorEval,getTarget=__name(()=>{if(selectorEval){let el=document.querySelector(selectorEval);if(!el)throw new Error(`Element with selector "${selectorEval}" not found`);return el}let scrolling=document.scrollingElement||document.documentElement||document.body;if(!scrolling)throw new Error("No scrolling element available.");return scrolling},"getTarget"),readMetrics=__name(el=>({x:el.scrollLeft,y:el.scrollTop,scrollWidth:el.scrollWidth,scrollHeight:el.scrollHeight,clientWidth:el.clientWidth,clientHeight:el.clientHeight}),"readMetrics"),clamp=__name((v,min,max)=>v<min?min:v>max?max:v,"clamp"),doScroll=__name(el=>{let maxX=Math.max(0,el.scrollWidth-el.clientWidth),maxY=Math.max(0,el.scrollHeight-el.clientHeight);if(modeEval==="by"){let nextX=clamp(el.scrollLeft+dxEval,0,maxX),nextY=clamp(el.scrollTop+dyEval,0,maxY);el.scrollTo({left:nextX,top:nextY,behavior:behaviorEval});return}if(modeEval==="to"){let nextX=typeof xEval=="number"?clamp(xEval,0,maxX):el.scrollLeft,nextY=typeof yEval=="number"?clamp(yEval,0,maxY):el.scrollTop;el.scrollTo({left:nextX,top:nextY,behavior:behaviorEval});return}if(modeEval==="top"){el.scrollTo({top:0,left:el.scrollLeft,behavior:behaviorEval});return}if(modeEval==="bottom"){el.scrollTo({top:maxY,left:el.scrollLeft,behavior:behaviorEval});return}if(modeEval==="left"){el.scrollTo({left:0,top:el.scrollTop,behavior:behaviorEval});return}if(modeEval==="right"){el.scrollTo({left:maxX,top:el.scrollTop,behavior:behaviorEval});return}},"doScroll"),target=getTarget(),before=readMetrics(target);doScroll(target);let after=readMetrics(target),maxScrollX=Math.max(0,after.scrollWidth-after.clientWidth),maxScrollY=Math.max(0,after.scrollHeight-after.clientHeight),canScrollX=after.scrollWidth>after.clientWidth,canScrollY=after.scrollHeight>after.clientHeight,eps=1,isAtLeft=after.x<=eps,isAtRight=after.x>=maxScrollX-eps,isAtTop=after.y<=eps,isAtBottom=after.y>=maxScrollY-eps;return{before,after,canScrollX,canScrollY,maxScrollX,maxScrollY,isAtLeft,isAtRight,isAtTop,isAtBottom}},{modeEval:mode,selectorEval:selector,dxEval:dx,dyEval:dy,xEval:x,yEval:y,behaviorEval:behavior});return{mode,selector:selector??null,behavior,before:result.before,after:result.after,canScrollX:result.canScrollX,canScrollY:result.canScrollY,maxScrollX:result.maxScrollX,maxScrollY:result.maxScrollY,isAtLeft:result.isAtLeft,isAtRight:result.isAtRight,isAtTop:result.isAtTop,isAtBottom:result.isAtBottom}}};var tools5=[new Click,new Drag,new Fill,new Hover,new PressKey,new ResizeViewport,new ResizeWindow,new Select,new Scroll];import{z as z51}from"zod";var DEFAULT_TIMEOUT_MS=0,DEFAULT_WAIT_UNTIL="load",GoBack=class{static{__name(this,"GoBack")}name(){return"navigation_go-back"}description(){return`
|
|
548
|
-
Navigates to the previous page in history.
|
|
549
|
-
In case of multiple redirects, the navigation will resolve with the response of the last redirect.
|
|
550
|
-
If cannot go back, returns empty response.
|
|
551
|
-
`}inputSchema(){return{timeout:z51.number().int().nonnegative().describe("Maximum operation time in milliseconds. Defaults to `0` - no timeout.").optional().default(DEFAULT_TIMEOUT_MS),waitUntil:z51.enum(["load","domcontentloaded","networkidle","commit"]).describe("\nWhen to consider operation succeeded, defaults to `load`. Events can be either:\n- `domcontentloaded`: Consider operation to be finished when the `DOMContentLoaded` event is fired.\n- `load`: Consider operation to be finished when the `load` event is fired.\n- `networkidle`: **DISCOURAGED** consider operation to be finished when there are no network connections for\n at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.\n- `commit`: Consider operation to be finished when network response is received and the document started loading.").optional().default(DEFAULT_WAIT_UNTIL)}}outputSchema(){return{url:z51.string().describe("Contains the URL of the navigated page.").optional(),status:z51.number().int().positive().describe("Contains the status code of the navigated page (e.g., 200 for a success).").optional(),statusText:z51.string().describe('Contains the status text of the navigated page (e.g. usually an "OK" for a success).').optional(),ok:z51.boolean().describe("Contains a boolean stating whether the navigated page was successful (status in the range 200-299) or not.").optional()}}async handle(context,args){let response=await context.page.goBack({timeout:args.timeout,waitUntil:args.waitUntil});return{url:response?.url(),status:response?.status(),statusText:response?.statusText(),ok:response?.ok()}}};import{z as z52}from"zod";var DEFAULT_TIMEOUT_MS2=0,DEFAULT_WAIT_UNTIL2="load",GoForward=class{static{__name(this,"GoForward")}name(){return"navigation_go-forward"}description(){return`
|
|
552
|
-
Navigates to the next page in history.
|
|
553
|
-
In case of multiple redirects, the navigation will resolve with the response of the last redirect.
|
|
554
|
-
If cannot go back, returns empty response.
|
|
555
|
-
`}inputSchema(){return{timeout:z52.number().int().nonnegative().describe("Maximum operation time in milliseconds. Defaults to `0` - no timeout.").optional().default(DEFAULT_TIMEOUT_MS2),waitUntil:z52.enum(["load","domcontentloaded","networkidle","commit"]).describe("\nWhen to consider operation succeeded, defaults to `load`. Events can be either:\n- `domcontentloaded`: Consider operation to be finished when the `DOMContentLoaded` event is fired.\n- `load`: Consider operation to be finished when the `load` event is fired.\n- `networkidle`: **DISCOURAGED** consider operation to be finished when there are no network connections for\n at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.\n- `commit`: Consider operation to be finished when network response is received and the document started loading.").optional().default(DEFAULT_WAIT_UNTIL2)}}outputSchema(){return{url:z52.string().describe("Contains the URL of the navigated page.").optional(),status:z52.number().int().positive().describe("Contains the status code of the navigated page (e.g., 200 for a success).").optional(),statusText:z52.string().describe('Contains the status text of the navigated page (e.g. usually an "OK" for a success).').optional(),ok:z52.boolean().describe("Contains a boolean stating whether the navigated page was successful (status in the range 200-299) or not.").optional()}}async handle(context,args){let response=await context.page.goForward({timeout:args.timeout,waitUntil:args.waitUntil});return{url:response?.url(),status:response?.status(),statusText:response?.statusText(),ok:response?.ok()}}};import{z as z53}from"zod";var DEFAULT_TIMEOUT_MS3=0,DEFAULT_WAIT_UNTIL3="load",GoTo=class{static{__name(this,"GoTo")}name(){return"navigation_go-to"}description(){return`
|
|
556
|
-
Navigates to the given URL.
|
|
557
|
-
**NOTE**: The tool either throws an error or returns a main resource response.
|
|
558
|
-
The only exceptions are navigation to \`about:blank\` or navigation to the same URL with a different hash,
|
|
559
|
-
which would succeed and return empty response.
|
|
560
|
-
`}inputSchema(){return{url:z53.string().describe("URL to navigate page to. The url should include scheme, e.g. `http://`, `https://`."),timeout:z53.number().int().nonnegative().describe("Maximum operation time in milliseconds. Defaults to `0` - no timeout.").optional().default(DEFAULT_TIMEOUT_MS3),waitUntil:z53.enum(["load","domcontentloaded","networkidle","commit"]).describe("\nWhen to consider operation succeeded, defaults to `load`. Events can be either:\n- `domcontentloaded`: Consider operation to be finished when the `DOMContentLoaded` event is fired.\n- `load`: Consider operation to be finished when the `load` event is fired.\n- `networkidle`: **DISCOURAGED** consider operation to be finished when there are no network connections for\n at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.\n- `commit`: Consider operation to be finished when network response is received and the document started loading.").optional().default(DEFAULT_WAIT_UNTIL3)}}outputSchema(){return{url:z53.string().describe("Contains the URL of the navigated page.").optional(),status:z53.number().int().positive().describe("Contains the status code of the navigated page (e.g., 200 for a success).").optional(),statusText:z53.string().describe('Contains the status text of the navigated page (e.g. usually an "OK" for a success).').optional(),ok:z53.boolean().describe("Contains a boolean stating whether the navigated page was successful (status in the range 200-299) or not.").optional()}}async handle(context,args){let response=await context.page.goto(args.url,{timeout:args.timeout,waitUntil:args.waitUntil});return{url:response?.url(),status:response?.status(),statusText:response?.statusText(),ok:response?.ok()}}};import{z as z54}from"zod";var DEFAULT_TIMEOUT_MS4=0,DEFAULT_WAIT_UNTIL4="load",Reload=class{static{__name(this,"Reload")}name(){return"navigation_reload"}description(){return`
|
|
561
|
-
Reloads the current page.
|
|
562
|
-
In case of multiple redirects, the navigation resolves with the response of the last redirect.
|
|
563
|
-
If the reload does not produce a response, returns empty response.
|
|
564
|
-
`}inputSchema(){return{timeout:z54.number().int().nonnegative().describe("Maximum operation time in milliseconds. Defaults to `0` - no timeout.").optional().default(DEFAULT_TIMEOUT_MS4),waitUntil:z54.enum(["load","domcontentloaded","networkidle","commit"]).describe("\nWhen to consider operation succeeded, defaults to `load`. Events can be either:\n- `domcontentloaded`: Consider operation to be finished when the `DOMContentLoaded` event is fired.\n- `load`: Consider operation to be finished when the `load` event is fired.\n- `networkidle`: **DISCOURAGED** consider operation to be finished when there are no network connections for\n at least `500` ms. Don't use this method for testing, rely on web assertions to assess readiness instead.\n- `commit`: Consider operation to be finished when network response is received and the document started loading.").optional().default(DEFAULT_WAIT_UNTIL4)}}outputSchema(){return{url:z54.string().describe("Contains the URL of the reloaded page.").optional(),status:z54.number().int().positive().describe("Contains the status code of the reloaded page (e.g., 200 for a success).").optional(),statusText:z54.string().describe('Contains the status text of the reloaded page (e.g. usually an "OK" for a success).').optional(),ok:z54.boolean().describe("Contains a boolean stating whether the reloaded page was successful (status in the range 200-299) or not.").optional()}}async handle(context,args){let response=await context.page.reload({timeout:args.timeout,waitUntil:args.waitUntil});return{url:response?.url(),status:response?.status(),statusText:response?.statusText(),ok:response?.ok()}}};var tools6=[new GoBack,new GoForward,new GoTo,new Reload];import{z as z55}from"zod";var GetConsoleMessages=class{static{__name(this,"GetConsoleMessages")}name(){return"o11y_get-console-messages"}description(){return"Retrieves console messages/logs from the browser with filtering options."}inputSchema(){return{type:z55.enum(getEnumKeyTuples(ConsoleMessageLevelName)).transform(createEnumTransformer(ConsoleMessageLevelName)).describe(`
|
|
565
|
-
Type of console messages to retrieve.
|
|
566
|
-
When specified, console messages with equal or higher levels are retrieved.
|
|
567
|
-
Valid values are (in ascending order according to their levels): ${getEnumKeyTuples(ConsoleMessageLevelName)}.`).optional(),search:z55.string().describe("Text to search for in console messages.").optional(),timestamp:z55.number().int().nonnegative().describe(`
|
|
568
|
-
Start time filter as a Unix epoch timestamp in milliseconds.
|
|
569
|
-
If provided, only console messages recorded at or after this timestamp will be returned.`).optional(),sequenceNumber:z55.number().int().nonnegative().describe(`
|
|
570
|
-
Sequence number for incremental retrieval.
|
|
571
|
-
If provided, only console messages with a sequence number greater than this value will be returned.
|
|
572
|
-
This allows clients to fetch console messages incrementally by passing the last received sequence number on subsequent requests.`).optional(),limit:z55.object({count:z55.number().int().nonnegative().default(100).describe(`
|
|
573
|
-
Count of the maximum number of console messages to return (default 100).
|
|
574
|
-
If the result exceeds this limit, it will be truncated.
|
|
575
|
-
0 means no count limit (return all).`),from:z55.enum(["start","end"]).default("end").describe(`
|
|
576
|
-
Controls which side is kept when truncation is applied.
|
|
577
|
-
"start" keeps the first N items (trims from the end).
|
|
578
|
-
"end" keeps the last N items (trims from the start).`)}).default({count:100,from:"end"}).describe("Maximum number of console messages to return. Default: last 100. Use count 0 for no limit.").optional()}}outputSchema(){return{messages:z55.array(z55.object({type:z55.string().describe("Type of the console message."),text:z55.string().describe("Text of the console message."),location:z55.object({url:z55.string().describe("URL of the resource."),lineNumber:z55.number().nonnegative().describe("0-based line number in the resource."),columnNumber:z55.number().nonnegative().describe("0-based column number in the resource.")}).describe("Location of the console message in the resource.").optional(),timestamp:z55.number().int().nonnegative().describe("Unix epoch timestamp (in milliseconds) of the console message."),sequenceNumber:z55.number().int().nonnegative().describe(`
|
|
579
|
-
A monotonically increasing sequence number assigned to each console message.
|
|
580
|
-
It reflects the order in which messages were captured and can be used by clients
|
|
581
|
-
to retrieve messages incrementally by requesting only those with a higher sequence
|
|
582
|
-
number than the last one received.`)}).describe("Console message item.")).describe("Retrieved console messages.")}}async handle(context,args){let consoleMessageLevelCodeThreshold=args.type?ConsoleMessageLevel[args.type]?.code:void 0,filteredConsoleMessages=context.getConsoleMessages().filter(msg=>{let filter=!0;return consoleMessageLevelCodeThreshold!==void 0&&(filter=msg.level.code>=consoleMessageLevelCodeThreshold),filter&&args.timestamp&&(filter=msg.timestamp>=args.timestamp),filter&&args.sequenceNumber&&(filter=msg.sequenceNumber>args.sequenceNumber),filter&&args.search&&(filter=msg.text.includes(args.search)),filter});return{messages:(args.limit?.count?args.limit.from==="start"?filteredConsoleMessages.slice(0,args.limit.count):filteredConsoleMessages.slice(-args.limit.count):filteredConsoleMessages).map(msg=>({type:msg.type,text:msg.text,location:msg.location?{url:msg.location.url,lineNumber:msg.location.lineNumber,columnNumber:msg.location.columnNumber}:void 0,timestamp:msg.timestamp,sequenceNumber:msg.sequenceNumber}))}}};import{z as z56}from"zod";var GetHttpRequests=class{static{__name(this,"GetHttpRequests")}name(){return"o11y_get-http-requests"}description(){return"Retrieves HTTP requests from the browser with filtering options."}inputSchema(){return{resourceType:z56.enum(getEnumKeyTuples(HttpResourceType)).transform(createEnumTransformer(HttpResourceType)).describe(`
|
|
583
|
-
Resource type of the HTTP requests to retrieve.
|
|
584
|
-
Valid values are: ${getEnumKeyTuples(HttpResourceType)}.`).optional(),status:z56.object({min:z56.number().int().positive().describe("Minimum status code of the HTTP requests to retrieve.").optional(),max:z56.number().int().positive().describe("Maximum status code of the HTTP requests to retrieve.").optional()}).describe("Status code of the HTTP requests to retrieve.").optional(),ok:z56.boolean().describe(`
|
|
585
|
-
Whether to retrieve successful or failed HTTP requests.
|
|
586
|
-
An HTTP request is considered successful only if its status code is 2XX.
|
|
587
|
-
Otherwise (non-2XX status code or no response at all because of timeout, network failure, etc ...) it is considered as failed.
|
|
588
|
-
When this flag is not set, all (successful and failed HTTP requests) are retrieved.`).optional(),timestamp:z56.number().int().nonnegative().describe(`
|
|
589
|
-
Start time filter as a Unix epoch timestamp in milliseconds.
|
|
590
|
-
If provided, only HTTP requests recorded at or after this timestamp will be returned.
|
|
591
|
-
`).optional(),sequenceNumber:z56.number().int().nonnegative().describe(`
|
|
592
|
-
Sequence number for incremental retrieval.
|
|
593
|
-
If provided, only HTTP requests with a sequence number greater than this value will be returned.
|
|
594
|
-
This allows clients to fetch HTTP requests incrementally by passing the last received sequence number on subsequent requests.
|
|
595
|
-
`).optional(),limit:z56.object({count:z56.number().int().nonnegative().default(100).describe(`
|
|
596
|
-
Count of the maximum number of HTTP requests to return (default 100).
|
|
597
|
-
If the result exceeds this limit, it will be truncated.
|
|
598
|
-
0 means no count limit (return all).`),from:z56.enum(["start","end"]).default("end").describe(`
|
|
599
|
-
Controls which side is kept when truncation is applied.
|
|
600
|
-
"start" keeps the first N items (trims from the end).
|
|
601
|
-
"end" keeps the last N items (trims from the start).`)}).default({count:100,from:"end"}).describe("Maximum number of HTTP requests to return. Default: last 100. Use count 0 for no limit.").optional()}}outputSchema(){return{requests:z56.array(z56.object({url:z56.string().describe("HTTP request url."),method:z56.enum(getEnumKeyTuples(HttpMethod)).describe(`HTTP request method. Valid values are: ${getEnumKeyTuples(HttpMethod)}`),headers:z56.record(z56.string(),z56.string()).describe("HTTP request headers as key-value pairs."),body:z56.string().describe("HTTP request body if available.").optional(),resourceType:z56.enum(getEnumKeyTuples(HttpResourceType)).describe(`
|
|
602
|
-
HTTP request resource type as it was perceived by the rendering engine.
|
|
603
|
-
Valid values are: ${getEnumKeyTuples(HttpResourceType)}`),failure:z56.string().describe("Error message of the HTTP request if failed.").optional(),duration:z56.number().describe('HTTP request duration in milliseconds. "-1" if not available (no response).').optional(),response:z56.object({status:z56.number().int().positive().describe("HTTP response status code."),statusText:z56.string().describe("HTTP response status text."),headers:z56.record(z56.string(),z56.string()).describe("HTTP response headers as key-value pairs."),body:z56.string().describe("HTTP response body if available.").optional()}).describe("HTTP response.").optional(),ok:z56.boolean().describe(`
|
|
604
|
-
Flag to represent whether the HTTP request successful or failed.
|
|
605
|
-
An HTTP request is considered successful only if its status code is 2XX.
|
|
606
|
-
Otherwise (non-2XX status code or no response at all because of timeout, network failure, etc ...) it is considered as failed.`).optional(),timestamp:z56.number().int().nonnegative().describe("Unix epoch timestamp (in milliseconds) of the HTTP request."),sequenceNumber:z56.number().int().nonnegative().describe(`
|
|
607
|
-
A monotonically increasing sequence number assigned to each HTTP request.
|
|
608
|
-
It reflects the order in which requests were captured and can be used by clients
|
|
609
|
-
to retrieve requests incrementally by requesting only those with a higher sequence
|
|
610
|
-
number than the last one received.`)}).describe("HTTP request item.")).describe("Retrieved HTTP requests.")}}async handle(context,args){let filteredHttpRequests=context.getHttpRequests().filter(req=>{let filter=!0;return filter&&args.resourceType&&(filter=req.resourceType===args.resourceType),filter&&args.status&&(filter&&args.status.min&&(filter=req.response?req.response.status>=args.status.min:!1),filter&&args.status.max&&(filter=req.response?req.response.status<=args.status.max:!1)),filter&&args.ok!==void 0&&(filter=req.ok),filter&&args.timestamp&&(filter=req.timestamp>=args.timestamp),filter&&args.sequenceNumber&&(filter=req.sequenceNumber>args.sequenceNumber),filter});return{requests:(args.limit?.count?args.limit.from==="start"?filteredHttpRequests.slice(0,args.limit.count):filteredHttpRequests.slice(-args.limit.count):filteredHttpRequests).map(req=>({url:req.url,method:req.method,headers:req.headers,body:req.body,resourceType:req.resourceType,failure:req.failure,duration:req.duration,response:req.response?{status:req.response.status,statusText:req.response.statusText,headers:req.response.headers,body:req.response.body}:void 0,ok:req.ok,timestamp:req.timestamp,sequenceNumber:req.sequenceNumber}))}}};import{z as z57}from"zod";var GetTraceId=class{static{__name(this,"GetTraceId")}name(){return"o11y_get-trace-id"}description(){return"Gets the OpenTelemetry compatible trace id of the current session."}inputSchema(){return{}}outputSchema(){return{traceId:z57.string().describe("The OpenTelemetry compatible trace id of the current session if available.").optional()}}async handle(context,args){return{traceId:await context.getTraceId()}}};import{z as z58}from"zod";var DEFAULT_WAIT_MS=0,MAX_WAIT_MS=3e4;function rateMs(value,good,poor){return typeof value!="number"||!Number.isFinite(value)?{rating:"not_available",value:null,unit:"ms",thresholds:{good,poor}}:value<=good?{rating:"good",value,unit:"ms",thresholds:{good,poor}}:value>poor?{rating:"poor",value,unit:"ms",thresholds:{good,poor}}:{rating:"needs_improvement",value,unit:"ms",thresholds:{good,poor}}}__name(rateMs,"rateMs");function rateScore(value,good,poor){return typeof value!="number"||!Number.isFinite(value)?{rating:"not_available",value:null,unit:"score",thresholds:{good,poor}}:value<=good?{rating:"good",value,unit:"score",thresholds:{good,poor}}:value>poor?{rating:"poor",value,unit:"score",thresholds:{good,poor}}:{rating:"needs_improvement",value,unit:"score",thresholds:{good,poor}}}__name(rateScore,"rateScore");function formatRating(r){return r==="needs_improvement"?"needs improvement":r==="not_available"?"not available":r}__name(formatRating,"formatRating");function buildRecommendations(params){let lcpRating=params.ratings.lcp.rating,inpRating=params.ratings.inp.rating,clsRating=params.ratings.cls.rating,ttfbRating=params.ratings.ttfb.rating,fcpRating=params.ratings.fcp.rating,coreWebVitalsPassed=lcpRating==="good"&&inpRating==="good"&&clsRating==="good",summary=[];coreWebVitalsPassed?summary.push("Core Web Vitals look good (LCP, INP and CLS are all within recommended thresholds)."):summary.push("Core Web Vitals need attention. Focus on the worst-rated metric first (LCP, INP, or CLS).");let lcp=[],inp=[],cls=[],ttfb=[],fcp=[],general=[];return params.lcpSelectorHint&&general.push(`LCP element hint (best-effort): ${params.lcpSelectorHint}`),lcpRating==="poor"||lcpRating==="needs_improvement"?(lcp.push("Optimize the LCP element (often the hero image, headline, or main content above the fold)."),lcp.push("Reduce render-blocking resources (critical CSS, JS). Consider inlining critical CSS and deferring non-critical JS."),lcp.push('Preload the LCP resource (e.g., <link rel="preload"> for the hero image/font) and ensure it is discoverable without heavy JS.'),lcp.push("Improve server response and caching. A slow TTFB often delays LCP."),lcp.push("Avoid client-only rendering for above-the-fold content when possible; stream/SSR critical content.")):lcpRating==="good"?lcp.push("LCP is within the recommended threshold. Keep the above-the-fold path lean."):lcp.push("LCP is not available in this browser/session. Consider using Chromium or a page-load scenario that produces LCP entries."),inpRating==="poor"||inpRating==="needs_improvement"?(inp.push("Break up long main-thread tasks. Aim to keep tasks under ~50ms (split work, yield to the event loop)."),inp.push("Reduce expensive work in input handlers (click, pointer, key events). Move non-urgent work to idle time."),inp.push("Avoid synchronous layout thrash during interactions (batch DOM reads/writes, reduce forced reflow)."),inp.push("Defer heavy third-party scripts and reduce JavaScript bundle size to improve responsiveness.")):inpRating==="good"?inp.push("INP is within the recommended threshold. Keep interaction handlers lightweight."):inp.push("INP is not available in this browser/session. It requires Event Timing support and user interactions."),clsRating==="poor"||clsRating==="needs_improvement"?(cls.push("Reserve space for images/iframes/ads (set width/height or aspect-ratio) to prevent layout jumps."),cls.push("Avoid inserting content above existing content unless it is in response to a user interaction."),cls.push("Use stable font loading (font-display: swap/optional) and consider preloading critical fonts to reduce text shifts."),cls.push("Be careful with late-loading banners/toasts; render them in reserved containers.")):clsRating==="good"?cls.push("CLS is within the recommended threshold. Keep layout stable during load and async updates."):cls.push("CLS is not available in this browser/session. Consider Chromium or a scenario with visible layout changes."),ttfbRating==="poor"||ttfbRating==="needs_improvement"?(ttfb.push("Improve backend latency: reduce server processing time, optimize DB queries, and eliminate unnecessary middleware."),ttfb.push("Enable CDN/edge caching where possible. Use caching headers and avoid dynamic responses for static content."),ttfb.push("Reduce cold-start and TLS overhead (keep-alive, warm pools, edge runtimes).")):ttfbRating==="good"?ttfb.push("TTFB is good. Backend/network latency is unlikely to be the primary bottleneck."):ttfb.push("TTFB is not available in this browser/session."),fcpRating==="poor"||fcpRating==="needs_improvement"?(fcp.push("Reduce render-blocking CSS/JS and prioritize critical content for first paint."),fcp.push("Optimize above-the-fold resources and avoid large synchronous scripts during initial load."),fcp.push("Consider code-splitting and preloading critical assets to improve first paint.")):fcpRating==="good"?fcp.push("FCP is good. The page provides early visual feedback."):fcp.push("FCP is not available in this browser/session."),general.push("For reliable debugging, capture metrics after navigation and after user actions that trigger loading or layout changes."),general.push("If values look unstable, try adding waitMs (e.g., 1000-3000) and re-measure after the UI settles."),{coreWebVitalsPassed,summary,lcp,inp,cls,ttfb,fcp,general}}__name(buildRecommendations,"buildRecommendations");var GetWebVitals=class{static{__name(this,"GetWebVitals")}name(){return"o11y_get-web-vitals"}description(){return`
|
|
611
|
-
Collects Web Vitals-style performance metrics and provides recommendations based on Google's thresholds.
|
|
612
|
-
|
|
613
|
-
Core Web Vitals:
|
|
614
|
-
- LCP (ms): Largest Contentful Paint (good <= 2500, poor > 4000)
|
|
615
|
-
- INP (ms): Interaction to Next Paint (good <= 200, poor > 500)
|
|
616
|
-
- CLS (score): Cumulative Layout Shift (good <= 0.1, poor > 0.25)
|
|
617
|
-
|
|
618
|
-
Supporting diagnostics:
|
|
619
|
-
- TTFB (ms): Time to First Byte (good <= 800, poor > 1800)
|
|
620
|
-
- FCP (ms): First Contentful Paint (good <= 1800, poor > 3000)
|
|
621
|
-
|
|
622
|
-
Guidance:
|
|
623
|
-
- Call after navigation and after user actions.
|
|
624
|
-
- If you need more stable LCP/CLS/INP, pass waitMs (e.g. 1000-3000).
|
|
625
|
-
- Some metrics may be unavailable depending on browser support and whether interactions occurred.
|
|
626
|
-
`.trim()}inputSchema(){return{waitMs:z58.number().int().min(0).max(MAX_WAIT_MS).optional().default(DEFAULT_WAIT_MS).describe("Optional wait duration in milliseconds before reading metrics (default: 0)."),includeDebug:z58.boolean().optional().default(!1).describe("If true, returns additional debug details such as entry counts and LCP element hint.")}}outputSchema(){let ratingSchema=z58.object({rating:z58.enum(["good","needs_improvement","poor","not_available"]).describe("Rating based on Google thresholds."),value:z58.number().nullable().describe("Metric value (null if unavailable)."),unit:z58.enum(["ms","score"]).describe("Unit of the metric."),thresholds:z58.object({good:z58.number().describe('Upper bound for the "good" rating.'),poor:z58.number().describe('Lower bound for the "poor" rating.')}).describe("Thresholds used for rating.")});return{url:z58.string().describe("Current page URL."),title:z58.string().describe("Current page title."),timestampMs:z58.number().int().describe("Unix epoch timestamp (ms) when the metrics were captured."),metrics:z58.object({lcpMs:z58.number().nullable().describe("Largest Contentful Paint in milliseconds."),inpMs:z58.number().nullable().describe("Interaction to Next Paint in milliseconds (best-effort approximation)."),cls:z58.number().nullable().describe("Cumulative Layout Shift score."),ttfbMs:z58.number().nullable().describe("Time to First Byte in milliseconds."),fcpMs:z58.number().nullable().describe("First Contentful Paint in milliseconds.")}).describe("Raw metric values (null if unavailable)."),ratings:z58.object({lcp:ratingSchema.describe("LCP rating."),inp:ratingSchema.describe("INP rating."),cls:ratingSchema.describe("CLS rating."),ttfb:ratingSchema.describe("TTFB rating."),fcp:ratingSchema.describe("FCP rating.")}).describe("Ratings computed from Google thresholds."),recommendations:z58.object({coreWebVitalsPassed:z58.boolean().describe('True if all Core Web Vitals are rated "good".'),summary:z58.array(z58.string()).describe("High-level summary and prioritization guidance."),lcp:z58.array(z58.string()).describe("Recommendations for improving LCP."),inp:z58.array(z58.string()).describe("Recommendations for improving INP."),cls:z58.array(z58.string()).describe("Recommendations for improving CLS."),ttfb:z58.array(z58.string()).describe("Recommendations for improving TTFB."),fcp:z58.array(z58.string()).describe("Recommendations for improving FCP."),general:z58.array(z58.string()).describe("General measurement and debugging notes.")}).describe("Recommendations based on the measured values and their ratings."),notes:z58.array(z58.string()).describe("Notes about metric availability, browser limitations, and interpretation."),debug:z58.object({waitMs:z58.number().int().describe("Actual wait duration used before reading metrics."),entries:z58.object({navigation:z58.number().int().describe("Count of navigation entries."),paint:z58.number().int().describe("Count of paint entries."),lcp:z58.number().int().describe("Count of largest-contentful-paint entries."),layoutShift:z58.number().int().describe("Count of layout-shift entries."),eventTiming:z58.number().int().describe("Count of event timing entries.")}).describe("Counts of PerformanceEntry types used to compute metrics."),lastLcpSelectorHint:z58.string().nullable().describe("Best-effort selector hint for the last LCP element (if available)."),lastLcpTagName:z58.string().nullable().describe("Tag name of the last LCP element (if available).")}).optional().describe("Optional debug details.")}}async handle(context,args){let waitMs=args.waitMs??DEFAULT_WAIT_MS,includeDebug=args.includeDebug===!0,pageUrl=String(context.page.url()),pageTitle=String(await context.page.title()),timestampMs=Date.now(),result=await context.page.evaluate(async params=>{let waitMsEval=params.waitMsEval,includeDebugEval=params.includeDebugEval,notes2=[],sleep=__name(ms=>new Promise(resolve=>{setTimeout(()=>resolve(),ms)}),"sleep");waitMsEval>0&&await sleep(waitMsEval);let ttfbMs2=null,navEntries=performance.getEntriesByType("navigation")??[];if(navEntries.length>0){let nav=navEntries[0];typeof nav.responseStart=="number"&&nav.responseStart>=0&&(ttfbMs2=nav.responseStart)}else notes2.push("TTFB: navigation entries not available (older browser or restricted timing).");let fcpMs2=null,paintEntries=performance.getEntriesByType("paint")??[],fcp=paintEntries.find(e=>e.name==="first-contentful-paint");fcp&&typeof fcp.startTime=="number"?fcpMs2=fcp.startTime:notes2.push("FCP: paint entries not available (browser may not support Paint Timing).");let lcpMs2=null,lastLcpEl=null,lcpEntries=performance.getEntriesByType("largest-contentful-paint")??[];if(lcpEntries.length>0){let last=lcpEntries[lcpEntries.length-1];typeof last.startTime=="number"&&(lcpMs2=last.startTime),last.element&&last.element instanceof Element&&(lastLcpEl=last.element)}else notes2.push("LCP: largest-contentful-paint entries not available (requires LCP support).");let selectorHintFor=__name(el=>{if(!el)return null;let dt=el.getAttribute("data-testid")||el.getAttribute("data-test-id")||el.getAttribute("data-test");if(dt&&dt.trim())return'[data-testid="'+dt.replace(/"/g,'\\"')+'"]';let ds=el.getAttribute("data-selector");if(ds&&ds.trim())return'[data-selector="'+ds.replace(/"/g,'\\"')+'"]';if(el.id)try{return"#"+CSS.escape(el.id)}catch{return"#"+String(el.id)}return el.tagName?el.tagName.toLowerCase():null},"selectorHintFor"),cls2=null,layoutShiftEntries=performance.getEntriesByType("layout-shift")??[];if(layoutShiftEntries.length>0){let sum=0;for(let e of layoutShiftEntries)e&&e.hadRecentInput===!0||typeof e.value=="number"&&(sum+=e.value);cls2=sum}else notes2.push("CLS: layout-shift entries not available (requires Layout Instability API support).");let inpMs2=null,eventEntries=performance.getEntriesByType("event")??[];if(eventEntries.length>0){let maxDur=0;for(let e of eventEntries){let interactionId=typeof e.interactionId=="number"?e.interactionId:0,duration=typeof e.duration=="number"?e.duration:0;interactionId>0&&duration>maxDur&&(maxDur=duration)}maxDur>0?inpMs2=maxDur:notes2.push("INP: event timing entries exist but no interactionId-based events were found.")}else notes2.push("INP: event timing entries not available (requires Event Timing API support).");notes2.length===0?notes2.push("All requested metrics were available."):notes2.push("Some metrics may be null due to browser support limitations.");let out={metrics:{ttfbMs:ttfbMs2,fcpMs:fcpMs2,lcpMs:lcpMs2,cls:cls2,inpMs:inpMs2},notes:notes2,lcp:{selectorHint:selectorHintFor(lastLcpEl),tagName:lastLcpEl?String(lastLcpEl.tagName).toLowerCase():null},debug:{waitMs:waitMsEval,entries:{navigation:navEntries.length,paint:paintEntries.length,lcp:lcpEntries.length,layoutShift:layoutShiftEntries.length,eventTiming:eventEntries.length}}};return includeDebugEval?(out.debug.lastLcpSelectorHint=out.lcp.selectorHint,out.debug.lastLcpTagName=out.lcp.tagName):delete out.debug,out},{waitMsEval:waitMs,includeDebugEval:includeDebug}),lcpMs=typeof result?.metrics?.lcpMs=="number"?result.metrics.lcpMs:null,inpMs=typeof result?.metrics?.inpMs=="number"?result.metrics.inpMs:null,cls=typeof result?.metrics?.cls=="number"?result.metrics.cls:null,ttfbMs=typeof result?.metrics?.ttfbMs=="number"?result.metrics.ttfbMs:null,fcpMs=typeof result?.metrics?.fcpMs=="number"?result.metrics.fcpMs:null,ratings={lcp:rateMs(lcpMs,2500,4e3),inp:rateMs(inpMs,200,500),cls:rateScore(cls,.1,.25),ttfb:rateMs(ttfbMs,800,1800),fcp:rateMs(fcpMs,1800,3e3)},lcpHint=typeof result?.lcp?.selectorHint=="string"?result.lcp.selectorHint:null,recommendations=buildRecommendations({ratings,lcpSelectorHint:lcpHint}),notes=Array.isArray(result?.notes)?result.notes:[];notes.push(`Ratings: LCP=${formatRating(ratings.lcp.rating)}, INP=${formatRating(ratings.inp.rating)}, CLS=${formatRating(ratings.cls.rating)}.`);let output={url:pageUrl,title:pageTitle,timestampMs,metrics:{lcpMs,inpMs,cls,ttfbMs,fcpMs},ratings,recommendations,notes};return includeDebug&&result?.debug&&(output.debug=result.debug),output}};import crypto2 from"node:crypto";function newTraceId(){return crypto2.randomBytes(16).toString("hex")}__name(newTraceId,"newTraceId");import{z as z59}from"zod";var NewTraceId=class{static{__name(this,"NewTraceId")}name(){return"o11y_new-trace-id"}description(){return"Generates new OpenTelemetry compatible trace id and sets it to the current session."}inputSchema(){return{}}outputSchema(){return{traceId:z59.string().describe("The generated new OpenTelemetry compatible trace id.")}}async handle(context,args){let traceId=newTraceId();return await context.setTraceId(traceId),{traceId}}};import{z as z60}from"zod";var SetTraceId=class{static{__name(this,"SetTraceId")}name(){return"o11y_set-trace-id"}description(){return"Sets the OpenTelemetry compatible trace id of the current session."}inputSchema(){return{traceId:z60.string().describe("The OpenTelemetry compatible trace id to be set.")}}outputSchema(){return{}}async handle(context,args){return await context.setTraceId(args.traceId),{}}};var tools7=[new GetConsoleMessages,new GetHttpRequests,new GetTraceId,new GetWebVitals,new NewTraceId,new SetTraceId];import{z as z61}from"zod";var DEFAULT_MAX_STACK_DEPTH=30,DEFAULT_MAX_PROPS_PREVIEW_CHARS=2e3,DEFAULT_INCLUDE_PROPS_PREVIEW=!0,DEFAULT_MAX_ELEMENT_PATH_DEPTH=25,DEFAULT_MAX_FIBER_SUBTREE_NODES_TO_SCAN=5e4,GetComponentForElement=class{static{__name(this,"GetComponentForElement")}name(){return"react_get-component-for-element"}description(){return`
|
|
627
|
-
Finds the React component(s) associated with a DOM element using React Fiber (best-effort).
|
|
628
|
-
|
|
629
|
-
How it works:
|
|
630
|
-
- Resolve a DOM element by CSS selector OR by (x,y) using elementFromPoint()
|
|
631
|
-
- Attempt to locate React Fiber pointers on that element (e.g. __reactFiber$*)
|
|
632
|
-
- If not present, walk up ancestor elements to find the nearest React-owned host node
|
|
633
|
-
|
|
634
|
-
Key correctness fix:
|
|
635
|
-
- If fiber is found on an ANCESTOR element, we scan that fiber subtree to locate the EXACT host fiber
|
|
636
|
-
where fiber.stateNode === target DOM element, then build the component stack from that host fiber.
|
|
637
|
-
This reduces unrelated components appearing in the returned stack.
|
|
638
|
-
|
|
639
|
-
What to expect (important for AI debugging):
|
|
640
|
-
- React Fiber is not a public API; results are best-effort and can differ by build (dev/prod).
|
|
641
|
-
- Component names may come from displayName, wrappers, third-party libraries, or minified production builds.
|
|
642
|
-
- wrappersDetected/wrapperFrames help interpret memo/forwardRef/context boundaries that can otherwise look confusing.
|
|
643
|
-
- If hostMapping.strategy is "ancestor-fallback", the stack may include unrelated frames; try a more specific selector
|
|
644
|
-
or target a deeper DOM node to improve mapping accuracy.
|
|
645
|
-
`.trim()}inputSchema(){return{selector:z61.string().optional().describe("CSS selector for the target element. If provided, takes precedence over x/y."),x:z61.number().int().optional().describe("Viewport X coordinate in CSS pixels. Used when selector is not provided."),y:z61.number().int().optional().describe("Viewport Y coordinate in CSS pixels. Used when selector is not provided."),maxStackDepth:z61.number().int().positive().optional().default(DEFAULT_MAX_STACK_DEPTH).describe("Maximum number of component frames to return in the component stack."),includePropsPreview:z61.boolean().optional().default(DEFAULT_INCLUDE_PROPS_PREVIEW).describe("If true, includes a best-effort, truncated props preview for the nearest component."),maxPropsPreviewChars:z61.number().int().positive().optional().default(DEFAULT_MAX_PROPS_PREVIEW_CHARS).describe("Maximum characters for props preview (after safe stringification).")}}outputSchema(){return{target:z61.object({selector:z61.string().nullable(),point:z61.object({x:z61.number().int().nullable(),y:z61.number().int().nullable()}),found:z61.boolean(),domHint:z61.string().nullable(),elementPath:z61.string().nullable()}),react:z61.object({detected:z61.boolean(),detectionReason:z61.string(),fiberKey:z61.string().nullable(),hostMapping:z61.object({fiberOnTargetElement:z61.boolean().describe("Whether the initial fiber pointer was found directly on the target element."),anchorDomHint:z61.string().nullable().describe("DOM hint of the element where fiber pointer was found (target or ancestor)."),targetDomHint:z61.string().nullable().describe("DOM hint of the actual target element."),hostFiberMatchedTarget:z61.boolean().describe("Whether we found the exact host fiber for target element (fiber.stateNode === targetEl) via subtree scan."),subtreeScanNodesScanned:z61.number().int().describe("Number of fiber nodes scanned during subtree search."),subtreeScanMaxNodes:z61.number().int().describe("Maximum fiber nodes allowed to scan (safety cap)."),strategy:z61.enum(["direct-on-target","ancestor-subtree-scan","ancestor-fallback"]).describe("Mapping strategy used to produce the final stack.")}),nearestComponent:z61.object({name:z61.string().nullable(),displayName:z61.string().nullable(),kind:z61.enum(["function","class","unknown"]),debugSource:z61.object({fileName:z61.string().optional(),lineNumber:z61.number().int().optional(),columnNumber:z61.number().int().optional()}).optional(),propsPreview:z61.string().optional()}).nullable(),componentStack:z61.array(z61.object({name:z61.string().nullable(),displayName:z61.string().nullable(),kind:z61.enum(["function","class","unknown"]),debugSource:z61.object({fileName:z61.string().optional(),lineNumber:z61.number().int().optional(),columnNumber:z61.number().int().optional()}).optional()})),componentStackText:z61.string(),wrappersDetected:z61.array(z61.string()),wrapperFrames:z61.array(z61.object({wrapper:z61.string(),frameIndex:z61.number().int(),frameLabel:z61.string()})),notes:z61.array(z61.string())})}}async handle(context,args){let selector=typeof args.selector=="string"&&args.selector.trim()?args.selector.trim():void 0,x=typeof args.x=="number"&&Number.isFinite(args.x)?Math.floor(args.x):void 0,y=typeof args.y=="number"&&Number.isFinite(args.y)?Math.floor(args.y):void 0;if(!selector&&(typeof x!="number"||typeof y!="number"))throw new Error("Provide either selector, or both x and y for elementFromPoint.");let maxStackDepth=typeof args.maxStackDepth=="number"&&args.maxStackDepth>0?Math.floor(args.maxStackDepth):DEFAULT_MAX_STACK_DEPTH,includePropsPreview=args.includePropsPreview===void 0?DEFAULT_INCLUDE_PROPS_PREVIEW:args.includePropsPreview===!0,maxPropsPreviewChars=typeof args.maxPropsPreviewChars=="number"&&Number.isFinite(args.maxPropsPreviewChars)&&args.maxPropsPreviewChars>0?Math.floor(args.maxPropsPreviewChars):DEFAULT_MAX_PROPS_PREVIEW_CHARS;return await context.page.evaluate(params=>{let selectorEval=params.selectorEval,xEval=params.xEval,yEval=params.yEval,maxStackDepthEval=params.maxStackDepthEval,includePropsPreviewEval=params.includePropsPreviewEval,maxPropsPreviewCharsEval=params.maxPropsPreviewCharsEval,maxElementPathDepthEval=params.maxElementPathDepthEval,maxFiberNodesToScanEval=params.maxFiberNodesToScanEval,notes=[];function domHint(el){if(!el)return null;let tag=el.tagName.toLowerCase(),idVal=el.id&&el.id.trim()?"#"+el.id.trim():"",clsRaw=typeof el.className=="string"?el.className:"",cls=clsRaw?"."+clsRaw.trim().split(/\s+/).slice(0,4).join("."):"";return tag+idVal+cls}__name(domHint,"domHint");function buildElementPath(el,maxDepth){if(!el)return null;let parts=[],cur2=el,depth=0;for(;cur2&&depth<maxDepth;){let tag=cur2.tagName?cur2.tagName.toLowerCase():"unknown",idVal=cur2.id&&cur2.id.trim()?"#"+cur2.id.trim():"",clsRaw=typeof cur2.className=="string"?cur2.className:"",clsList=clsRaw?clsRaw.trim().split(/\s+/).filter(Boolean).slice(0,3):[],cls=clsList.length>0?"."+clsList.join("."):"",nth="";try{let parent=cur2.parentElement;if(parent){let siblings=Array.from(parent.children).filter(c=>c.tagName===cur2.tagName);if(siblings.length>1){let idx=siblings.indexOf(cur2)+1;idx>0&&(nth=`:nth-of-type(${idx})`)}}}catch{}parts.push(`${tag}${idVal}${cls}${nth}`),cur2=cur2.parentElement,depth++}return parts.reverse(),parts.join(" > ")}__name(buildElementPath,"buildElementPath");function findFiberKeyOn(el){if(!el)return null;let keys=Object.getOwnPropertyNames(el);for(let k of keys)if(k.startsWith("__reactFiber$")||k.startsWith("__reactInternalInstance$"))return k;return null}__name(findFiberKeyOn,"findFiberKeyOn");function findFiberForElement(start){if(!start)return null;let directKey=findFiberKeyOn(start);if(directKey){let fiber=start[directKey];if(fiber)return{fiber,fiberKey:directKey,onTarget:!0,anchorEl:start}}let cur2=start;for(;cur2;){let k=findFiberKeyOn(cur2);if(k){let fiber=cur2[k];if(fiber)return{fiber,fiberKey:k,onTarget:!1,anchorEl:cur2}}cur2=cur2.parentElement}return null}__name(findFiberForElement,"findFiberForElement");function findHostFiberForDomElement(subtreeRootFiber,targetEl2,maxNodesToScan){if(!subtreeRootFiber)return{hostFiber:null,scanned:0,found:!1};if(subtreeRootFiber.stateNode===targetEl2)return{hostFiber:subtreeRootFiber,scanned:1,found:!0};let queue=[],visited=new Set;queue.push(subtreeRootFiber),visited.add(subtreeRootFiber);let scanned=0;for(;queue.length>0;){let f=queue.shift();if(scanned++,f&&f.stateNode===targetEl2)return{hostFiber:f,scanned,found:!0};if(scanned>=maxNodesToScan)return{hostFiber:null,scanned,found:!1};let child=f?f.child:null;child&&!visited.has(child)&&(visited.add(child),queue.push(child));let sibling=f?f.sibling:null;sibling&&!visited.has(sibling)&&(visited.add(sibling),queue.push(sibling))}return{hostFiber:null,scanned,found:!1}}__name(findHostFiberForDomElement,"findHostFiberForDomElement");function isClassComponentType(t){if(!t)return!1;let proto=t.prototype;return!!(proto&&proto.isReactComponent)}__name(isClassComponentType,"isClassComponentType");function typeDisplayName(t){if(!t)return null;if(typeof t=="function"){let dn=t.displayName;return typeof dn=="string"&&dn.trim()?dn.trim():typeof t.name=="string"&&t.name.trim()?t.name.trim():"Anonymous"}if(typeof t=="object"){let dn=t.displayName;if(typeof dn=="string"&&dn.trim())return dn.trim();let render=t.render;if(typeof render=="function"){let rdn=render.displayName;return typeof rdn=="string"&&rdn.trim()?rdn.trim():typeof render.name=="string"&&render.name.trim()?render.name.trim():"Anonymous"}}return null}__name(typeDisplayName,"typeDisplayName");function typeName(t){if(!t)return null;if(typeof t=="function")return typeof t.name=="string"&&t.name.trim()?t.name.trim():null;if(typeof t=="object"){let render=t.render;return typeof render=="function"&&typeof render.name=="string"&&render.name.trim()?render.name.trim():null}return null}__name(typeName,"typeName");function unwrapType(t){if(!t)return t;if(typeof t=="object"){let render=t.render;if(typeof render=="function")return render}return t}__name(unwrapType,"unwrapType");function isMeaningfulComponentFiber(f){return f?typeof unwrapType(f.type??f.elementType)=="function":!1}__name(isMeaningfulComponentFiber,"isMeaningfulComponentFiber");function inferKind(f){if(!f)return"unknown";let t=unwrapType(f.type??f.elementType);return typeof t=="function"?isClassComponentType(t)?"class":"function":"unknown"}__name(inferKind,"inferKind");function getDebugSource(f){let ds=f?f._debugSource:void 0;if(!ds||typeof ds!="object")return;let out={};return typeof ds.fileName=="string"&&(out.fileName=ds.fileName),typeof ds.lineNumber=="number"&&(out.lineNumber=ds.lineNumber),typeof ds.columnNumber=="number"&&(out.columnNumber=ds.columnNumber),Object.keys(out).length>0?out:void 0}__name(getDebugSource,"getDebugSource");function safeStringify(v,maxChars){let seen=new WeakSet;function helper(x2,depth){if(x2===null)return null;let t=typeof x2;if(t==="string")return x2.length>500?x2.slice(0,500)+"\u2026":x2;if(t==="number"||t==="boolean")return x2;if(t==="bigint")return String(x2);if(t!=="undefined"){if(t==="function")return"[function]";if(t==="symbol")return String(x2);if(t==="object"){if(x2 instanceof Element)return"[Element "+(x2.tagName?x2.tagName.toLowerCase():"")+"]";if(x2 instanceof Window)return"[Window]";if(x2 instanceof Document)return"[Document]";if(x2 instanceof Date)return x2.toISOString();if(seen.has(x2))return"[circular]";if(seen.add(x2),Array.isArray(x2))return depth<=0?"[array len="+x2.length+"]":x2.slice(0,20).map(it=>helper(it,depth-1));if(depth<=0)return"[object]";let out={},keys=Object.keys(x2).slice(0,40);for(let k of keys)try{out[k]=helper(x2[k],depth-1)}catch{out[k]="[unreadable]"}return out}return String(x2)}}__name(helper,"helper");let s="";try{s=JSON.stringify(helper(v,2))}catch{try{s=String(v)}catch{s="[unserializable]"}}return s.length>maxChars?s.slice(0,maxChars)+"\u2026(truncated)":s}__name(safeStringify,"safeStringify");function stackTextFromFrames(frames){return frames.map(f=>{let dn=f?.displayName,nm=f?.name;return typeof dn=="string"&&dn.trim()?dn.trim():typeof nm=="string"&&nm.trim()?nm.trim():"Anonymous"}).filter(x2=>!!x2).reverse().join(" > ")}__name(stackTextFromFrames,"stackTextFromFrames");function frameFromFiber(f){let t=unwrapType(f.type??f.elementType),name=typeName(t),displayName=typeDisplayName(t),kind=inferKind(f),debugSource=getDebugSource(f),frame={name,displayName,kind};return debugSource&&(frame.debugSource=debugSource),frame}__name(frameFromFiber,"frameFromFiber");function makeFrameKey(frame){let dn=frame.displayName?frame.displayName:"",nm=frame.name?frame.name:"",src=frame.debugSource,srcKey=src&&typeof src=="object"?`${String(src.fileName??"")}:${String(src.lineNumber??"")}:${String(src.columnNumber??"")}`:"";return`${dn}|${nm}|${frame.kind}|${srcKey}`}__name(makeFrameKey,"makeFrameKey");function collapseConsecutiveDuplicates(frames){let out=[],lastKey=null;for(let f of frames){let k=makeFrameKey(f);lastKey&&k===lastKey||(out.push(f),lastKey=k)}return out}__name(collapseConsecutiveDuplicates,"collapseConsecutiveDuplicates");function detectWrappers(frames){let found=new Set;function canonicalAdd(key){let v=key.trim().toLowerCase();v&&found.add(v)}__name(canonicalAdd,"canonicalAdd");for(let f of frames){let label=typeof f.displayName=="string"&&f.displayName.trim()?f.displayName.trim():typeof f.name=="string"&&f.name.trim()?f.name.trim():"";if(!label)continue;let l=label.toLowerCase();/^memo(\(|$)/i.test(label)&&canonicalAdd("memo"),l.includes("forwardref")&&canonicalAdd("forwardref"),l.includes(".provider")&&canonicalAdd("context-provider"),l.includes(".consumer")&&canonicalAdd("context-consumer"),l.includes("suspense")&&canonicalAdd("suspense"),l.includes("fragment")&&canonicalAdd("fragment"),l.includes("strictmode")&&canonicalAdd("strictmode"),l.includes("profiler")&&canonicalAdd("profiler")}let out=Array.from(found);return out.sort((a,b)=>a<b?-1:a>b?1:0),out}__name(detectWrappers,"detectWrappers");function findWrapperFrames(frames,wrappersDetected2){let out=[],wrappers=new Set(wrappersDetected2.map(w=>w.toLowerCase()));for(let i=0;i<frames.length;i++){let f=frames[i],label=f.displayName&&f.displayName.trim()?f.displayName.trim():f.name&&f.name.trim()?f.name.trim():"Anonymous",l=label.toLowerCase();for(let w of wrappers){let hit=!1;w==="memo"?hit=/^memo(\(|$)/i.test(label):w==="forwardref"?hit=l.includes("forwardref"):w==="context-provider"?hit=l.includes(".provider"):w==="context-consumer"?hit=l.includes(".consumer"):w==="suspense"?hit=l.includes("suspense"):w==="fragment"?hit=l.includes("fragment"):w==="strictmode"?hit=l.includes("strictmode"):w==="profiler"&&(hit=l.includes("profiler")),hit&&out.push({wrapper:w,frameIndex:i,frameLabel:label})}}return out}__name(findWrapperFrames,"findWrapperFrames");let targetEl=null;if(selectorEval&&selectorEval.trim())try{targetEl=document.querySelector(selectorEval)}catch{targetEl=null}else typeof xEval=="number"&&typeof yEval=="number"&&(targetEl=document.elementFromPoint(xEval,yEval));let foundEl=!!targetEl,targetHint=domHint(targetEl),elementPath=buildElementPath(targetEl,maxElementPathDepthEval);if(!foundEl)return{target:{selector:selectorEval??null,point:{x:typeof xEval=="number"?xEval:null,y:typeof yEval=="number"?yEval:null},found:!1,domHint:null,elementPath:null},react:{detected:!1,detectionReason:"Target element not found.",fiberKey:null,hostMapping:{fiberOnTargetElement:!1,anchorDomHint:null,targetDomHint:null,hostFiberMatchedTarget:!1,subtreeScanNodesScanned:0,subtreeScanMaxNodes:maxFiberNodesToScanEval,strategy:"ancestor-fallback"},nearestComponent:null,componentStack:[],componentStackText:"",wrappersDetected:[],wrapperFrames:[],notes:["No DOM element could be resolved; cannot inspect React."]}};let fiberHit=findFiberForElement(targetEl);if(!fiberHit)return notes.push("No React fiber pointer found on the element or its ancestors."),notes.push("This can happen if the page is not React, uses a different renderer, or runs with hardened/minified internals."),{target:{selector:selectorEval??null,point:{x:typeof xEval=="number"?xEval:null,y:typeof yEval=="number"?yEval:null},found:!0,domHint:targetHint,elementPath},react:{detected:!1,detectionReason:"React fiber not found on element/ancestors.",fiberKey:null,hostMapping:{fiberOnTargetElement:!1,anchorDomHint:null,targetDomHint:targetHint,hostFiberMatchedTarget:!1,subtreeScanNodesScanned:0,subtreeScanMaxNodes:maxFiberNodesToScanEval,strategy:"ancestor-fallback"},nearestComponent:null,componentStack:[],componentStackText:"",wrappersDetected:[],wrapperFrames:[],notes}};let hostFiber=fiberHit.fiber,hostMatch=fiberHit.onTarget,subtreeScanned=0,anchorHint=domHint(fiberHit.anchorEl),strategy="direct-on-target";if(!fiberHit.onTarget){strategy="ancestor-fallback";let scanRes=findHostFiberForDomElement(fiberHit.fiber,targetEl,maxFiberNodesToScanEval);subtreeScanned=scanRes.scanned,scanRes.found&&scanRes.hostFiber?(hostFiber=scanRes.hostFiber,hostMatch=!0,strategy="ancestor-subtree-scan",notes.push(`Mapped target DOM element to host fiber by scanning fiber subtree (scanned=${subtreeScanned}).`)):(hostMatch=!1,notes.push(`Could not find exact host fiber for the target element in the ancestor fiber subtree (scanned=${subtreeScanned}). Falling back to ancestor fiber stack; some frames may be unrelated.`))}let hostMapping={fiberOnTargetElement:fiberHit.onTarget,anchorDomHint:anchorHint,targetDomHint:targetHint,hostFiberMatchedTarget:hostMatch,subtreeScanNodesScanned:subtreeScanned,subtreeScanMaxNodes:maxFiberNodesToScanEval,strategy},nearest=null,cur=hostFiber;for(;cur;){if(isMeaningfulComponentFiber(cur)){nearest=cur;break}cur=cur.return??null}nearest||notes.push("Fiber was found, but no meaningful function/class component was detected in the return chain.");let stack=[],seenFibers=new Set,stackCur=nearest;for(;stackCur&&stack.length<maxStackDepthEval;){if(seenFibers.has(stackCur)){notes.push("Detected a cycle in fiber.return chain; stopping stack traversal.");break}seenFibers.add(stackCur),isMeaningfulComponentFiber(stackCur)&&stack.push(frameFromFiber(stackCur)),stackCur=stackCur.return??null}let collapsedStack=stack.length>0?collapseConsecutiveDuplicates(stack):[],componentStackText=stackTextFromFrames(collapsedStack),wrappersDetected=detectWrappers(collapsedStack),wrapperFrames=findWrapperFrames(collapsedStack,wrappersDetected);wrappersDetected.length>=3&¬es.push(`Wrapper-heavy stack detected (${wrappersDetected.join(", ")}). Interpreting nearestComponent may require skipping wrappers.`);let nearestOut=null;if(nearest&&(nearestOut=frameFromFiber(nearest),includePropsPreviewEval))try{let props=nearest.memoizedProps;props!==void 0?nearestOut.propsPreview=safeStringify(props,maxPropsPreviewCharsEval):notes.push("memoizedProps not available on nearest component fiber.")}catch{notes.push("Failed to read memoizedProps for nearest component (best-effort).")}return notes.push("React Fiber inspection uses non-public internals; fields are best-effort."),notes.push("Component names may come from displayName, wrappers, third-party libraries, or minified production builds."),strategy==="ancestor-fallback"&¬es.push("Host mapping fallback was used; consider selecting a deeper/more specific DOM element for a more accurate component stack."),{target:{selector:selectorEval??null,point:{x:typeof xEval=="number"?xEval:null,y:typeof yEval=="number"?yEval:null},found:!0,domHint:targetHint,elementPath},react:{detected:!0,detectionReason:strategy==="direct-on-target"?"React fiber found on the target element.":strategy==="ancestor-subtree-scan"?"React fiber found on an ancestor; exact host fiber located via subtree scan.":"React fiber found on an ancestor; exact host fiber not found, stack may include unrelated frames.",fiberKey:fiberHit.fiberKey,hostMapping,nearestComponent:nearestOut,componentStack:collapsedStack,componentStackText,wrappersDetected,wrapperFrames,notes}}},{selectorEval:selector??null,xEval:typeof x=="number"?x:null,yEval:typeof y=="number"?y:null,maxStackDepthEval:maxStackDepth,includePropsPreviewEval:includePropsPreview,maxPropsPreviewCharsEval:maxPropsPreviewChars,maxElementPathDepthEval:DEFAULT_MAX_ELEMENT_PATH_DEPTH,maxFiberNodesToScanEval:DEFAULT_MAX_FIBER_SUBTREE_NODES_TO_SCAN})}};import{z as z62}from"zod";var DEFAULT_MATCH_STRATEGY="contains",DEFAULT_MAX_ELEMENTS=200,DEFAULT_ONLY_VISIBLE2=!0,DEFAULT_ONLY_IN_VIEWPORT2=!0,DEFAULT_TEXT_PREVIEW_MAX_LENGTH2=80,DEFAULT_MAX_MATCHES=5,DEFAULT_STACK_LIMIT=50,INTERNAL_MAX_ROOTS_SCAN=20,INTERNAL_MAX_FIBERS_VISITED=25e4,GetElementForComponent=class{static{__name(this,"GetElementForComponent")}name(){return"react_get-element-for-component"}description(){return`
|
|
646
|
-
Maps a React COMPONENT INSTANCE to the DOM elements it renders (its "DOM footprint") by traversing the React Fiber graph.
|
|
647
|
-
|
|
648
|
-
Selection strategy:
|
|
649
|
-
- Best: provide an anchor (anchorSelector OR anchorX/anchorY) to target the correct instance near that UI.
|
|
650
|
-
- Optionally provide a query (componentName and/or fileNameHint/lineNumber) to search the Fiber graph.
|
|
651
|
-
- If both anchor + query are provided, we rank candidates and pick the best match near the anchor.
|
|
652
|
-
|
|
653
|
-
Important behavior:
|
|
654
|
-
- The React DevTools hook is helpful but NOT strictly required.
|
|
655
|
-
- If hook exists, roots are discovered reliably via getFiberRoots().
|
|
656
|
-
- If hook doesn't exist, we fall back to scanning the DOM for __reactFiber$ pointers (best-effort).
|
|
657
|
-
- Query search returns multiple candidates (up to maxMatches) and ranks them.
|
|
658
|
-
- Debug source information is best-effort and may be missing even in dev builds depending on bundler/build flags.
|
|
659
|
-
|
|
660
|
-
Operational note for MCP users:
|
|
661
|
-
- If you are using a persistent/headful browser and want more reliable root discovery and component search,
|
|
662
|
-
install the "React Developer Tools" Chrome extension in that browser profile (manual step by the user).
|
|
663
|
-
`.trim()}inputSchema(){return{anchorSelector:z62.string().optional().describe("DOM CSS selector used as an anchor to pick a concrete component instance near that element."),anchorX:z62.number().int().nonnegative().optional().describe("Anchor X coordinate (viewport pixels)."),anchorY:z62.number().int().nonnegative().optional().describe("Anchor Y coordinate (viewport pixels)."),componentName:z62.string().optional().describe("React component name/displayName to search in the Fiber graph."),matchStrategy:z62.enum(["exact","contains"]).optional().default(DEFAULT_MATCH_STRATEGY).describe("How to match componentName against Fiber type/displayName."),fileNameHint:z62.string().optional().describe('Best-effort debug source file hint (usually endsWith match), e.g., "UserCard.tsx".'),lineNumber:z62.number().int().positive().optional().describe("Optional debug source line number hint (dev builds only)."),maxElements:z62.number().int().positive().optional().default(DEFAULT_MAX_ELEMENTS).describe("Maximum number of DOM elements to return from the selected component subtree."),onlyVisible:z62.boolean().optional().default(DEFAULT_ONLY_VISIBLE2).describe("If true, only visually visible elements are returned."),onlyInViewport:z62.boolean().optional().default(DEFAULT_ONLY_IN_VIEWPORT2).describe("If true, only elements intersecting the viewport are returned."),textPreviewMaxLength:z62.number().int().positive().optional().default(DEFAULT_TEXT_PREVIEW_MAX_LENGTH2).describe("Max length for per-element text preview (innerText/textContent/aria-label)."),maxMatches:z62.number().int().positive().optional().default(DEFAULT_MAX_MATCHES).describe("Max number of matching component candidates to return/rank.")}}outputSchema(){return{reactDetected:z62.boolean().describe("True if __REACT_DEVTOOLS_GLOBAL_HOOK__ looks available."),fiberDetected:z62.boolean().describe("True if DOM appears to contain React Fiber pointers (__reactFiber$...)."),rootDiscovery:z62.enum(["devtools-hook","dom-fiber-scan","none"]).describe("How roots were discovered."),component:z62.object({name:z62.string().nullable(),displayName:z62.string().nullable(),debugSource:z62.object({fileName:z62.string().nullable(),lineNumber:z62.number().int().nullable(),columnNumber:z62.number().int().nullable()}).nullable(),componentStack:z62.array(z62.string()),selection:z62.enum(["anchor","query","query+anchor","unknown"]),scoring:z62.object({score:z62.number(),nameMatched:z62.boolean(),debugSourceMatched:z62.boolean(),anchorRelated:z62.boolean(),proximityPx:z62.number().nullable().optional()}).optional()}).nullable(),candidates:z62.array(z62.object({name:z62.string().nullable(),displayName:z62.string().nullable(),debugSource:z62.object({fileName:z62.string().nullable(),lineNumber:z62.number().int().nullable(),columnNumber:z62.number().int().nullable()}).nullable(),componentStack:z62.array(z62.string()),selection:z62.enum(["anchor","query","query+anchor","unknown"]),scoring:z62.object({score:z62.number(),nameMatched:z62.boolean(),debugSourceMatched:z62.boolean(),anchorRelated:z62.boolean(),proximityPx:z62.number().nullable().optional()}).optional(),domFootprintCount:z62.number().int()})).describe("Ranked candidate matches (best-first)."),elements:z62.array(z62.object({tagName:z62.string(),id:z62.string().nullable(),className:z62.string().nullable(),selectorHint:z62.string().nullable(),textPreview:z62.string().nullable(),boundingBox:z62.object({x:z62.number(),y:z62.number(),width:z62.number(),height:z62.number()}).nullable(),isVisible:z62.boolean(),isInViewport:z62.boolean()})),notes:z62.array(z62.string())}}async handle(context,args){let anchorSelector=args.anchorSelector,anchorX=args.anchorX,anchorY=args.anchorY,componentName=args.componentName,matchStrategy=args.matchStrategy??DEFAULT_MATCH_STRATEGY,fileNameHint=args.fileNameHint,lineNumber=args.lineNumber,maxElements=args.maxElements??DEFAULT_MAX_ELEMENTS,onlyVisible=args.onlyVisible??DEFAULT_ONLY_VISIBLE2,onlyInViewport=args.onlyInViewport??DEFAULT_ONLY_IN_VIEWPORT2,textPreviewMaxLength=args.textPreviewMaxLength??DEFAULT_TEXT_PREVIEW_MAX_LENGTH2,maxMatches=args.maxMatches??DEFAULT_MAX_MATCHES,hasAnchorSelector=typeof anchorSelector=="string"&&anchorSelector.trim().length>0,hasAnchorPoint=typeof anchorX=="number"&&typeof anchorY=="number",hasQuery=typeof componentName=="string"&&componentName.trim().length>0||typeof fileNameHint=="string"&&fileNameHint.trim().length>0||typeof lineNumber=="number";if(!hasAnchorSelector&&!hasAnchorPoint&&!hasQuery)throw new Error("Provide at least one targeting method: anchorSelector, (anchorX+anchorY), or componentName/debugSource hints.");return await context.page.evaluate(params=>{let anchorSelectorEval=params.anchorSelectorEval,anchorXEval=params.anchorXEval,anchorYEval=params.anchorYEval,componentNameEval=params.componentNameEval,matchStrategyEval=params.matchStrategyEval,fileNameHintEval=params.fileNameHintEval,lineNumberEval=params.lineNumberEval,maxElementsEval=params.maxElementsEval,onlyVisibleEval=params.onlyVisibleEval,onlyInViewportEval=params.onlyInViewportEval,textPreviewMaxLengthEval=params.textPreviewMaxLengthEval,maxMatchesEval=params.maxMatchesEval,maxRootsScan=params.maxRootsScan,maxFibersVisited=params.maxFibersVisited,stackLimit=params.stackLimit,notes=[];function isElement(v){return typeof Element<"u"&&v instanceof Element}__name(isElement,"isElement");function normalizeStr(v){if(typeof v!="string")return null;let t=v.trim();return t||null}__name(normalizeStr,"normalizeStr");function getFiberFromDomElement(el){let anyEl=el,keys=Object.keys(anyEl);for(let k of keys)if(k.startsWith("__reactFiber$")){let f=anyEl[k];if(f)return f}for(let k of keys)if(k.startsWith("__reactInternalInstance$")){let f=anyEl[k];if(f)return f}return null}__name(getFiberFromDomElement,"getFiberFromDomElement");function getDevtoolsHook(){let hook2=globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__;return!hook2||typeof hook2.getFiberRoots!="function"?null:hook2}__name(getDevtoolsHook,"getDevtoolsHook");function getAllRootsFromHook(hook2){let roots2=[],renderers=hook2.renderers;return!renderers||typeof renderers.forEach!="function"?roots2:(renderers.forEach((_renderer,rendererId)=>{try{let set=hook2.getFiberRoots(rendererId);set&&typeof set.forEach=="function"&&set.forEach(root=>{root&&roots2.push(root)})}catch{}}),roots2.slice(0,maxRootsScan))}__name(getAllRootsFromHook,"getAllRootsFromHook");function getSeedFibersFromDomScan(maxSeeds){let out=[],els=Array.from(document.querySelectorAll("*")),step=els.length>5e3?Math.ceil(els.length/5e3):1;for(let i=0;i<els.length;i+=step){let el=els[i],f=getFiberFromDomElement(el);if(f&&(out.push(f),out.length>=maxSeeds))break}return out}__name(getSeedFibersFromDomScan,"getSeedFibersFromDomScan");function getFunctionDisplayName(fn){if(typeof fn!="function")return null;let anyFn=fn,dn=normalizeStr(anyFn.displayName);if(dn)return dn;let nm=normalizeStr(anyFn.name);return nm||null}__name(getFunctionDisplayName,"getFunctionDisplayName");function getFiberTypeName(fiber){if(!fiber)return null;let t=fiber.type??fiber.elementType??null;if(!t)return null;if(typeof t=="function")return getFunctionDisplayName(t);if(typeof t=="string")return t;let dn=normalizeStr(t.displayName);return dn||normalizeStr(t.name)}__name(getFiberTypeName,"getFiberTypeName");function getDisplayName(fiber){if(!fiber)return null;let t=fiber.type??fiber.elementType??null;if(!t)return null;let dn=normalizeStr(t.displayName);return dn||getFiberTypeName(fiber)}__name(getDisplayName,"getDisplayName");function getDebugSource(fiber){let seen=new Set,queue=[],push=__name(x=>{x&&(seen.has(x)||(seen.add(x),queue.push(x)))},"push");push(fiber),push(fiber?.alternate);for(let i=0;i<8;i++){let f=queue[i];if(!f)break;push(f?._debugOwner),push(f?._debugOwner?.alternate)}for(let f of queue){let src=f?._debugSource??f?._debugOwner?._debugSource??f?.type?._debugSource??f?.elementType?._debugSource??null;if(!src)continue;let fileName=normalizeStr(src.fileName)??null,lineNumber2=typeof src.lineNumber=="number"?src.lineNumber:null,columnNumber=typeof src.columnNumber=="number"?src.columnNumber:null;if(fileName||lineNumber2!==null||columnNumber!==null)return{fileName,lineNumber:lineNumber2,columnNumber}}return null}__name(getDebugSource,"getDebugSource");function isHostFiber(fiber){let sn=fiber?.stateNode;return isElement(sn)}__name(isHostFiber,"isHostFiber");function buildComponentStack(fiber,limit){let out=[],cur=fiber??null;for(let i=0;i<limit&&cur;i++){let name=getDisplayName(cur),host=isHostFiber(cur);name&&!host&&out.push(name),cur=cur.return??null}if(out.length===0){cur=fiber??null;for(let i=0;i<limit&&cur;i++){let name=getDisplayName(cur);name&&out.push(name),cur=cur.return??null}}let deduped=[];for(let n of out)(deduped.length===0||deduped[deduped.length-1]!==n)&&deduped.push(n);return deduped}__name(buildComponentStack,"buildComponentStack");function firstMeaningfulComponentAbove(fiber){let cur=fiber??null,visited=new Set;for(;cur;){let key=cur.alternate??cur;if(visited.has(key))break;if(visited.add(key),!isHostFiber(cur))return cur;cur=cur.return??null}return null}__name(firstMeaningfulComponentAbove,"firstMeaningfulComponentAbove");function matchesName(candidate,query2,strategy){if(!candidate)return!1;let a=candidate.trim(),b=query2.trim();return!a||!b?!1:strategy==="exact"?a===b:a.toLowerCase().includes(b.toLowerCase())}__name(matchesName,"matchesName");function matchesDebugSource(fiber,fileNameHint2,lineNumber2){let src=getDebugSource(fiber);if(!src)return!1;if(fileNameHint2){let hint=fileNameHint2.trim();if(hint){let fn=(src.fileName??"").trim();if(!fn)return!1;let fnLower=fn.toLowerCase(),hintLower=hint.toLowerCase();if(!(fnLower.endsWith(hintLower)||fnLower.includes(hintLower)))return!1}}return!(typeof lineNumber2=="number"&&(src.lineNumber===null||Math.abs(src.lineNumber-lineNumber2)>3))}__name(matchesDebugSource,"matchesDebugSource");function toStartFiber(rootOrFiber){if(!rootOrFiber)return null;let maybeCurrent=rootOrFiber.current;return maybeCurrent?maybeCurrent.child??maybeCurrent:rootOrFiber}__name(toStartFiber,"toStartFiber");function pickAnchorElement(anchorSelector2,x,y){if(anchorSelector2&&anchorSelector2.trim()){let el=document.querySelector(anchorSelector2);return el||(notes.push(`anchorSelector did not match any element: ${anchorSelector2}`),null)}if(typeof x=="number"&&typeof y=="number"){let el=document.elementFromPoint(x,y);return el||(notes.push(`anchorPoint did not hit any element: (${x}, ${y})`),null)}return null}__name(pickAnchorElement,"pickAnchorElement");function selectorHintFor(el){let dt=normalizeStr(el.getAttribute("data-testid"))??normalizeStr(el.getAttribute("data-test-id"))??normalizeStr(el.getAttribute("data-test"))??null;if(dt)return`[data-testid='${dt.replace(/'/g,"\\'")}']`;let ds=normalizeStr(el.getAttribute("data-selector"))??null;if(ds)return`[data-selector='${ds.replace(/'/g,"\\'")}']`;if(el.id)try{return`#${CSS.escape(el.id)}`}catch{return`#${el.id}`}return el.tagName.toLowerCase()}__name(selectorHintFor,"selectorHintFor");function textPreviewFor(el,maxLen){let aria=normalizeStr(el.getAttribute("aria-label"))??null;if(aria)return aria.slice(0,maxLen);let txt=String(el.innerText??el.textContent??"").trim();return txt?txt.slice(0,maxLen):null}__name(textPreviewFor,"textPreviewFor");function computeRuntime(el){let r=el.getBoundingClientRect(),s=getComputedStyle(el),isVisible=s.display!=="none"&&s.visibility!=="hidden"&&parseFloat(s.opacity||"1")>0&&r.width>0&&r.height>0,vw=window.innerWidth,vh=window.innerHeight,isInViewport=r.right>0&&r.bottom>0&&r.left<vw&&r.top<vh,boundingBox=Number.isFinite(r.x)&&Number.isFinite(r.y)&&Number.isFinite(r.width)&&Number.isFinite(r.height)?{x:r.x,y:r.y,width:r.width,height:r.height}:null,centerX=r.left+r.width/2,centerY=r.top+r.height/2;return{boundingBox,isVisible,isInViewport,centerX,centerY}}__name(computeRuntime,"computeRuntime");function collectDomElementsFromFiberSubtree(fiber,maxElements2,onlyVisible2,onlyInViewport2,textPreviewMaxLength2){let out=[],seen=new Set,stack=[];fiber&&stack.push(fiber);let visited=new Set;for(;stack.length>0&&!(out.length>=maxElements2);){let f=stack.pop();if(!f)continue;let key=f.alternate??f;if(visited.has(key))continue;if(visited.add(key),isHostFiber(f)){let el=f.stateNode;if(!seen.has(el)){seen.add(el);let rt=computeRuntime(el);if(!(onlyVisible2&&!rt.isVisible)){if(!(onlyInViewport2&&!rt.isInViewport)){let tagName=el.tagName.toLowerCase(),id=el.id?String(el.id):null,classNameRaw=el.className,className=typeof classNameRaw=="string"&&classNameRaw.trim()?classNameRaw.trim():null;out.push({tagName,id,className,selectorHint:selectorHintFor(el),textPreview:textPreviewFor(el,textPreviewMaxLength2),boundingBox:rt.boundingBox,isVisible:rt.isVisible,isInViewport:rt.isInViewport})}}}}let child=f.child??null,sibling=f.sibling??null;child&&stack.push(child),sibling&&stack.push(sibling)}return out}__name(collectDomElementsFromFiberSubtree,"collectDomElementsFromFiberSubtree");function findFibersByQuery(roots2,query2,maxMatches2){let nameQ=query2.componentName?query2.componentName.trim():void 0,hasNameQ=!!nameQ,fileQ=query2.fileNameHint?query2.fileNameHint.trim():void 0,hasFileQ=!!fileQ,hasLineQ=typeof query2.lineNumber=="number";if(!(hasNameQ||hasFileQ||hasLineQ))return[];let stack=[];for(let r of roots2){let start=toStartFiber(r);start&&stack.push(start)}let visited=new Set,matches=[],visitedCount=0;for(;stack.length>0&&!(matches.length>=maxMatches2);){let f=stack.pop();if(!f)continue;let key=f.alternate??f;if(visited.has(key))continue;if(visited.add(key),visitedCount++,visitedCount>maxFibersVisited){notes.push(`Fiber traversal safety cap reached (${maxFibersVisited}). Results may be incomplete.`);break}let dn=getDisplayName(f),tn=getFiberTypeName(f),nameMatches=hasNameQ?matchesName(dn,nameQ,query2.matchStrategy)||matchesName(tn,nameQ,query2.matchStrategy):!0,srcMatches=hasFileQ||hasLineQ?matchesDebugSource(f,fileQ,query2.lineNumber):!0;nameMatches&&srcMatches&&matches.push(f);let child=f.child??null,sibling=f.sibling??null;child&&stack.push(child),sibling&&stack.push(sibling)}return matches}__name(findFibersByQuery,"findFibersByQuery");function scoreCandidate(fiber,anchorEl2,anchorX2,anchorY2,q,maxElements2,onlyVisible2,onlyInViewport2,textPreviewMaxLength2){let nameQ=q.componentName?q.componentName.trim():void 0,hasNameQ=!!nameQ,dn=getDisplayName(fiber),tn=getFiberTypeName(fiber),nameMatched=hasNameQ?matchesName(dn,nameQ,q.matchStrategy)||matchesName(tn,nameQ,q.matchStrategy):!1,debugSourceMatched=normalizeStr(q.fileNameHint)||typeof q.lineNumber=="number"?matchesDebugSource(fiber,normalizeStr(q.fileNameHint)??void 0,typeof q.lineNumber=="number"?q.lineNumber:void 0):!1,dom=collectDomElementsFromFiberSubtree(fiber,maxElements2,onlyVisible2,onlyInViewport2,textPreviewMaxLength2),anchorRelated=!1,proximityPx=null;if(anchorEl2){let anchorSel=selectorHintFor(anchorEl2);if(anchorRelated=dom.some(d=>!d.selectorHint||!anchorSel?!1:d.selectorHint===anchorSel)||dom.some(d=>{if(!d.boundingBox)return!1;let r=anchorEl2.getBoundingClientRect(),bb=d.boundingBox;return r.left<bb.x+bb.width&&r.left+r.width>bb.x&&r.top<bb.y+bb.height&&r.top+r.height>bb.y}),typeof anchorX2=="number"&&typeof anchorY2=="number"&&dom.length>0){let best2=null;for(let item of dom){if(!item.boundingBox)continue;let cx=item.boundingBox.x+item.boundingBox.width/2,cy=item.boundingBox.y+item.boundingBox.height/2,dx=cx-anchorX2,dy=cy-anchorY2,dist=Math.sqrt(dx*dx+dy*dy);(best2===null||dist<best2)&&(best2=dist)}proximityPx=best2}}let score=0;if(score+=nameMatched?3:0,score+=debugSourceMatched?3:0,score+=anchorRelated?2:0,score+=Math.min(1.5,dom.length/25),typeof proximityPx=="number"&&Number.isFinite(proximityPx)){let p=Math.max(0,Math.min(1,1-proximityPx/1e3));score+=1.5*p}return{score,nameMatched,debugSourceMatched,anchorRelated,proximityPx,dom}}__name(scoreCandidate,"scoreCandidate");let hook=getDevtoolsHook(),reactDetected=!!hook;reactDetected?notes.push("React DevTools hook detected. Root discovery will use getFiberRoots() (more reliable)."):(notes.push("React DevTools hook was not detected (__REACT_DEVTOOLS_GLOBAL_HOOK__)."),notes.push('If you are using a persistent/headful browser profile, install the "React Developer Tools" Chrome extension in that profile (manual step by the user) to enable reliable root discovery and component search.'));let fiberDetected=(()=>{let body=document.body;return body?!!(getFiberFromDomElement(body)||getSeedFibersFromDomScan(1).length>0):!1})();fiberDetected?notes.push("React Fiber pointers detected on DOM nodes. Anchor-based mapping may still work without the DevTools hook (best-effort)."):notes.push("No React Fiber pointers were detected on DOM nodes (__reactFiber$...). This can happen if the page is not React, React has not rendered yet, or internals are unavailable.");let anchorEl=pickAnchorElement(anchorSelectorEval,anchorXEval,anchorYEval),anchorSelected=null;if(anchorEl){let anchorFiber=getFiberFromDomElement(anchorEl);if(anchorFiber){let candidateA=anchorFiber,candidateB=anchorFiber.alternate??null,chosen=candidateA;candidateB&&(candidateB.child||candidateB.sibling)&&!(candidateA.child||candidateA.sibling)&&(chosen=candidateB);let nearestComponent=firstMeaningfulComponentAbove(chosen);nearestComponent?anchorSelected=nearestComponent:notes.push("Anchor fiber found but no meaningful component fiber was found above it.")}else notes.push("Anchor element found but React fiber was not found on it.")}let roots=[],rootDiscovery="none";if(hook){let r=getAllRootsFromHook(hook);r.length>0&&(roots=r,rootDiscovery="devtools-hook")}if(roots.length===0&&fiberDetected){let seeds=getSeedFibersFromDomScan(10);seeds.length>0&&(roots=seeds,rootDiscovery="dom-fiber-scan",notes.push("Using DOM fiber scan as fallback root discovery (best-effort)."))}let hasQuery2=!!normalizeStr(componentNameEval)||!!normalizeStr(fileNameHintEval)||typeof lineNumberEval=="number",query={componentName:normalizeStr(componentNameEval)??void 0,matchStrategy:matchStrategyEval,fileNameHint:normalizeStr(fileNameHintEval)??void 0,lineNumber:typeof lineNumberEval=="number"?lineNumberEval:void 0},queryMatches=[];hasQuery2&&(roots.length>0?queryMatches=findFibersByQuery(roots,query,Math.max(1,Math.floor(maxMatchesEval))):notes.push("Query was provided but no roots could be discovered. Provide an anchorSelector/anchorX+anchorY so we can map via DOM fiber pointers."));let candidates=[];anchorSelected&&candidates.push(anchorSelected);for(let f of queryMatches)candidates.push(f);let uniq=[],seenCand=new Set;for(let f of candidates){let key=f?.alternate??f;f&&!seenCand.has(key)&&(seenCand.add(key),uniq.push(f))}if(uniq.length===0)return reactDetected||notes.push("No candidates found. Without the DevTools hook, component search may be unreliable unless you provide a strong anchor."),{reactDetected,fiberDetected,rootDiscovery,component:null,candidates:[],elements:[],notes:[...notes,"Failed to select a target component fiber. Provide a better anchor, or ensure React is present and render has happened."]};let scored=[];for(let f of uniq){let s=scoreCandidate(f,anchorEl,anchorXEval,anchorYEval,query,maxElementsEval,onlyVisibleEval,onlyInViewportEval,textPreviewMaxLengthEval),selection="unknown",isAnchor=anchorSelected?(anchorSelected.alternate??anchorSelected)===(f.alternate??f):!1,isQuery=queryMatches.some(qf=>(qf.alternate??qf)===(f.alternate??f));isAnchor&&isQuery?selection="query+anchor":isAnchor?selection="anchor":isQuery?selection="query":selection="unknown";let name=getFiberTypeName(f),displayName=getDisplayName(f),debugSource=getDebugSource(f),componentStack=buildComponentStack(f,stackLimit),meta={name,displayName,debugSource,componentStack,selection,scoring:{score:s.score,nameMatched:s.nameMatched,debugSourceMatched:s.debugSourceMatched,anchorRelated:s.anchorRelated,proximityPx:s.proximityPx}};scored.push({fiber:f,meta,dom:s.dom,domFootprintCount:s.dom.length})}scored.sort((a,b)=>(b.meta.scoring?.score??0)-(a.meta.scoring?.score??0));let best=scored[0],outCandidates=scored.slice(0,Math.max(1,Math.floor(maxMatchesEval))).map(c=>({...c.meta,domFootprintCount:c.domFootprintCount})),elements=best.dom;return hasQuery2&&(query.fileNameHint||typeof query.lineNumber=="number")&&(outCandidates.some(c=>!!(c.debugSource?.fileName||c.debugSource?.lineNumber!==null))||(notes.push("debugSource hints were provided, but no _debugSource information was found on matched fibers. This is common in production builds and some dev toolchains."),notes.push('React DevTools may still display "Rendered by <file>:<line>" using sourcemaps/stack traces even when fiber._debugSource is null.'))),elements.length>=maxElementsEval&¬es.push(`Element list was truncated at maxElements=${maxElementsEval}. Increase maxElements if needed.`),elements.length===0&¬es.push("No DOM elements were returned for the selected component. It may render no host elements, or filtering (onlyVisible/onlyInViewport) removed them."),!reactDetected&&fiberDetected?notes.push("React DevTools hook was not detected, but DOM fiber pointers were found. Using DOM-fiber scanning and anchor-based mapping (best-effort)."):!reactDetected&&!fiberDetected&¬es.push("React DevTools hook was not detected and no DOM fiber pointers were found. Component-to-DOM mapping is unavailable on this page."),{reactDetected,fiberDetected,rootDiscovery,component:best.meta,candidates:outCandidates,elements,notes:[...notes,"Component metadata is best-effort. Wrappers (memo/forwardRef/HOCs), Suspense/Offscreen, and portals may make names/stacks noisy."]}},{anchorSelectorEval:typeof anchorSelector=="string"&&anchorSelector.trim()?anchorSelector.trim():void 0,anchorXEval:typeof anchorX=="number"&&Number.isFinite(anchorX)?Math.floor(anchorX):void 0,anchorYEval:typeof anchorY=="number"&&Number.isFinite(anchorY)?Math.floor(anchorY):void 0,componentNameEval:typeof componentName=="string"&&componentName.trim()?componentName.trim():void 0,matchStrategyEval:matchStrategy,fileNameHintEval:typeof fileNameHint=="string"&&fileNameHint.trim()?fileNameHint.trim():void 0,lineNumberEval:typeof lineNumber=="number"&&Number.isFinite(lineNumber)?Math.floor(lineNumber):void 0,maxElementsEval:Math.max(1,Math.floor(maxElements)),onlyVisibleEval:!!onlyVisible,onlyInViewportEval:!!onlyInViewport,textPreviewMaxLengthEval:Math.max(1,Math.floor(textPreviewMaxLength)),maxMatchesEval:Math.max(1,Math.floor(maxMatches)),maxRootsScan:INTERNAL_MAX_ROOTS_SCAN,maxFibersVisited:INTERNAL_MAX_FIBERS_VISITED,stackLimit:DEFAULT_STACK_LIMIT})}};var tools8=[new GetComponentForElement,new GetElementForComponent];import{z as z63}from"zod";var JsInBrowser=class{static{__name(this,"JsInBrowser")}name(){return"run_js-in-browser"}description(){return`
|
|
664
|
-
Runs custom JavaScript INSIDE the active browser page using Playwright's "page.evaluate()".
|
|
665
|
-
|
|
666
|
-
This code executes in the PAGE CONTEXT (real browser environment):
|
|
667
|
-
- Has access to window, document, DOM, Web APIs
|
|
668
|
-
- Can read/modify the page state
|
|
669
|
-
- Runs with the same permissions as the loaded web page
|
|
670
|
-
|
|
671
|
-
Typical use cases:
|
|
672
|
-
- Inspect or mutate DOM state
|
|
673
|
-
- Read client-side variables or framework internals
|
|
674
|
-
- Trigger browser-side logic
|
|
675
|
-
- Extract computed values directly from the page
|
|
676
|
-
|
|
677
|
-
Notes:
|
|
678
|
-
- The code runs in an isolated execution context, but within the page
|
|
679
|
-
- No direct access to Node.js APIs
|
|
680
|
-
- Return value must be serializable
|
|
681
|
-
- The script is executed as a function body, so "return" and top-level "await" are valid; their value is returned to the caller.
|
|
682
|
-
- When using fetch(): check response.ok and/or Content-Type before calling .json(); error pages often return HTML and will cause "is not valid JSON" if parsed.
|
|
683
|
-
`}inputSchema(){return{script:z63.string().describe('JavaScript code to execute. May use "return" to pass a serializable value back; the script runs as a function body.')}}outputSchema(){return{result:z63.any().describe(`
|
|
684
|
-
The result of the evaluation. This value can be of any type, including primitives, arrays, or objects.
|
|
685
|
-
It represents the direct return value of the JavaScript expression executed in the page context.
|
|
686
|
-
The structure and type of this value are not constrained and depend entirely on the evaluated code.`)}}async handle(context,args){let wrapped=`(async function() { ${args.script} })()`;return{result:await context.page.evaluate(wrapped)}}};import crypto3 from"node:crypto";import vm from"node:vm";import{z as z64}from"zod";var DEFAULT_TIMEOUT_MS5=5e3,MAX_TIMEOUT_MS=3e4;function _toJsonSafe(value){if(value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean")return value;try{return JSON.parse(JSON.stringify(value))}catch{return String(value)}}__name(_toJsonSafe,"_toJsonSafe");var JsInSandbox=class{static{__name(this,"JsInSandbox")}name(){return"run_js-in-sandbox"}description(){return`
|
|
687
|
-
Runs custom JavaScript inside a Node.js VM sandbox.
|
|
688
|
-
|
|
689
|
-
This runs on the MCP SERVER (not in the browser).
|
|
690
|
-
|
|
691
|
-
Available bindings:
|
|
692
|
-
- page: Playwright Page (main interaction surface)
|
|
693
|
-
- console: captured logs (log/warn/error)
|
|
694
|
-
- sleep(ms): async helper
|
|
695
|
-
|
|
696
|
-
Safe built-ins:
|
|
697
|
-
- Math, JSON, Number, String, Boolean, Array, Object, Date, RegExp
|
|
698
|
-
- isFinite, isNaN, parseInt, parseFloat
|
|
699
|
-
- URL, URLSearchParams
|
|
700
|
-
- TextEncoder, TextDecoder
|
|
701
|
-
- structuredClone
|
|
702
|
-
- crypto.randomUUID()
|
|
703
|
-
- AbortController
|
|
704
|
-
- setTimeout / clearTimeout
|
|
705
|
-
|
|
706
|
-
NOT available:
|
|
707
|
-
- require, process, fs, Buffer
|
|
708
|
-
- globalThis
|
|
709
|
-
|
|
710
|
-
This is NOT a security boundary. Intended for trusted automation logic.
|
|
711
|
-
`.trim()}inputSchema(){return{code:z64.string().describe("JavaScript code (async allowed)."),timeoutMs:z64.number().int().min(0).max(MAX_TIMEOUT_MS).optional().default(DEFAULT_TIMEOUT_MS5).describe("Max VM CPU time for synchronous execution in milliseconds.")}}outputSchema(){return{result:z64.any().describe(`
|
|
712
|
-
Return value of the sandboxed code (best-effort JSON-safe).
|
|
713
|
-
If user returns undefined but logs exist, returns { logs }.
|
|
714
|
-
If error occurs, returns { error, logs }.`)}}async handle(context,args){let logs=[],sandboxConsole={log:__name((...items)=>{logs.push({level:"log",message:items.map(x=>String(x)).join(" ")})},"log"),warn:__name((...items)=>{logs.push({level:"warn",message:items.map(x=>String(x)).join(" ")})},"warn"),error:__name((...items)=>{logs.push({level:"error",message:items.map(x=>String(x)).join(" ")})},"error")},sleep=__name(async ms=>{let d=Math.max(0,Math.floor(ms));await new Promise(resolve=>{setTimeout(()=>resolve(),d)})},"sleep"),sandbox={page:context.page,console:sandboxConsole,sleep,Math,JSON,Number,String,Boolean,Array,Object,Date,RegExp,isFinite,isNaN,parseInt,parseFloat,URL,URLSearchParams,TextEncoder,TextDecoder,structuredClone,crypto:{randomUUID:crypto3.randomUUID},AbortController,setTimeout,clearTimeout},vmContext=vm.createContext(sandbox),wrappedSource=`
|
|
715
|
-
'use strict';
|
|
716
|
-
(async () => {
|
|
717
|
-
${String(args.code??"")}
|
|
718
|
-
})()
|
|
719
|
-
`.trim();try{let value=new vm.Script(wrappedSource,{filename:"mcp-sandbox.js"}).runInContext(vmContext,{timeout:args.timeoutMs??DEFAULT_TIMEOUT_MS5}),awaited=await Promise.resolve(value);return awaited===void 0&&logs.length>0?{result:{logs}}:{result:_toJsonSafe(awaited)}}catch(e){return{result:{error:e instanceof Error?e.stack??e.message:String(e),logs}}}}};var tools9=[new JsInBrowser,new JsInSandbox];import picomatch from"picomatch";var STORE_BY_CONTEXT2=new WeakMap;function _ensureStore2(ctx){let existing=STORE_BY_CONTEXT2.get(ctx);if(existing)return existing;let created={stubs:[],installed:!1};return STORE_BY_CONTEXT2.set(ctx,created),created}__name(_ensureStore2,"_ensureStore");function _nowId(){let t=Date.now(),r=Math.floor(Math.random()*1e6);return`${t.toString(36)}-${r.toString(36)}`}__name(_nowId,"_nowId");async function _sleep(ms){ms<=0||await new Promise(resolve=>{setTimeout(()=>resolve(),ms)})}__name(_sleep,"_sleep");function _normalizeTimes(times){return typeof times!="number"||!Number.isFinite(times)||times<=0?-1:Math.floor(times)}__name(_normalizeTimes,"_normalizeTimes");function _isTimesRemaining(times,usedCount){return times===-1?!0:usedCount<times}__name(_isTimesRemaining,"_isTimesRemaining");function _normalizeChance(chance){if(typeof chance=="number"&&Number.isFinite(chance))return Math.max(0,Math.min(1,chance))}__name(_normalizeChance,"_normalizeChance");function _shouldApplyChance(chance){return chance===void 0?!0:chance<=0?!1:chance>=1?!0:Math.random()<chance}__name(_shouldApplyChance,"_shouldApplyChance");function _compileMatcher(pattern){let p=pattern.trim();return p?picomatch(p,{dot:!0,nocase:!1}):()=>!1}__name(_compileMatcher,"_compileMatcher");function _pickStub(stubs,url){for(let s of stubs)if(s.enabled&&_isTimesRemaining(s.times,s.usedCount)&&s.matcher(url)&&!(s.kind==="mock_http_response"&&!_shouldApplyChance(s.chance)))return s}__name(_pickStub,"_pickStub");async function _applyStub(route,stub){let req=route.request();if(stub.usedCount++,stub.delayMs>0&&await _sleep(stub.delayMs),stub.kind==="mock_http_response"){if(stub.action==="abort"){let code=stub.abortErrorCode??"failed";await route.abort(code);return}let status=typeof stub.status=="number"?stub.status:200,headers=stub.headers??{},body=typeof stub.body=="string"?stub.body:"";await route.fulfill({status,headers,body});return}else if(stub.kind==="intercept_http_request"){let overrides={headers:{...req.headers(),...stub.modifications.headers??{}}};typeof stub.modifications.method=="string"&&stub.modifications.method.trim()&&(overrides.method=stub.modifications.method.trim().toUpperCase()),typeof stub.modifications.body=="string"&&(overrides.postData=stub.modifications.body),await route.continue(overrides);return}await route.continue()}__name(_applyStub,"_applyStub");async function ensureRoutingInstalled(ctx){let store=_ensureStore2(ctx);store.installed||(await ctx.route("**/*",async route=>{let url=route.request().url(),innerStore=_ensureStore2(ctx),stub=_pickStub(innerStore.stubs,url);if(!stub){await route.continue();return}try{await _applyStub(route,stub)}finally{_isTimesRemaining(stub.times,stub.usedCount)||(innerStore.stubs=innerStore.stubs.filter(x=>x.id!==stub.id))}}),store.installed=!0)}__name(ensureRoutingInstalled,"ensureRoutingInstalled");function addMockHttpResponseStub(ctx,input){let store=_ensureStore2(ctx),stub={...input,kind:"mock_http_response",id:_nowId(),usedCount:0,matcher:_compileMatcher(input.pattern),times:_normalizeTimes(input.times),delayMs:Math.max(0,Math.floor(input.delayMs)),chance:_normalizeChance(input.chance)};return store.stubs.push(stub),stub}__name(addMockHttpResponseStub,"addMockHttpResponseStub");function addHttpInterceptRequestStub(ctx,input){let store=_ensureStore2(ctx),stub={...input,kind:"intercept_http_request",id:_nowId(),usedCount:0,matcher:_compileMatcher(input.pattern),times:_normalizeTimes(input.times),delayMs:Math.max(0,Math.floor(input.delayMs))};return store.stubs.push(stub),stub}__name(addHttpInterceptRequestStub,"addHttpInterceptRequestStub");function clearStub(ctx,id){let store=_ensureStore2(ctx);if(!id){let n=store.stubs.length;return store.stubs=[],n}let before=store.stubs.length;return store.stubs=store.stubs.filter(s=>s.id!==id),before-store.stubs.length}__name(clearStub,"clearStub");function listStubs(ctx){return[..._ensureStore2(ctx).stubs]}__name(listStubs,"listStubs");function normalizeDelayMs(delayMs){return typeof delayMs!="number"||!Number.isFinite(delayMs)||delayMs<=0?0:Math.floor(delayMs)}__name(normalizeDelayMs,"normalizeDelayMs");function normalizeTimesPublic(times){return _normalizeTimes(times)}__name(normalizeTimesPublic,"normalizeTimesPublic");function normalizeHeaders(headers){if(!headers)return;let out={};for(let[k,v]of Object.entries(headers))out[String(k)]=String(v);return out}__name(normalizeHeaders,"normalizeHeaders");function normalizeBody(body){if(typeof body=="string")return body;if(body&&typeof body=="object")return JSON.stringify(body)}__name(normalizeBody,"normalizeBody");function normalizeAbortCode(code){if(typeof code!="string")return;let v=code.trim();if(v)return v}__name(normalizeAbortCode,"normalizeAbortCode");function normalizeMethod(method){if(typeof method!="string")return;let v=method.trim();if(v)return v.toUpperCase()}__name(normalizeMethod,"normalizeMethod");function normalizeChance(chance){return _normalizeChance(chance)}__name(normalizeChance,"normalizeChance");import{z as z65}from"zod";var Clear=class{static{__name(this,"Clear")}name(){return"stub_clear"}description(){return`
|
|
720
|
-
Clears stubs installed.
|
|
721
|
-
|
|
722
|
-
- If stubId is provided, clears only that stub.
|
|
723
|
-
- If stubId is omitted, clears all stubs for the current session/context.
|
|
724
|
-
`.trim()}inputSchema(){return{stubId:z65.string().optional().describe("Stub id to remove. Omit to remove all stubs.")}}outputSchema(){return{clearedCount:z65.number().int().nonnegative().describe("Number of stubs removed.")}}async handle(context,args){return{clearedCount:clearStub(context.browserContext,args.stubId)}}};import{z as z66}from"zod";var InterceptHttpRequest=class{static{__name(this,"InterceptHttpRequest")}name(){return"stub_intercept-http-request"}description(){return`
|
|
725
|
-
Installs a request interceptor stub that can modify outgoing requests before they are sent.
|
|
726
|
-
|
|
727
|
-
Use cases:
|
|
728
|
-
- A/B testing / feature flags (inject headers)
|
|
729
|
-
- Security testing (inject malformed headers / payload)
|
|
730
|
-
- Edge cases (special characters, large payload)
|
|
731
|
-
- Auth simulation (add API keys / tokens in headers)
|
|
732
|
-
|
|
733
|
-
Notes:
|
|
734
|
-
- pattern is a glob matched against the full request URL (picomatch).
|
|
735
|
-
- This modifies requests; it does not change responses.
|
|
736
|
-
- times limits how many times the interceptor applies (-1 means infinite).
|
|
737
|
-
`.trim()}inputSchema(){return{pattern:z66.string().describe("Glob pattern matched against the full request URL (picomatch)."),modifications:z66.object({headers:z66.record(z66.string(),z66.string()).optional().describe("Headers to merge into the outgoing request headers."),body:z66.union([z66.string(),z66.record(z66.string(),z66.any()),z66.array(z66.any())]).optional().describe("Override request body. If object/array, it will be JSON-stringified."),method:z66.string().optional().describe("Override HTTP method (e.g., POST, PUT).")}).optional().describe("Request modifications to apply."),delayMs:z66.number().int().nonnegative().optional().describe("Artificial delay in milliseconds before continuing the request."),times:z66.number().int().optional().describe("Apply only N times, then let through. Omit for infinite.")}}outputSchema(){return{stubId:z66.string().describe("Unique id of the installed stub."),kind:z66.literal("intercept_http_request").describe("Stub kind."),pattern:z66.string().describe("Glob pattern."),enabled:z66.boolean().describe("Whether the stub is enabled."),delayMs:z66.number().int().describe("Applied artificial delay in milliseconds."),times:z66.number().int().describe("Max applications (-1 means infinite).")}}async handle(context,args){await ensureRoutingInstalled(context.browserContext);let delayMs=normalizeDelayMs(args.delayMs),times=normalizeTimesPublic(args.times),headers=normalizeHeaders(args.modifications?.headers),body=normalizeBody(args.modifications?.body),method=normalizeMethod(args.modifications?.method),stub=addHttpInterceptRequestStub(context.browserContext,{enabled:!0,pattern:args.pattern,modifications:{headers,body,method},delayMs,times});return{stubId:stub.id,kind:"intercept_http_request",pattern:stub.pattern,enabled:stub.enabled,delayMs:stub.delayMs,times:stub.times}}};import{z as z67}from"zod";var List=class{static{__name(this,"List")}name(){return"stub_list"}description(){return`
|
|
738
|
-
Lists currently installed stubs for the active browser context/session.
|
|
739
|
-
Useful to debug why certain calls are being mocked/intercepted.
|
|
740
|
-
`.trim()}inputSchema(){return{}}outputSchema(){return{stubs:z67.array(z67.object({id:z67.string().describe("Stub id."),kind:z67.string().describe("Stub kind."),enabled:z67.boolean().describe("Whether stub is enabled."),pattern:z67.string().describe("Glob pattern (picomatch)."),delayMs:z67.number().int().describe("Artificial delay in ms."),times:z67.number().int().describe("Max applications (-1 means infinite)."),usedCount:z67.number().int().describe("How many times it has been applied."),action:z67.string().optional().describe("For mock_response: fulfill/abort."),status:z67.number().int().optional().describe("For mock_response: HTTP status (if set).")}))}}async handle(context,args){return{stubs:listStubs(context.browserContext).map(s=>{let base={id:s.id,kind:s.kind,enabled:s.enabled,pattern:s.pattern,delayMs:s.delayMs,times:s.times,usedCount:s.usedCount};return s.kind==="mock_http_response"&&(base.action=s.action,typeof s.status=="number"&&(base.status=s.status)),base})}}};import{z as z68}from"zod";var MockHttpResponse=class{static{__name(this,"MockHttpResponse")}name(){return"stub_mock-http-response"}description(){return`
|
|
741
|
-
Installs a response stub for matching requests using glob patterns (picomatch).
|
|
742
|
-
|
|
743
|
-
Use cases:
|
|
744
|
-
- Offline testing (return 200 with local JSON)
|
|
745
|
-
- Error scenarios (force 500/404 or abort with timedout)
|
|
746
|
-
- Edge cases (empty data / huge payload / special characters)
|
|
747
|
-
- Flaky API testing (chance < 1.0)
|
|
748
|
-
- Performance testing (delayMs)
|
|
749
|
-
|
|
750
|
-
Notes:
|
|
751
|
-
- pattern is a glob matched against the full request URL.
|
|
752
|
-
- stubs are evaluated in insertion order; first match wins.
|
|
753
|
-
- times limits how many times the stub applies (-1 means infinite).
|
|
754
|
-
`.trim()}inputSchema(){return{pattern:z68.string().describe("Glob pattern matched against the full request URL (picomatch)."),response:z68.object({action:z68.enum(["fulfill","abort"]).optional().default("fulfill").describe("Fulfill with a mocked response or abort the request."),status:z68.number().int().min(100).max(599).optional().describe("HTTP status code (used when action=fulfill)."),headers:z68.record(z68.string(),z68.string()).optional().describe("HTTP headers for the mocked response."),body:z68.union([z68.string(),z68.record(z68.string(),z68.any()),z68.array(z68.any())]).optional().describe("Response body. If object/array, it will be JSON-stringified."),abortErrorCode:z68.string().optional().describe('Playwright abort error code (used when action=abort), e.g. "timedout".')}).describe("Mock response configuration."),delayMs:z68.number().int().nonnegative().optional().describe("Artificial delay in milliseconds before applying the stub."),times:z68.number().int().optional().describe("Apply only N times, then let through. Omit for infinite."),chance:z68.number().min(0).max(1).optional().describe("Probability (0..1) to apply the stub per request (flaky testing).")}}outputSchema(){return{stubId:z68.string().describe("Unique id of the installed stub (use it to clear later)."),kind:z68.literal("mock_http_response").describe("Stub kind."),pattern:z68.string().describe("Glob pattern."),enabled:z68.boolean().describe("Whether the stub is enabled."),delayMs:z68.number().int().describe("Applied artificial delay in milliseconds."),times:z68.number().int().describe("Max applications (-1 means infinite)."),chance:z68.number().optional().describe("Apply probability (omit means always)."),action:z68.enum(["fulfill","abort"]).describe("Applied action."),status:z68.number().int().optional().describe("HTTP status (present when action=fulfill).")}}async handle(context,args){await ensureRoutingInstalled(context.browserContext);let action=args.response.action??"fulfill",delayMs=normalizeDelayMs(args.delayMs),times=normalizeTimesPublic(args.times),chance=normalizeChance(args.chance),status=args.response.status,headers=normalizeHeaders(args.response.headers),body=normalizeBody(args.response.body),abortErrorCode=normalizeAbortCode(args.response.abortErrorCode),stub=addMockHttpResponseStub(context.browserContext,{enabled:!0,pattern:args.pattern,action,status,headers,body,abortErrorCode,delayMs,times,chance}),out={stubId:stub.id,kind:"mock_http_response",pattern:stub.pattern,enabled:stub.enabled,delayMs:stub.delayMs,times:stub.times,action:stub.action};return typeof stub.chance=="number"&&(out.chance=stub.chance),stub.action==="fulfill"&&(out.status=typeof stub.status=="number"?stub.status:200),out}};var tools10=[new Clear,new InterceptHttpRequest,new List,new MockHttpResponse];import{z as z69}from"zod";var DEFAULT_TIMEOUT_MS6=3e4,DEFAULT_IDLE_TIME_MS=500,DEFAULT_MAX_CONNECTIONS=0,DEFAULT_POLL_INTERVAL_MS=50,WaitForNetworkIdle=class{static{__name(this,"WaitForNetworkIdle")}name(){return"sync_wait-for-network-idle"}description(){return`
|
|
755
|
-
Waits until the page reaches a network-idle condition based on the session's tracked in-flight request count.
|
|
756
|
-
|
|
757
|
-
Definition:
|
|
758
|
-
- "Idle" means the number of in-flight requests is <= maxConnections
|
|
759
|
-
- and it stays that way continuously for at least idleTimeMs.
|
|
760
|
-
|
|
761
|
-
When to use:
|
|
762
|
-
- Before interacting with SPA pages that load data asynchronously
|
|
763
|
-
- Before taking screenshots / AX tree snapshots for more stable results
|
|
764
|
-
- After actions that trigger background fetch/XHR activity
|
|
765
|
-
|
|
766
|
-
Notes:
|
|
767
|
-
- This tool does NOT rely on window globals or page-injected counters.
|
|
768
|
-
- It uses server-side tracking, so it works reliably even with strict CSP.
|
|
769
|
-
- If the page has long-polling or never-ending requests, increase maxConnections or accept a shorter idleTimeMs.
|
|
770
|
-
`.trim()}inputSchema(){return{timeoutMs:z69.number().int().min(0).optional().default(DEFAULT_TIMEOUT_MS6).describe("Maximum time to wait before failing (milliseconds).."),idleTimeMs:z69.number().int().min(0).optional().default(DEFAULT_IDLE_TIME_MS).describe("How long the network must stay idle continuously before resolving (milliseconds)."),maxConnections:z69.number().int().min(0).optional().default(DEFAULT_MAX_CONNECTIONS).describe("Idle threshold. Network is considered idle when in-flight requests <= maxConnections."),pollIntervalMs:z69.number().int().min(10).optional().default(DEFAULT_POLL_INTERVAL_MS).describe("Polling interval used to sample the in-flight request count (milliseconds).")}}outputSchema(){return{waitedMs:z69.number().int().nonnegative().describe("Total time waited until the network became idle or the tool timed out (milliseconds)."),idleTimeMs:z69.number().int().nonnegative().describe("Idle duration required for success (milliseconds)."),timeoutMs:z69.number().int().nonnegative().describe("Maximum allowed wait time (milliseconds)."),maxConnections:z69.number().int().nonnegative().describe("Idle threshold used: in-flight requests must be <= this value."),pollIntervalMs:z69.number().int().nonnegative().describe("Polling interval used to sample the in-flight request count (milliseconds)."),finalInFlightRequests:z69.number().int().nonnegative().describe("The last observed number of in-flight requests at the moment the tool returned."),observedIdleMs:z69.number().int().nonnegative().describe("How long the in-flight request count stayed <= maxConnections right before returning (milliseconds).")}}async handle(context,args){let timeoutMs=args.timeoutMs??DEFAULT_TIMEOUT_MS6,idleTimeMs=args.idleTimeMs??DEFAULT_IDLE_TIME_MS,maxConnections=args.maxConnections??DEFAULT_MAX_CONNECTIONS,pollIntervalMs=args.pollIntervalMs??DEFAULT_POLL_INTERVAL_MS,startMs=Date.now(),deadlineMs=startMs+timeoutMs,lastNotIdleMs=startMs,lastInFlight=0;for(;;){let nowMs=Date.now();lastInFlight=context.numOfInFlightRequests(),lastInFlight>maxConnections&&(lastNotIdleMs=nowMs);let observedIdleMs=nowMs-lastNotIdleMs;if(observedIdleMs>=idleTimeMs)return{waitedMs:nowMs-startMs,idleTimeMs,timeoutMs,maxConnections,pollIntervalMs,finalInFlightRequests:lastInFlight,observedIdleMs};if(nowMs>=deadlineMs){let waitedMs=nowMs-startMs;throw new Error(`Timed out after ${waitedMs}ms waiting for network idle (idleTimeMs=${idleTimeMs}, maxConnections=${maxConnections}, inFlight=${lastInFlight}).`)}await this.sleep(pollIntervalMs)}}async sleep(ms){await new Promise(resolve=>{setTimeout(()=>resolve(),ms)})}};var tools11=[new WaitForNetworkIdle];import fs from"node:fs";import{chromium,firefox,webkit}from"playwright";var DEFAULT_BROWSER_TYPE="chromium",browsers=new Map,persistenceBrowserContexts=new Map;function _browserKey(browserOptions){return JSON.stringify(browserOptions)}__name(_browserKey,"_browserKey");function _browserLaunchOptions(browserOptions){let launchOptions={headless:browserOptions.headless,executablePath:browserOptions.executablePath,handleSIGINT:!1,handleSIGTERM:!1};if(browserOptions.useInstalledOnSystem)if(browserOptions.browserType==="chromium")launchOptions.channel="chrome",launchOptions.args=["--disable-blink-features=AutomationControlled"],launchOptions.ignoreDefaultArgs=["--disable-extensions"];else throw new Error(`Browser type ${browserOptions.browserType} is not supported to be used from the one installed on the system`);return launchOptions}__name(_browserLaunchOptions,"_browserLaunchOptions");async function _createBrowser(browserOptions){let browserInstance;switch(browserOptions.browserType){case"firefox":browserInstance=firefox;break;case"webkit":browserInstance=webkit;break;default:browserInstance=chromium;break}return browserInstance.launch(_browserLaunchOptions(browserOptions))}__name(_createBrowser,"_createBrowser");async function _getBrowser(browserOptions){let browserKey=_browserKey(browserOptions),browserInstance=browsers.get(browserKey);if(browserInstance&&!browserInstance.isConnected()){try{await browserInstance.close().catch(()=>{})}catch{}browserInstance=void 0}return browserInstance||(browserInstance=await _createBrowser(browserOptions),browsers.set(browserKey,browserInstance)),browserInstance}__name(_getBrowser,"_getBrowser");function _persistentBrowserContextKey(browserContextOptions){return browserContextOptions.persistent.userDataDir}__name(_persistentBrowserContextKey,"_persistentBrowserContextKey");function _persistentBrowserContextLaunchOptions(browserContextOptions){let browserOptions=browserContextOptions.browserOptions,launchOptions={headless:browserOptions.headless,executablePath:browserOptions.executablePath,bypassCSP:!0,viewport:browserOptions.headless?void 0:null,locale:browserContextOptions.locale};if(browserOptions.useInstalledOnSystem)if(browserOptions.browserType==="chromium")launchOptions.channel="chrome",launchOptions.args=["--disable-blink-features=AutomationControlled"],launchOptions.ignoreDefaultArgs=["--disable-extensions"];else throw new Error(`Browser type ${browserOptions.browserType} is not supported to be used from the one installed on the system`);return launchOptions}__name(_persistentBrowserContextLaunchOptions,"_persistentBrowserContextLaunchOptions");async function _createPersistentBrowserContext(browserContextOptions){let browserInstance;switch(browserContextOptions.browserOptions.browserType){case"firefox":browserInstance=firefox;break;case"webkit":browserInstance=webkit;break;default:browserInstance=chromium;break}let userDataDir=browserContextOptions.persistent.userDataDir;fs.mkdirSync(userDataDir,{recursive:!0});let browserContext=await browserInstance.launchPersistentContext(userDataDir,_persistentBrowserContextLaunchOptions(browserContextOptions));for(let p of browserContext.pages())try{await p.close()}catch{}return browserContext}__name(_createPersistentBrowserContext,"_createPersistentBrowserContext");async function _getPersistentBrowserContext(browserContextOptions){let persistentBrowserContextKey=_persistentBrowserContextKey(browserContextOptions),browserContext=persistenceBrowserContexts.get(persistentBrowserContextKey);if(browserContext&&!browserContext.browser()?.isConnected()){try{await browserContext.close().catch(()=>{})}catch{}browserContext=void 0}if(!browserContext)browserContext=await _createPersistentBrowserContext(browserContextOptions),persistenceBrowserContexts.set(persistentBrowserContextKey,browserContext);else throw new Error(`There is already active persistent browser context in the user data directory: ${browserContextOptions.persistent?.userDataDir}`);return browserContext}__name(_getPersistentBrowserContext,"_getPersistentBrowserContext");async function newBrowserContext(browserContextOptions={browserOptions:{browserType:DEFAULT_BROWSER_TYPE,headless:BROWSER_HEADLESS_ENABLE,executablePath:BROWSER_EXECUTABLE_PATH,useInstalledOnSystem:BROWSER_USE_INSTALLED_ON_SYSTEM},persistent:BROWSER_PERSISTENT_ENABLE?{userDataDir:BROWSER_PERSISTENT_USER_DATA_DIR}:void 0,locale:BROWSER_LOCALE}){return browserContextOptions.persistent?{browserContext:await _getPersistentBrowserContext(browserContextOptions)}:{browserContext:await(await _getBrowser(browserContextOptions.browserOptions)).newContext({viewport:browserContextOptions.browserOptions.headless?void 0:null,bypassCSP:!0,locale:browserContextOptions.locale})}}__name(newBrowserContext,"newBrowserContext");async function newPage(browserContext,pageOptions={}){return await browserContext.newPage()}__name(newPage,"newPage");async function closeBrowserContext(browserContext){await browserContext.close();let deleted=!1;for(let[key,val]of persistenceBrowserContexts.entries())browserContext===val&&(persistenceBrowserContexts.delete(key),deleted=!0);return deleted}__name(closeBrowserContext,"closeBrowserContext");function _normalizeBasePath(input){let p=input.trim();return p.startsWith("/")||(p="/"+p),p.endsWith("/")||(p=p+"/"),p}__name(_normalizeBasePath,"_normalizeBasePath");function _normalizeUpstreamBaseUrl(input){let u=input.trim();return u&&(u.endsWith("/")?u.slice(0,-1):u)}__name(_normalizeUpstreamBaseUrl,"_normalizeUpstreamBaseUrl");function _computeSuffixPath(fullUrl,basePath){try{let pathname=new URL(fullUrl).pathname;if(!pathname.startsWith(basePath))return null;let raw=pathname.slice(basePath.length);return raw?raw.startsWith("/")?raw:"/"+raw:null}catch{return null}}__name(_computeSuffixPath,"_computeSuffixPath");function _appendSuffixToUpstream(upstreamBaseUrl,suffixPath,originalUrl){try{let qs=new URL(originalUrl).search??"";return upstreamBaseUrl+suffixPath+qs}catch{return upstreamBaseUrl+suffixPath}}__name(_appendSuffixToUpstream,"_appendSuffixToUpstream");var OTELProxy=class{static{__name(this,"OTELProxy")}config;queue;workers;isRunning;isInstalled;metrics;constructor(config){let maxQueueSize=config.maxQueueSize??200,concurrency=config.concurrency??2,respondNoContent=config.respondNoContent??!0,normalizedLocalPath=_normalizeBasePath(config.localPath),normalizedUpstreamUrl=_normalizeUpstreamBaseUrl(config.upstreamUrl);this.config={...config,localPath:normalizedLocalPath,upstreamUrl:normalizedUpstreamUrl,maxQueueSize,concurrency,respondNoContent},this.queue=[],this.workers=[],this.isRunning=!1,this.isInstalled=!1,this.metrics={routedRequests:0,acceptedBatches:0,droppedBatches:0,forwardedBatches:0,failedBatches:0,inFlight:0,queueSize:0,lastError:null}}getMetrics(){return{...this.metrics,queueSize:this.queue.length}}async install(context){if(this.isInstalled)return;let basePath=this.config.localPath;if(!basePath.startsWith("/"))throw new Error('localPath must start with "/" (e.g. "/__mcp_otel/").');let pattern=`**${basePath}**`;await context.route(pattern,async route=>{await this._handleRoute(route)}),this.isInstalled=!0,this.isRunning||await this.start(),debug(`[otel-proxy] installed route pattern: ${pattern} (basePath=${basePath}, upstreamBase=${this.config.upstreamUrl})`)}async uninstall(context){if(!this.isInstalled)return;let pattern=`**${this.config.localPath}**`;try{await context.unroute(pattern)}catch{}this.isInstalled=!1,await this.stop()}async start(){if(this.isRunning)return;this.isRunning=!0;let workerCount=Math.max(1,this.config.concurrency);for(let i=0;i<workerCount;i++){let w=this._workerLoop(i);this.workers.push(w)}debug(`[otel-proxy] started with concurrency=${workerCount}, maxQueueSize=${this.config.maxQueueSize}`)}async stop(){if(this.isRunning){this.isRunning=!1,this.queue.length=0;try{await Promise.allSettled(this.workers)}finally{this.workers.length=0}debug("[otel-proxy] stopped")}}async _handleRoute(route){let req=route.request();if(this.metrics.routedRequests++,req.method().toUpperCase()==="OPTIONS"){await this._fulfillFast(route);return}if(this.config.shouldForward&&!this.config.shouldForward(req)){await this._fulfillFast(route);return}let requestUrl=req.url(),basePath=this.config.localPath,suffixPath=_computeSuffixPath(requestUrl,basePath);if(!suffixPath){await route.fallback();return}let upstreamFullUrl=_appendSuffixToUpstream(this.config.upstreamUrl,suffixPath,requestUrl),body=await req.postDataBuffer()??Buffer.alloc(0),contentType=req.headers()["content-type"]??"application/x-protobuf",method=req.method(),headers={"content-type":contentType};if(this.config.upstreamHeaders)for(let[k,v]of Object.entries(this.config.upstreamHeaders))headers[k]=v;if(this.queue.length>=this.config.maxQueueSize){this.metrics.droppedBatches++,await this._fulfillFast(route),warn(`[otel-proxy] dropped batch (queue full: ${this.queue.length}/${this.config.maxQueueSize}) suffix=${suffixPath}`);return}let item={body,contentType,createdAtMs:Date.now(),upstreamUrl:upstreamFullUrl,method,headers};this.queue.push(item),this.metrics.acceptedBatches++,await this._fulfillFast(route)}async _fulfillFast(route){let status=this.config.respondNoContent?204:200;if(status===204){await route.fulfill({status});return}await route.fulfill({status,headers:{"content-type":"text/plain; charset=utf-8"},body:""})}async _workerLoop(workerIndex){for(;this.isRunning;){let item=this.queue.shift();if(!item){await this._sleep(25);continue}this.metrics.inFlight++;try{await this._forwardUpstream(item),this.metrics.forwardedBatches++}catch(e){this.metrics.failedBatches++;let msg=e instanceof Error?e.message:String(e);this.metrics.lastError=msg,warn(`[otel-proxy] worker=${workerIndex} forward failed: ${msg}`)}finally{this.metrics.inFlight--}}}async _forwardUpstream(item){let res=await fetch(item.upstreamUrl,{method:item.method,headers:item.headers,body:new Uint8Array(item.body)});if(res.status<200||res.status>=300){let text=await this._safeReadText(res);throw new Error(`upstream returned ${res.status} for ${item.upstreamUrl}: ${text}`)}}async _safeReadText(res){try{return(await res.text()).slice(0,500)}catch{return""}}async _sleep(ms){await new Promise(resolve=>{setTimeout(()=>resolve(),ms)})}};import*as fs2 from"node:fs";import*as path3 from"node:path";import{fileURLToPath}from"node:url";var __filename=fileURLToPath(import.meta.url),__dirname=path3.dirname(__filename),OTEL_PROXY_LOCAL_PATH="/__mcp_otel/",OTEL_BUNDLE_FILE_NAME="otel-initializer.bundle.js";function _getOtelAssetsDir(){return OTEL_ASSETS_DIR?OTEL_ASSETS_DIR:path3.join(__dirname,"platform","browser","otel")}__name(_getOtelAssetsDir,"_getOtelAssetsDir");function _getOTELExporterConfig(){if(OTEL_EXPORTER_TYPE==="otlp/http"||OTEL_EXPORTER_HTTP_URL){if(!OTEL_EXPORTER_HTTP_URL)throw new Error('OTEL exporter HTTP url must be set when OTEL exporter type is "otlp/http"');return{type:"otlp/http",url:OTEL_PROXY_LOCAL_PATH,upstreamURL:OTEL_EXPORTER_HTTP_URL,headers:OTEL_EXPORTER_HTTP_HEADERS}}else{if(OTEL_EXPORTER_TYPE==="console")return{type:"console"};if(OTEL_EXPORTER_TYPE==="none")return{type:"none"};throw new Error(`Invalid OTEL exporter type ${OTEL_EXPORTER_TYPE}`)}}__name(_getOTELExporterConfig,"_getOTELExporterConfig");function _getOTELInstrumentationConfig(){return{userInteractionEvents:OTEL_INSTRUMENTATION_USER_INTERACTION_EVENTS}}__name(_getOTELInstrumentationConfig,"_getOTELInstrumentationConfig");function _getOTELConfig(){return{serviceName:OTEL_SERVICE_NAME,serviceVersion:OTEL_SERVICE_VERSION,exporter:_getOTELExporterConfig(),instrumentation:_getOTELInstrumentationConfig(),debug:!1}}__name(_getOTELConfig,"_getOTELConfig");function _readBundleContent(assetDir,bundleFileName){let assetDirAbs=path3.isAbsolute(assetDir)?assetDir:path3.join(process.cwd(),assetDir),filePath=path3.join(assetDirAbs,bundleFileName);if(!fs2.existsSync(filePath))throw new Error(`OTEL bundle not found at: ${filePath}`);return fs2.readFileSync(filePath,"utf-8")}__name(_readBundleContent,"_readBundleContent");async function _applyConfigToPage(page,cfg){await page.evaluate(nextCfg=>{let g=globalThis;g.__MCP_DEVTOOLS__||(g.__MCP_DEVTOOLS__={}),g.__MCP_TRACE_ID__=nextCfg.traceId,g.__mcpOtel&&typeof g.__mcpOtel.init=="function"?g.__mcpOtel.init(nextCfg):(g.__MCP_DEVTOOLS__.otelInitialized=!1,g.__MCP_DEVTOOLS__.otelInitError="__mcpOtel.init is not available while applying config")},cfg).catch(e=>{let msg=e instanceof Error?e.message:String(e);debug(`[otel-controller] applyConfigToPage failed (ignored): ${msg}`)})}__name(_applyConfigToPage,"_applyConfigToPage");function _installAutoSync(browserContext,getCfg){let perPageHandlers=new WeakMap,attachToPage=__name(page=>{if(perPageHandlers.has(page))return;let onFrameNavigated=__name(async frame=>{frame===page.mainFrame()&&await _applyConfigToPage(page,getCfg())},"onFrameNavigated");perPageHandlers.set(page,onFrameNavigated),page.on("framenavigated",onFrameNavigated)},"attachToPage");for(let p of browserContext.pages())attachToPage(p);let onNewPage=__name(p=>{attachToPage(p)},"onNewPage");browserContext.on("page",onNewPage);let detach=__name(()=>{try{browserContext.off("page",onNewPage)}catch{}for(let p of browserContext.pages()){let h=perPageHandlers.get(p);if(h)try{p.off("framenavigated",h)}catch{}}},"detach");return debug("[otel-controller] auto-sync installed (page+framenavigated)"),{detach}}__name(_installAutoSync,"_installAutoSync");var OTELController=class{static{__name(this,"OTELController")}browserContext;config;proxy;initialized=!1;autoSyncDetach;constructor(browserContext){this.browserContext=browserContext,this.config=_getOTELConfig()}async init(options){if(this.initialized){debug("[otel-controller] init skipped: BrowserContext already initialized");return}if(!options.traceId||!options.traceId.trim())throw new Error("[otel-controller] init requires a non-empty traceId");this.config.traceId=options.traceId;let assetDir=_getOtelAssetsDir();this.config.exporter.type==="otlp/http"&&(this.proxy=new OTELProxy({localPath:OTEL_PROXY_LOCAL_PATH,upstreamUrl:this.config.exporter.upstreamURL,upstreamHeaders:{...this.config.exporter.headers??{}}}),await this.proxy.install(this.browserContext)),debug(`[otel-controller] exporter=${this.config.exporter.type} localBase=${OTEL_PROXY_LOCAL_PATH}`+(this.config.exporter.type==="otlp/http"?` upstreamBase=${this.config.exporter.upstreamURL}`:""));let bundleContent=_readBundleContent(assetDir,OTEL_BUNDLE_FILE_NAME),sync=_installAutoSync(this.browserContext,()=>this.config);this.autoSyncDetach=sync.detach,await this.browserContext.addInitScript({content:bundleContent}),await this.browserContext.addInitScript(cfg=>{let g=globalThis;g.__MCP_DEVTOOLS__||(g.__MCP_DEVTOOLS__={}),g.__MCP_TRACE_ID__=cfg.traceId,g.__mcpOtel&&typeof g.__mcpOtel.init=="function"?g.__mcpOtel.init(cfg):(g.__MCP_DEVTOOLS__.otelInitialized=!1,g.__MCP_DEVTOOLS__.otelInitError="__mcpOtel.init is not available (initializer bundle did not install)")},this.config),this.initialized=!0,debug("[otel-controller] init installed: bundle + config init scripts + auto-sync")}isOTELRequest(request){return new URL(request.url()).pathname.startsWith(OTEL_PROXY_LOCAL_PATH)}async isInitialized(page){return await page.evaluate(()=>globalThis.__MCP_DEVTOOLS__?.otelInitialized===!0)}async getInitError(page){return await page.evaluate(()=>{let v=globalThis.__MCP_DEVTOOLS__?.otelInitError;if(typeof v=="string"&&v.trim())return v})}async getTraceId(page){return await page.evaluate(()=>{let g=globalThis;if(g.__mcpOtel&&typeof g.__mcpOtel.getTraceId=="function"){let tid=g.__mcpOtel.getTraceId();if(typeof tid=="string"&&tid.trim())return tid}let fallback=g.__MCP_TRACE_ID__;if(typeof fallback=="string"&&fallback.trim())return fallback})}async setTraceId(page,traceId){this.config.traceId=traceId,await page.evaluate(tid=>{let g=globalThis;g.__mcpOtel&&typeof g.__mcpOtel.setTraceId=="function"?g.__mcpOtel.setTraceId(tid):g.__MCP_TRACE_ID__=tid},traceId)}async close(){if(this.autoSyncDetach){try{this.autoSyncDetach()}catch{}this.autoSyncDetach=void 0}this.proxy&&(await this.proxy.uninstall(this.browserContext),this.proxy=void 0)}};var BrowserToolSessionContext=class{static{__name(this,"BrowserToolSessionContext")}_sessionId;options;otelController;consoleMessages=[];httpRequests=[];initialized=!1;closed=!1;traceId;_numOfInFlightRequests=0;_lastNetworkActivityTimestamp=0;browserContext;page;constructor(sessionId,browserContext,page,options){this._sessionId=sessionId,this.browserContext=browserContext,this.page=page,this.options=options,this.otelController=new OTELController(this.browserContext)}async init(){if(this.closed)throw new Error("Session context is already closed");if(this.initialized)throw new Error("Session context is already initialized");let me=this,consoleMessageSequenceNumber=0;this.page.on("console",msg=>{me.consoleMessages.push(me._toConsoleMessage(msg,++consoleMessageSequenceNumber)),me.consoleMessages.length>BROWSER_CONSOLE_MESSAGES_BUFFER_SIZE&&me.consoleMessages.splice(0,me.consoleMessages.length-BROWSER_CONSOLE_MESSAGES_BUFFER_SIZE)}),this.page.on("pageerror",err=>{me.consoleMessages.push(me._errorToConsoleMessage(err,++consoleMessageSequenceNumber)),me.consoleMessages.length>BROWSER_CONSOLE_MESSAGES_BUFFER_SIZE&&me.consoleMessages.splice(0,me.consoleMessages.length-BROWSER_CONSOLE_MESSAGES_BUFFER_SIZE)});let httpRequestSequenceNumber=0;this.page.on("request",async req=>{me.otelController.isOTELRequest(req)||(me._numOfInFlightRequests++,me._lastNetworkActivityTimestamp=Date.now())}),this.page.on("requestfinished",async req=>{me.otelController.isOTELRequest(req)||(me._numOfInFlightRequests--,me._lastNetworkActivityTimestamp=Date.now(),me.httpRequests.push(await me._toHttpRequest(req,++httpRequestSequenceNumber)),me.httpRequests.length>BROWSER_HTTP_REQUESTS_BUFFER_SIZE&&me.httpRequests.splice(0,me.httpRequests.length-BROWSER_HTTP_REQUESTS_BUFFER_SIZE))}),this.page.on("requestfailed",async req=>{me.otelController.isOTELRequest(req)||(me._numOfInFlightRequests--,me._lastNetworkActivityTimestamp=Date.now(),me.httpRequests.push(await me._toHttpRequest(req,++httpRequestSequenceNumber)),me.httpRequests.length>BROWSER_HTTP_REQUESTS_BUFFER_SIZE&&me.httpRequests.splice(0,me.httpRequests.length-BROWSER_HTTP_REQUESTS_BUFFER_SIZE))}),this.options.otelEnable&&(this.traceId=newTraceId(),await this.otelController.init({traceId:this.traceId})),this.initialized=!0}_toConsoleMessageLevelName(type){switch(type){case"assert":case"error":return"error";case"warning":return"warning";case"count":case"dir":case"dirxml":case"info":case"log":case"table":case"time":case"timeEnd":return"info";case"clear":case"debug":case"endGroup":case"profile":case"profileEnd":case"startGroup":case"startGroupCollapsed":case"trace":return"debug";default:return"info"}}_toConsoleMessage(message,sequenceNumber){let timestamp=Date.now(),levelName=this._toConsoleMessageLevelName(message.type()),levelCode=ConsoleMessageLevel[levelName].code;return{type:message.type(),text:message.text(),level:{name:levelName,code:levelCode},location:{url:message.location().url,lineNumber:message.location().lineNumber,columnNumber:message.location().columnNumber},timestamp,sequenceNumber}}_errorToConsoleMessage(error,sequenceNumber){let timestamp=Date.now();return error instanceof Error?{type:"error",text:error.message,level:{name:"error",code:3},timestamp,sequenceNumber}:{type:"error",text:String(error),level:{name:"error",code:3},timestamp,sequenceNumber}}_isBodyLikelyPresent(status,method){return!(method==="HEAD"||method==="OPTIONS"||status===204||status===304||status>=300&&status<400)}async _safeReadResponseBody(res){try{let method=res.request().method(),status=res.status();return this._isBodyLikelyPresent(status,method)?(await res.body()).toString("utf-8"):void 0}catch{return}}async _toHttpRequest(req,sequenceNumber){let res=await req.response();return{url:req.url(),method:req.method(),headers:req.headers(),body:req.postData()||void 0,resourceType:req.resourceType(),failure:req.failure()?.errorText,duration:req.timing().responseEnd,response:res?{status:res.status(),statusText:res.statusText(),headers:res.headers(),body:await this._safeReadResponseBody(res)}:void 0,ok:res?res.ok():!1,timestamp:Math.floor(req.timing().startTime),sequenceNumber}}numOfInFlightRequests(){return this._numOfInFlightRequests}lastNetworkActivityTimestamp(){return this._lastNetworkActivityTimestamp}sessionId(){return this._sessionId}async getTraceId(){return this.traceId}async setTraceId(traceId){if(!this.options.otelEnable)throw new Error("OTEL is not enabled");this.traceId=traceId,await this.otelController.setTraceId(this.page,traceId)}getConsoleMessages(){return this.consoleMessages}getHttpRequests(){return this.httpRequests}async close(){if(this.closed)return!1;debug(`Closing OTEL controller of the session with id ${this._sessionId} ...`),await this.otelController.close();try{debug(`Closing browser context of the session with id ${this._sessionId} ...`),await closeBrowserContext(this.browserContext)}catch(err){debug(`Error occurred while closing browser context of the session with id ${this._sessionId} ...`,err)}return this.consoleMessages.length=0,this.httpRequests.length=0,this.closed=!0,!0}};var BrowserToolExecutor=class{static{__name(this,"BrowserToolExecutor")}sessionIdProvider;sessionContext;constructor(sessionIdProvider){this.sessionIdProvider=sessionIdProvider}async _createSessionContext(){let browserContextInfo=await newBrowserContext(),page=await newPage(browserContextInfo.browserContext),sessionId=this.sessionIdProvider(),context=new BrowserToolSessionContext(sessionId,browserContextInfo.browserContext,page,{otelEnable:OTEL_ENABLE});return await context.init(),context}async _sessionContext(){return this.sessionContext||(this.sessionContext=await this._createSessionContext(),debug(`Created session context on the first tool call for the session with id ${this.sessionContext.sessionId()}`)),this.sessionContext}async executeTool(tool,args){debug(`Executing tool ${tool.name()} with input: ${toJson(args)}`);try{let sessionContext=await this._sessionContext(),result=await tool.handle(sessionContext,args);return debug(`Executed tool ${tool.name()} and got output: ${toJson(result)}`),result}catch(err){throw debug(`Error occurred while executing ${tool.name()}: ${err}`),err}}};var tools12=[...tools,...tools2,...tools3,...tools4,...tools5,...tools6,...tools7,...tools8,...tools9,...tools10,...tools11];function createToolExecutor(sessionIdProvider){return new BrowserToolExecutor(sessionIdProvider)}__name(createToolExecutor,"createToolExecutor");import{Option}from"commander";var BrowserCliProvider=class{static{__name(this,"BrowserCliProvider")}platform="browser";cliName="browser-devtools-cli";tools=tools12;sessionDescription="Manage browser sessions";cliExamples=["browser-devtools-cli --no-headless interactive","browser-devtools-cli --persistent --no-headless interactive"];bashCompletionOptions="--headless --no-headless --persistent --no-persistent --user-data-dir --use-system-browser --browser-path";bashCompletionCommands="daemon session tools config completion interactive navigation content interaction a11y accessibility o11y react run stub sync figma debug";zshCompletionOptions=` '--headless[Run in headless mode]' \\
|
|
771
|
-
'--no-headless[Run in headful mode]' \\
|
|
772
|
-
'--persistent[Use persistent context]' \\
|
|
773
|
-
'--no-persistent[Use ephemeral context]' \\
|
|
774
|
-
'--user-data-dir[User data directory]:path:_files -/' \\
|
|
775
|
-
'--use-system-browser[Use system browser]' \\
|
|
776
|
-
'--browser-path[Browser executable path]:path:_files' \\`;zshCompletionCommands=[{name:"daemon",description:"Manage the daemon server"},{name:"session",description:"Manage browser sessions"},{name:"tools",description:"List and inspect available tools"},{name:"config",description:"Show current configuration"},{name:"completion",description:"Generate shell completion scripts"},{name:"interactive",description:"Start interactive REPL mode"},{name:"navigation",description:"Navigation commands"},{name:"content",description:"Content extraction commands"},{name:"interaction",description:"Interaction commands"},{name:"a11y",description:"Accessibility commands"},{name:"accessibility",description:"Extended accessibility commands"},{name:"o11y",description:"Observability commands"},{name:"react",description:"React debugging commands"},{name:"run",description:"Script execution commands"},{name:"stub",description:"HTTP stubbing commands"},{name:"sync",description:"Synchronization commands"},{name:"figma",description:"Figma integration commands"},{name:"debug",description:"Non-blocking debugging commands"}];replPrompt="browser> ";cliDescription="Browser DevTools MCP CLI";packageName="browser-devtools-mcp";buildEnv(opts){let env={...process.env};return opts.headless!==void 0&&(env.BROWSER_HEADLESS_ENABLE=String(opts.headless)),opts.persistent!==void 0&&(env.BROWSER_PERSISTENT_ENABLE=String(opts.persistent)),opts.userDataDir!==void 0&&(env.BROWSER_PERSISTENT_USER_DATA_DIR=opts.userDataDir),opts.useSystemBrowser!==void 0&&(env.BROWSER_USE_INSTALLED_ON_SYSTEM=String(opts.useSystemBrowser)),opts.browserPath!==void 0&&(env.BROWSER_EXECUTABLE_PATH=opts.browserPath),env}addOptions(cmd){return cmd.addOption(new Option("--headless","Run browser in headless mode (no visible window)").default(BROWSER_HEADLESS_ENABLE)).addOption(new Option("--no-headless","Run browser in headful mode (visible window)")).addOption(new Option("--persistent","Use persistent browser context (preserves cookies, localStorage)").default(BROWSER_PERSISTENT_ENABLE)).addOption(new Option("--no-persistent","Use ephemeral browser context (cleared on session end)")).addOption(new Option("--user-data-dir <path>","Directory for persistent browser context user data").default(BROWSER_PERSISTENT_USER_DATA_DIR)).addOption(new Option("--use-system-browser","Use system-installed Chrome instead of bundled browser").default(BROWSER_USE_INSTALLED_ON_SYSTEM)).addOption(new Option("--browser-path <path>","Custom browser executable path"))}getConfig(){return{headless:BROWSER_HEADLESS_ENABLE,persistent:BROWSER_PERSISTENT_ENABLE,userDataDir:BROWSER_PERSISTENT_USER_DATA_DIR,useSystemBrowser:BROWSER_USE_INSTALLED_ON_SYSTEM,executablePath:BROWSER_EXECUTABLE_PATH,locale:BROWSER_LOCALE}}formatConfig(configValues){let lines=[" Browser:",` Headless: ${configValues.headless}`,` Persistent: ${configValues.persistent}`,` User Data Dir: ${configValues.userDataDir||"(default)"}`,` Use System Browser: ${configValues.useSystemBrowser}`,` Executable Path: ${configValues.executablePath||"(bundled)"}`];return configValues.locale&&lines.push(` Locale: ${configValues.locale}`),lines.join(`
|
|
777
|
-
`)}formatConfigForRepl(opts){return[` headless = ${opts.headless??BROWSER_HEADLESS_ENABLE}`,` persistent = ${opts.persistent??BROWSER_PERSISTENT_ENABLE}`,` user-data-dir = ${opts.userDataDir||BROWSER_PERSISTENT_USER_DATA_DIR||"(default)"}`,` use-system-browser = ${opts.useSystemBrowser??BROWSER_USE_INSTALLED_ON_SYSTEM}`,` browser-path = ${opts.browserPath||"(auto)"}`].join(`
|
|
778
|
-
`)}},cliProvider=new BrowserCliProvider;var SERVER_INSTRUCTIONS=`
|
|
779
|
-
This MCP server exposes a Playwright-powered browser runtime to AI agents,
|
|
780
|
-
enabling deep, bidirectional debugging and interaction with live web pages.
|
|
781
|
-
|
|
782
|
-
It supports both visual understanding and code-level inspection of browser state,
|
|
783
|
-
similar to existing Playwright and Chrome DevTools\u2013based MCP servers, with a focus on AI-driven exploration, diagnosis, and action.
|
|
784
|
-
|
|
785
|
-
Core capabilities include:
|
|
786
|
-
|
|
787
|
-
**Content & Visual Inspection:**
|
|
788
|
-
- Screenshots (full page or specific elements)
|
|
789
|
-
- HTML and text content extraction with filtering options
|
|
790
|
-
- PDF generation with customizable formats
|
|
791
|
-
- Design comparison: Compare live page UI against Figma designs with similarity scoring
|
|
792
|
-
- Accessibility snapshots (ARIA and AX tree) with visual diagnostics
|
|
793
|
-
- Viewport and window resizing for responsive testing
|
|
794
|
-
|
|
795
|
-
**Browser Control & Interaction:**
|
|
796
|
-
- Navigation (go to URL, back, forward)
|
|
797
|
-
- Element interaction (click, fill, hover, select, drag)
|
|
798
|
-
- Keyboard simulation (press-key)
|
|
799
|
-
- Scrolling (viewport or container-based with multiple modes)
|
|
800
|
-
- Viewport emulation and real window resizing
|
|
801
|
-
|
|
802
|
-
**JavaScript Execution:**
|
|
803
|
-
- Run JavaScript in browser page context (access to window, document, DOM, Web APIs)
|
|
804
|
-
- Run JavaScript in Node.js VM sandbox on the server (with Playwright Page access and safe built-ins)
|
|
805
|
-
|
|
806
|
-
**Observability & Monitoring:**
|
|
807
|
-
- Console message capture with filtering
|
|
808
|
-
- HTTP request/response monitoring with detailed filtering
|
|
809
|
-
- Web Vitals performance metrics (LCP, INP, CLS, TTFB, FCP) with recommendations
|
|
810
|
-
- OpenTelemetry trace ID management for distributed tracing correlation
|
|
811
|
-
|
|
812
|
-
**Network Stubbing & Mocking:**
|
|
813
|
-
- HTTP request interception and modification (headers, body, method) using glob patterns
|
|
814
|
-
- HTTP response mocking (fulfill with custom status/headers/body or abort) with configurable delay, times limit, and probability
|
|
815
|
-
- Stub management (list all installed stubs, clear specific or all stubs)
|
|
816
|
-
- Supports A/B testing, security testing, offline testing, error scenarios, and flaky API testing
|
|
817
|
-
|
|
818
|
-
**Synchronization:**
|
|
819
|
-
- Network idle waiting for async operations
|
|
820
|
-
- Configurable timeouts and polling intervals
|
|
821
|
-
|
|
822
|
-
**Design Comparison:**
|
|
823
|
-
- Figma design comparison: Compare live page UI against Figma design snapshots
|
|
824
|
-
- Multi-signal similarity scoring (MSSIM, image embedding, text embedding)
|
|
825
|
-
- Configurable weights and comparison modes (raw vs semantic)
|
|
826
|
-
|
|
827
|
-
**React Component Inspection:**
|
|
828
|
-
- Get component for element: Find React component(s) associated with a DOM element using React Fiber
|
|
829
|
-
- Get element for component: Map a React component instance to the DOM elements it renders
|
|
830
|
-
- Requires persistent browser context (BROWSER_PERSISTENT_ENABLE=true) for optimal operation
|
|
831
|
-
- React DevTools extension must be manually installed in the browser profile (MCP server does NOT auto-install)
|
|
832
|
-
- Without extension, tools fall back to best-effort DOM scanning for __reactFiber$ pointers (less reliable)
|
|
833
|
-
|
|
834
|
-
**Non-Blocking Debugging:**
|
|
835
|
-
- Tracepoints: Capture call stack, local variables, and watch expressions at specific code locations without pausing execution
|
|
836
|
-
- Logpoints: Evaluate and log expressions at code locations (lightweight alternative to tracepoints)
|
|
837
|
-
- Exceptionpoints: Automatically capture snapshots when uncaught or all exceptions occur
|
|
838
|
-
- Netpoints: Monitor specific network requests/responses matching URL patterns
|
|
839
|
-
- Dompoints: Monitor DOM mutations (attribute changes, subtree modifications, node removal) on specific elements
|
|
840
|
-
- Watch expressions: Evaluate custom expressions at every tracepoint hit
|
|
841
|
-
- Source map support: Automatically resolves bundled code locations to original source files
|
|
842
|
-
- Snapshot retrieval: Query captured snapshots by probe ID or sequence number for incremental polling
|
|
843
|
-
|
|
844
|
-
**Advanced Features:**
|
|
845
|
-
- OpenTelemetry integration: Automatic UI trace collection and backend trace correlation
|
|
846
|
-
- Session-based architecture with long-lived browser contexts
|
|
847
|
-
- Persistent browser contexts for stateful sessions (required for React tools)
|
|
848
|
-
- Headless and headful mode support
|
|
849
|
-
- System-installed browser usage option
|
|
850
|
-
- Streamable responses and server-initiated notifications
|
|
851
|
-
- Clean lifecycle management and teardown
|
|
852
|
-
|
|
853
|
-
UI debugging guidance for AI agents:
|
|
854
|
-
|
|
855
|
-
*** INSPECTION PREFERENCE (follow this order) ***
|
|
856
|
-
1. Prefer "a11y_take-aria-snapshot" first for page structure, roles, and semantics. Use it when you need to understand what is on the page, hierarchy, or accessibility.
|
|
857
|
-
2. If you need layout, bounding boxes, visibility, or occlusion: use "a11y_take-ax-tree-snapshot" (optionally with checkOcclusion:true). This often suffices instead of a screenshot.
|
|
858
|
-
3. Use "content_take-screenshot" ONLY when you genuinely need to see how the UI looks visually (e.g. visual design check, pixel-level verification, or when snapshots are insufficient). Do not take screenshots just to "see the page"\u2014use ARIA or AX snapshot instead.
|
|
859
|
-
*** SCREENSHOT TOOL: includeBase64 ***
|
|
860
|
-
- The screenshot is always saved to disk; the tool returns the file path. Do NOT set includeBase64 to true unless the assistant cannot read files from that path (e.g. remote MCP server, container). Leave includeBase64 false (default) to avoid large responses; read the image from the returned path when possible.
|
|
861
|
-
|
|
862
|
-
- Prefer Accessibility (AX) and ARIA snapshots over raw DOM dumps when diagnosing UI problems.
|
|
863
|
-
These snapshots provide higher-signal, semantically meaningful anchors (roles, names, states) that
|
|
864
|
-
map more reliably to what users perceive and what assistive tech can interact with.
|
|
865
|
-
- Use the AX Tree Snapshot tool to correlate interactive semantics with runtime visual truth:
|
|
866
|
-
bounding boxes, visibility, viewport intersection, and (optionally) computed styles.
|
|
867
|
-
- If a UI control appears present but interactions fail (e.g., clicks do nothing), suspect overlap/occlusion.
|
|
868
|
-
In such cases, enable occlusion checking ("elementFromPoint") to identify which element is actually on top.
|
|
869
|
-
- Use ARIA snapshots to reason about accessibility roles/states and to validate that the intended
|
|
870
|
-
semantics (labels, roles, disabled state, focusability) match the visible UI.
|
|
871
|
-
- Before taking screenshots or snapshots, wait for network idle to ensure page stability.
|
|
872
|
-
- Use Web Vitals tool to assess performance and identify optimization opportunities.
|
|
873
|
-
- For design validation, use "figma_compare-page-with-design" to compare live page UI against Figma designs:
|
|
874
|
-
- Use "semantic" MSSIM mode for comparing real data vs design data (less sensitive to text/value differences)
|
|
875
|
-
- Use "raw" MSSIM mode only when expecting near pixel-identical output
|
|
876
|
-
- If layout mismatch is suspected, run with fullPage=true first, then retry with a selector for the problematic region
|
|
877
|
-
- Notes explain which signals were used or skipped; skipped signals usually mean missing cloud configuration
|
|
878
|
-
- For React component inspection, use "react_get-component-for-element" and "react_get-element-for-component":
|
|
879
|
-
- These tools work best with persistent browser context enabled (BROWSER_PERSISTENT_ENABLE=true)
|
|
880
|
-
- React DevTools extension must be manually installed in the browser profile (MCP server does NOT auto-install)
|
|
881
|
-
- Chrome Web Store: https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi
|
|
882
|
-
- Without extension, tools use best-effort DOM scanning (less reliable than using DevTools hook)
|
|
883
|
-
- Component names and debug source info are best-effort and may vary by build (dev/prod)
|
|
884
|
-
- For distributed tracing, set trace IDs before navigation to correlate frontend and backend traces.
|
|
885
|
-
- For testing and debugging scenarios, use stub tools to intercept/modify requests or mock responses:
|
|
886
|
-
- Use "stub_intercept-http-request" to modify outgoing requests (inject headers, change body/method)
|
|
887
|
-
- Use "stub_mock-http-response" to mock responses for offline testing, error scenarios, or flaky API simulation
|
|
888
|
-
- Use "stub_list" to check what stubs are active and "stub_clear" to remove them when done
|
|
889
|
-
- For non-blocking JavaScript debugging:
|
|
890
|
-
- Use "debug_put-tracepoint" to capture call stack, local variables, and watch expressions at specific code locations
|
|
891
|
-
- Use "debug_put-logpoint" for lightweight logging at code locations (no call stack capture)
|
|
892
|
-
- Use "debug_put-exceptionpoint" to capture snapshots when exceptions occur (state: "uncaught" or "all")
|
|
893
|
-
- Use "debug_put-netpoint" to monitor specific network requests/responses by URL pattern
|
|
894
|
-
- Use "debug_put-dompoint" to monitor DOM mutations on specific elements
|
|
895
|
-
- Use "debug_add-watch" to add watch expressions evaluated at every tracepoint hit
|
|
896
|
-
- Use "debug_get-tracepoint-snapshots", "debug_get-logpoint-snapshots", etc. to retrieve captured data
|
|
897
|
-
- Use "fromSequence" parameter for incremental polling of new snapshots
|
|
898
|
-
- Tracepoints/logpoints support source maps: set probes on original source file locations
|
|
899
|
-
|
|
900
|
-
This server is designed for AI coding assistants, visual debugging agents, and automated analysis tools
|
|
901
|
-
that need to reason about what a page looks like, how it is structured, and how it behaves \u2014 all through a single MCP interface.
|
|
902
|
-
|
|
903
|
-
It treats the browser as a queryable, inspectable, and controllable execution environment rather than a static screenshot source.
|
|
904
|
-
`,UI_DEBUGGING_POLICY=`
|
|
905
|
-
<ui_debugging_policy>
|
|
906
|
-
When asked to check for UI problems, layout issues, or visual bugs, ALWAYS follow this policy:
|
|
907
|
-
|
|
908
|
-
1. **Synchronization**: If the page loads content asynchronously, call "sync_wait-for-network-idle" first
|
|
909
|
-
to ensure the page is stable before inspection.
|
|
910
|
-
|
|
911
|
-
2. **Inspection order (prefer snapshots over screenshots)**:
|
|
912
|
-
- First try "a11y_take-aria-snapshot" for structure, roles, and semantics.
|
|
913
|
-
- If you need layout/occlusion/visibility: use "a11y_take-ax-tree-snapshot" (with "checkOcclusion:true" when interactions fail).
|
|
914
|
-
- Call "content_take-screenshot" ONLY when you truly need to see the visual appearance of the UI (e.g. design check, pixel verification). Do not take screenshots just to see the page\u2014use ARIA or AX snapshot instead.
|
|
915
|
-
- When taking a screenshot, do NOT set "includeBase64" to true unless the assistant cannot read the returned file path (e.g. remote/container). The image is always saved to disk.
|
|
916
|
-
|
|
917
|
-
3. **Accessibility Tree Analysis**: Call "a11y_take-ax-tree-snapshot" tool with "checkOcclusion:true"
|
|
918
|
-
- Provides precise bounding boxes, runtime visual data, and occlusion detection
|
|
919
|
-
- Best for detecting overlaps and measuring exact positions
|
|
920
|
-
- Use "onlyVisible:true" or "onlyInViewport:true" to filter results
|
|
921
|
-
- Set "includeStyles:true" to analyze computed CSS properties
|
|
922
|
-
|
|
923
|
-
4. **ARIA Snapshot**: Call "a11y_take-aria-snapshot" tool (full page or specific selector)
|
|
924
|
-
- Provides semantic structure and accessibility roles
|
|
925
|
-
- Best for understanding page hierarchy and accessibility issues
|
|
926
|
-
- Use in combination with AX tree snapshot for comprehensive analysis
|
|
927
|
-
|
|
928
|
-
5. **Design Comparison** (if Figma design is available): Call "figma_compare-page-with-design" tool
|
|
929
|
-
- Compares live page UI against Figma design snapshot
|
|
930
|
-
- Returns combined similarity score using multiple signals (MSSIM, image embedding, text embedding)
|
|
931
|
-
- Use "semantic" mode for real data vs design data comparisons
|
|
932
|
-
- Use "raw" mode only when expecting pixel-identical output
|
|
933
|
-
- Notes explain which signals were used or skipped
|
|
934
|
-
|
|
935
|
-
6. **React Component Inspection** (if page uses React): Use React tools to understand component structure
|
|
936
|
-
- Call "react_get-component-for-element" with selector or (x,y) to find React component for a DOM element
|
|
937
|
-
- Call "react_get-element-for-component" to find DOM elements rendered by a React component
|
|
938
|
-
- **Important:** These tools require persistent browser context (BROWSER_PERSISTENT_ENABLE=true)
|
|
939
|
-
- React DevTools extension must be manually installed in the browser profile for optimal reliability
|
|
940
|
-
- Without extension, tools use best-effort DOM scanning (less reliable)
|
|
941
|
-
- Component names and debug source info are best-effort and may vary by build (dev/prod)
|
|
942
|
-
|
|
943
|
-
7. **Performance Check** (optional but recommended): Call "o11y_get-web-vitals" to assess page performance
|
|
944
|
-
- Identifies performance issues that may affect user experience
|
|
945
|
-
- Provides actionable recommendations based on Google's thresholds
|
|
946
|
-
|
|
947
|
-
8. **Console & Network Inspection**: Check for errors and failed requests
|
|
948
|
-
- Call "o11y_get-console-messages" with "type:ERROR" to find JavaScript errors
|
|
949
|
-
- Call "o11y_get-http-requests" with "ok:false" to find failed network requests
|
|
950
|
-
- If network issues are suspected or testing error scenarios, use stub tools:
|
|
951
|
-
- Use "stub_mock-http-response" to simulate error responses (e.g., 500, 404, timeout) to test UI error handling
|
|
952
|
-
- Use "stub_intercept-http-request" to modify requests (e.g., inject headers) to test different scenarios
|
|
953
|
-
- Use "stub_list" to verify active stubs and "stub_clear" to remove them after testing
|
|
954
|
-
|
|
955
|
-
9. **Manual Verification**: Calculate bounding box overlaps:
|
|
956
|
-
- Horizontal: (element1.x + element1.width) \u2264 element2.x
|
|
957
|
-
- Vertical: (element1.y + element1.height) \u2264 element2.y
|
|
958
|
-
|
|
959
|
-
10. **Report ALL findings**: aesthetic issues, overlaps, spacing problems, alignment issues,
|
|
960
|
-
accessibility problems, semantic structure issues, design parity issues (if compared with Figma),
|
|
961
|
-
React component structure issues (if inspected), performance problems, console errors, failed requests
|
|
962
|
-
|
|
963
|
-
11. **JavaScript Execution** (when needed for advanced debugging):
|
|
964
|
-
- Use "run_js-in-browser" to inspect or mutate DOM state, read client-side variables, or extract computed values directly from the page
|
|
965
|
-
- Use "run_js-in-sandbox" for server-side automation logic that needs access to Playwright Page object or safe built-ins
|
|
966
|
-
|
|
967
|
-
12. **Non-Blocking JavaScript Debugging** (for deep code investigation):
|
|
968
|
-
- Use "debug_put-tracepoint" to set breakpoints that capture call stack and local variables without pausing
|
|
969
|
-
- Use "debug_put-logpoint" for lightweight logging at specific code locations
|
|
970
|
-
- Use "debug_put-exceptionpoint" with state "uncaught" or "all" to capture exception snapshots
|
|
971
|
-
- Use "debug_put-netpoint" to monitor specific network requests by URL pattern
|
|
972
|
-
- Use "debug_put-dompoint" to monitor DOM mutations (attributes, subtree, removal) on elements
|
|
973
|
-
- Use "debug_add-watch" to add expressions evaluated at every tracepoint hit
|
|
974
|
-
- Retrieve snapshots with "debug_get-tracepoint-snapshots", "debug_get-logpoint-snapshots", etc.
|
|
975
|
-
- Use "fromSequence" parameter to poll only new snapshots since last retrieval
|
|
976
|
-
- Probes support source maps: specify original source file paths for bundled applications
|
|
977
|
-
- Use "debug_status" to check current debugging state and probe counts
|
|
978
|
-
|
|
979
|
-
**Tool Usage Notes:**
|
|
980
|
-
- ARIA snapshot first for structure/roles/semantics; then AX tree for layout/occlusion/positioning.
|
|
981
|
-
- Screenshot only when you must see the actual pixels (e.g. visual design); otherwise use snapshots.
|
|
982
|
-
- Do not set includeBase64 on screenshot unless the assistant cannot read the file path.
|
|
983
|
-
- AX tree: Technical measurements, occlusion, precise positioning, visual diagnostics
|
|
984
|
-
- ARIA snapshot: Semantic understanding, accessibility structure, role hierarchy
|
|
985
|
-
- Network idle: Essential for SPAs and async content
|
|
986
|
-
- Web Vitals: Performance context for UI issues
|
|
987
|
-
- Tracepoints: Deep code investigation with call stack and variables (non-blocking)
|
|
988
|
-
- Logpoints: Lightweight logging at specific code locations
|
|
989
|
-
- Exceptionpoints: Automatic exception capture without manual breakpoints
|
|
990
|
-
- Netpoints/Dompoints: Monitor network and DOM changes without code modification
|
|
991
|
-
|
|
992
|
-
**Important:**
|
|
993
|
-
- Never assume "looks good visually" = "no problems". Overlaps and accessibility issues
|
|
994
|
-
can be functionally broken while appearing visually correct.
|
|
995
|
-
- Always check occlusion when interactions fail or elements appear misaligned.
|
|
996
|
-
- Use scroll tool if elements are below the fold before inspection.
|
|
997
|
-
- For responsive issues, use resize-viewport or resize-window tools to test different sizes.
|
|
998
|
-
</ui_debugging_policy>
|
|
999
|
-
`;var platformInfo={serverInfo:{instructions:SERVER_INSTRUCTIONS,policies:[UI_DEBUGGING_POLICY]},toolsInfo:{tools:tools12,createToolExecutor},cliInfo:{cliProvider}};import{z as z70}from"zod";var Connect=class{static{__name(this,"Connect")}name(){return"debug_connect"}description(){return`
|
|
1000
|
-
Connects to a Node.js process for V8 debugging.
|
|
1001
|
-
|
|
1002
|
-
Supports multiple connection methods:
|
|
1003
|
-
- By PID: Specify the process ID directly
|
|
1004
|
-
- By process name: Search for a Node.js process by name pattern
|
|
1005
|
-
- By Docker container: Use containerId or containerName (with port 9229 exposed)
|
|
1006
|
-
- By port: Connect to an already-active inspector on a specific port
|
|
1007
|
-
- By WebSocket URL: Direct WebSocket connection
|
|
1008
|
-
|
|
1009
|
-
If the process doesn't have V8 Inspector active, it will be
|
|
1010
|
-
automatically activated via SIGUSR1 signal (no code changes needed).
|
|
1011
|
-
For Docker containers, uses docker exec to send SIGUSR1 inside the container.
|
|
1012
|
-
Requires: docker run -p 9229:9229 ... and Node started with --inspect or --inspect=0.0.0.0:9229.
|
|
1013
|
-
|
|
1014
|
-
When MCP runs in a container connecting to another container:
|
|
1015
|
-
- Mount /var/run/docker.sock in the MCP container and ensure docker CLI is available
|
|
1016
|
-
- Use host: host.docker.internal (or container name if on same Docker network) to reach the app's inspector
|
|
1017
|
-
|
|
1018
|
-
Once connected, you can use tracepoints, logpoints, exceptionpoints,
|
|
1019
|
-
and watch expressions - the same debugging tools available for browser.
|
|
1020
|
-
`}inputSchema(){return{pid:z70.number().int().positive().describe("Process ID to connect to").optional(),processName:z70.string().describe('Process name pattern to search for (e.g., "server.js", "api")').optional(),containerId:z70.string().describe("Docker container ID - process runs inside this container").optional(),containerName:z70.string().describe("Docker container name or pattern (e.g., my-node-app) - resolved via docker ps -f name=").optional(),host:z70.string().describe("Inspector host (default: 127.0.0.1); for containerized MCP use host.docker.internal or container name").optional(),port:z70.number().int().positive().describe("Inspector port (default: 9229); for Docker use host-mapped port").optional(),wsUrl:z70.string().describe("Direct WebSocket URL (e.g., ws://127.0.0.1:9229/abc-123)").optional()}}outputSchema(){return{connected:z70.boolean().describe("Whether connection was successful"),pid:z70.number().describe("Process ID"),command:z70.string().optional().describe("Process command line"),containerId:z70.string().optional().describe("Docker container ID when connected via container"),inspectorHost:z70.string().optional().describe("Inspector host"),inspectorPort:z70.number().optional().describe("Inspector port"),webSocketUrl:z70.string().optional().describe("WebSocket URL"),title:z70.string().describe("Target title")}}async handle(context,args){let result=await context.connect({pid:args.pid,processName:args.processName,containerId:args.containerId,containerName:args.containerName,host:args.host,port:args.port,wsUrl:args.wsUrl,activateIfNeeded:!0});return{connected:!0,pid:result.processInfo.pid,command:result.processInfo.command,containerId:result.processInfo.containerId,inspectorHost:result.processInfo.inspectorHost,inspectorPort:result.processInfo.inspectorPort,webSocketUrl:result.processInfo.webSocketUrl,title:result.target.title}}};import{z as z71}from"zod";var Disconnect=class{static{__name(this,"Disconnect")}name(){return"debug_disconnect"}description(){return"Disconnects from the currently connected Node.js process and cleans up debugging resources."}inputSchema(){return{}}outputSchema(){return{disconnected:z71.boolean().describe("Whether disconnection was successful")}}async handle(context,_args){return await context.disconnect(),{disconnected:!0}}};import{z as z72}from"zod";function _filterSnapshots(storeKey,probeId,fromSequence,limit,kind){let snapshots;if(probeId)snapshots=getSnapshotsByProbe(storeKey,probeId);else if(kind){let probes=listProbes(storeKey),probeIds=new Set(probes.filter(p=>p.kind===kind).map(p=>p.id)),allSnapshots=getSnapshots(storeKey);kind==="tracepoint"?snapshots=allSnapshots.filter(s=>probeIds.has(s.probeId)||s.probeId==="__exception__"):snapshots=allSnapshots.filter(s=>probeIds.has(s.probeId))}else snapshots=getSnapshots(storeKey);return fromSequence!==void 0&&(snapshots=snapshots.filter(s=>s.sequenceNumber>fromSequence)),limit!==void 0&&(snapshots=snapshots.slice(-limit)),snapshots}__name(_filterSnapshots,"_filterSnapshots");var GetTracepointSnapshots2=class{static{__name(this,"GetTracepointSnapshots")}name(){return"debug_get-tracepoint-snapshots"}description(){return"Retrieves snapshots captured by tracepoints on the Node.js process. Each snapshot contains call stack with local variables, async stack trace, watch expression results, and traceContext (traceId, spanId) when the process uses @opentelemetry/api."}inputSchema(){return{probeId:z72.string().describe("Filter by specific tracepoint ID").optional(),fromSequence:z72.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:z72.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:z72.array(z72.any()).describe("Captured snapshots"),count:z72.number().describe("Number of snapshots returned")}}async handle(context,args){let snapshots=_filterSnapshots(context.storeKey,args.probeId,args.fromSequence,args.limit,"tracepoint");return{snapshots,count:snapshots.length}}},GetLogpointSnapshots2=class{static{__name(this,"GetLogpointSnapshots")}name(){return"debug_get-logpoint-snapshots"}description(){return"Retrieves snapshots captured by logpoints on the Node.js process. Each snapshot contains the log expression result and traceContext (traceId, spanId) when the process uses @opentelemetry/api."}inputSchema(){return{probeId:z72.string().describe("Filter by specific logpoint ID").optional(),fromSequence:z72.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence").optional(),limit:z72.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:z72.array(z72.any()).describe("Captured snapshots"),count:z72.number().describe("Number of snapshots returned")}}async handle(context,args){let snapshots=_filterSnapshots(context.storeKey,args.probeId,args.fromSequence,args.limit,"logpoint");return{snapshots,count:snapshots.length}}},GetExceptionpointSnapshots2=class{static{__name(this,"GetExceptionpointSnapshots")}name(){return"debug_get-exceptionpoint-snapshots"}description(){return"Retrieves snapshots captured by exception breakpoints on the Node.js process. Snapshots include traceContext (traceId, spanId) when the process uses @opentelemetry/api."}inputSchema(){return{fromSequence:z72.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence").optional(),limit:z72.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:z72.array(z72.any()).describe("Captured snapshots"),count:z72.number().describe("Number of snapshots returned")}}async handle(context,args){let snapshots=getSnapshots(context.storeKey).filter(s=>s.probeId==="__exception__");return args.fromSequence!==void 0&&(snapshots=snapshots.filter(s=>s.sequenceNumber>args.fromSequence)),args.limit!==void 0&&(snapshots=snapshots.slice(-args.limit)),{snapshots,count:snapshots.length}}},ClearTracepointSnapshots2=class{static{__name(this,"ClearTracepointSnapshots")}name(){return"debug_clear-tracepoint-snapshots"}description(){return"Clears tracepoint snapshots. Optionally filter by specific tracepoint ID."}inputSchema(){return{probeId:z72.string().describe("Clear only snapshots for this tracepoint ID").optional()}}outputSchema(){return{cleared:z72.number().describe("Number of snapshots cleared")}}async handle(context,args){let{clearSnapshots,clearSnapshotsByProbe:clearSnapshotsByProbe2}=await import("./core-76RLSP3N.js");return{cleared:args.probeId?clearSnapshotsByProbe2(context.storeKey,args.probeId):clearSnapshots(context.storeKey)}}},ClearLogpointSnapshots2=class{static{__name(this,"ClearLogpointSnapshots")}name(){return"debug_clear-logpoint-snapshots"}description(){return"Clears logpoint snapshots. Optionally filter by specific logpoint ID."}inputSchema(){return{probeId:z72.string().describe("Clear only snapshots for this logpoint ID").optional()}}outputSchema(){return{cleared:z72.number().describe("Number of snapshots cleared")}}async handle(context,args){let{clearSnapshotsByProbe:clearSnapshotsByProbe2,clearSnapshots}=await import("./core-76RLSP3N.js");return{cleared:args.probeId?clearSnapshotsByProbe2(context.storeKey,args.probeId):clearSnapshots(context.storeKey)}}},ClearExceptionpointSnapshots2=class{static{__name(this,"ClearExceptionpointSnapshots")}name(){return"debug_clear-exceptionpoint-snapshots"}description(){return"Clears all exception snapshots."}inputSchema(){return{}}outputSchema(){return{cleared:z72.number().describe("Number of snapshots cleared")}}async handle(context,_args){let{clearSnapshotsByProbe:clearSnapshotsByProbe2}=await import("./core-76RLSP3N.js");return{cleared:clearSnapshotsByProbe2(context.storeKey,"__exception__")}}};import{z as z73}from"zod";var GetLogs=class{static{__name(this,"GetLogs")}name(){return"debug_get-logs"}description(){return"Retrieves console messages/logs from the Node.js process with filtering options."}inputSchema(){return{type:z73.enum(getEnumKeyTuples(ConsoleMessageLevelName)).transform(createEnumTransformer(ConsoleMessageLevelName)).describe(`Type of console messages to retrieve. When specified, messages with equal or higher levels are retrieved. Valid values: ${getEnumKeyTuples(ConsoleMessageLevelName).join(", ")}.`).optional(),search:z73.string().describe("Text to search for in console messages.").optional(),timestamp:z73.number().int().nonnegative().describe("Start time filter as Unix epoch timestamp in milliseconds. If provided, only messages recorded at or after this timestamp will be returned.").optional(),sequenceNumber:z73.number().int().nonnegative().describe("Sequence number for incremental retrieval. If provided, only messages with sequence number greater than this value will be returned.").optional(),limit:z73.object({count:z73.number().int().nonnegative().default(0).describe("Max number of messages. 0 = no limit."),from:z73.enum(["start","end"]).default("end").describe("Which side to keep when truncated.")}).describe("Maximum number of console messages to return.").optional()}}outputSchema(){return{messages:z73.array(z73.object({type:z73.string().describe("Type of the console message."),text:z73.string().describe("Text of the console message."),location:z73.object({url:z73.string().describe("URL of the resource."),lineNumber:z73.number().nonnegative().describe("0-based line number."),columnNumber:z73.number().nonnegative().describe("0-based column number.")}).describe("Location of the console message.").optional(),timestamp:z73.number().int().nonnegative().describe("Unix epoch timestamp (ms)."),sequenceNumber:z73.number().int().nonnegative().describe("Monotonic sequence number.")})).describe("Retrieved console messages.")}}async handle(context,args){let levelCodeThreshold=args.type?ConsoleMessageLevel[args.type]?.code:void 0,filtered=getConsoleMessages(context.storeKey).filter(msg=>!(levelCodeThreshold!==void 0&&msg.level.code<levelCodeThreshold||args.timestamp&&msg.timestamp<args.timestamp||args.sequenceNumber&&msg.sequenceNumber<=args.sequenceNumber||args.search&&!msg.text.includes(args.search)));return{messages:(args.limit?.count?args.limit.from==="start"?filtered.slice(0,args.limit.count):filtered.slice(-args.limit.count):filtered).map(msg=>({type:msg.type,text:msg.text,location:msg.location?{url:msg.location.url,lineNumber:msg.location.lineNumber,columnNumber:msg.location.columnNumber}:void 0,timestamp:msg.timestamp,sequenceNumber:msg.sequenceNumber}))}}};import{z as z74}from"zod";var RemoveTracepoint2=class{static{__name(this,"RemoveTracepoint")}name(){return"debug_remove-tracepoint"}description(){return"Removes a tracepoint by its ID."}inputSchema(){return{id:z74.string().describe("Tracepoint ID to remove")}}outputSchema(){return{removed:z74.boolean().describe("Whether the tracepoint was removed")}}async handle(context,args){return{removed:await removeProbe(context.storeKey,args.id)}}},ListTracepoints2=class{static{__name(this,"ListTracepoints")}name(){return"debug_list-tracepoints"}description(){return"Lists all active tracepoints on the Node.js process."}inputSchema(){return{}}outputSchema(){return{tracepoints:z74.array(z74.any()).describe("Active tracepoints")}}async handle(context,_args){return{tracepoints:listProbes(context.storeKey).filter(p=>p.kind==="tracepoint").map(p=>({id:p.id,urlPattern:p.urlPattern,lineNumber:p.lineNumber,columnNumber:p.columnNumber,condition:p.condition,hitCondition:p.hitCondition,hitCount:p.hitCount,resolvedLocations:p.resolvedLocations,enabled:p.enabled}))}}},ClearTracepoints2=class{static{__name(this,"ClearTracepoints")}name(){return"debug_clear-tracepoints"}description(){return"Removes all tracepoints from the Node.js process."}inputSchema(){return{}}outputSchema(){return{cleared:z74.number().describe("Number of tracepoints cleared")}}async handle(context,_args){let probes=listProbes(context.storeKey).filter(p=>p.kind==="tracepoint"),count=0;for(let p of probes)await removeProbe(context.storeKey,p.id)&&count++;return{cleared:count}}},RemoveLogpoint2=class{static{__name(this,"RemoveLogpoint")}name(){return"debug_remove-logpoint"}description(){return"Removes a logpoint by its ID."}inputSchema(){return{id:z74.string().describe("Logpoint ID to remove")}}outputSchema(){return{removed:z74.boolean().describe("Whether the logpoint was removed")}}async handle(context,args){return{removed:await removeProbe(context.storeKey,args.id)}}},ListLogpoints2=class{static{__name(this,"ListLogpoints")}name(){return"debug_list-logpoints"}description(){return"Lists all active logpoints on the Node.js process."}inputSchema(){return{}}outputSchema(){return{logpoints:z74.array(z74.any()).describe("Active logpoints")}}async handle(context,_args){return{logpoints:listProbes(context.storeKey).filter(p=>p.kind==="logpoint").map(p=>({id:p.id,urlPattern:p.urlPattern,lineNumber:p.lineNumber,logExpression:p.logExpression,condition:p.condition,hitCondition:p.hitCondition,hitCount:p.hitCount,resolvedLocations:p.resolvedLocations,enabled:p.enabled}))}}},ClearLogpoints2=class{static{__name(this,"ClearLogpoints")}name(){return"debug_clear-logpoints"}description(){return"Removes all logpoints from the Node.js process."}inputSchema(){return{}}outputSchema(){return{cleared:z74.number().describe("Number of logpoints cleared")}}async handle(context,_args){let probes=listProbes(context.storeKey).filter(p=>p.kind==="logpoint"),count=0;for(let p of probes)await removeProbe(context.storeKey,p.id)&&count++;return{cleared:count}}};import{z as z75}from"zod";var PutExceptionpoint2=class{static{__name(this,"PutExceptionpoint")}name(){return"debug_put-exceptionpoint"}description(){return`
|
|
1021
|
-
Sets the exception tracepoint state for a Node.js process:
|
|
1022
|
-
- "none": Don't capture on exceptions
|
|
1023
|
-
- "uncaught": Capture only on uncaught exceptions
|
|
1024
|
-
- "all": Capture on all exceptions (caught and uncaught)
|
|
1025
|
-
|
|
1026
|
-
When an exception occurs, a snapshot is captured with exception details.
|
|
1027
|
-
`}inputSchema(){return{state:z75.enum(["none","uncaught","all"]).describe("Exception tracepoint state")}}outputSchema(){return{state:z75.string().describe("New exception tracepoint state"),previousState:z75.string().describe("Previous state")}}async handle(context,args){let previousState=getExceptionBreakpoint(context.storeKey);return await setExceptionBreakpoint(context.storeKey,args.state),{state:args.state,previousState}}};import{z as z76}from"zod";var PutLogpoint2=class{static{__name(this,"PutLogpoint")}name(){return"debug_put-logpoint"}description(){return`
|
|
1028
|
-
Puts a logpoint on a Node.js backend process.
|
|
1029
|
-
When the logpoint is hit, the logExpression is evaluated and the result
|
|
1030
|
-
is captured in the snapshot's logResult field.
|
|
1031
|
-
|
|
1032
|
-
Logpoints are lightweight - they only capture the log expression result,
|
|
1033
|
-
NOT call stack or watch expressions. Use tracepoints for full debug context.
|
|
1034
|
-
|
|
1035
|
-
urlPattern matches script file paths (e.g., "server.js"). Auto-escaped.
|
|
1036
|
-
|
|
1037
|
-
logExpression examples:
|
|
1038
|
-
- Simple value: "user.name"
|
|
1039
|
-
- Template: "\`User: \${user.name}, Age: \${user.age}\`"
|
|
1040
|
-
- Object: "{ user, timestamp: Date.now() }"
|
|
1041
|
-
`}inputSchema(){return{urlPattern:z76.string().describe('Script file path pattern (e.g., "server.js"). Auto-escaped.'),lineNumber:z76.number().int().positive().describe("Line number (1-based)"),columnNumber:z76.number().int().nonnegative().describe("Column number (1-based). Optional.").optional(),logExpression:z76.string().describe("Expression to evaluate and log when hit"),condition:z76.string().describe("Conditional expression - logpoint only hits if this evaluates to true").optional(),hitCondition:z76.string().describe("Hit count condition").optional()}}outputSchema(){return{id:z76.string().describe("Logpoint ID"),urlPattern:z76.string().describe("URL pattern"),lineNumber:z76.number().describe("Line number"),logExpression:z76.string().describe("Log expression"),resolvedLocations:z76.number().describe("Number of locations resolved")}}async handle(context,args){let probe=await createProbe(context.storeKey,{kind:"logpoint",urlPattern:args.urlPattern,lineNumber:args.lineNumber,columnNumber:args.columnNumber,logExpression:args.logExpression,condition:args.condition,hitCondition:args.hitCondition});return{id:probe.id,urlPattern:probe.urlPattern,lineNumber:probe.lineNumber,logExpression:probe.logExpression||"",resolvedLocations:probe.resolvedLocations}}};import{z as z77}from"zod";var PutTracepoint2=class{static{__name(this,"PutTracepoint")}name(){return"debug_put-tracepoint"}description(){return`
|
|
1042
|
-
Puts a non-blocking tracepoint on a Node.js backend process.
|
|
1043
|
-
When hit, a snapshot of the call stack and local variables is captured
|
|
1044
|
-
automatically without pausing execution.
|
|
1045
|
-
|
|
1046
|
-
The urlPattern matches script file paths. Special characters are auto-escaped.
|
|
1047
|
-
Examples:
|
|
1048
|
-
- "server.js" matches scripts containing "server.js"
|
|
1049
|
-
- "routes/api.ts" matches scripts containing "routes/api.ts"
|
|
1050
|
-
|
|
1051
|
-
DO NOT escape characters yourself.
|
|
1052
|
-
|
|
1053
|
-
Returns resolvedLocations: number of scripts where the tracepoint was set.
|
|
1054
|
-
If 0, the pattern didn't match any loaded scripts.
|
|
1055
|
-
`}inputSchema(){return{urlPattern:z77.string().describe('Script file path pattern (e.g., "server.js"). Auto-escaped.'),lineNumber:z77.number().int().positive().describe("Line number (1-based)"),columnNumber:z77.number().int().nonnegative().describe("Column number (1-based). Optional.").optional(),condition:z77.string().describe("Conditional expression - only triggers if this evaluates to true").optional(),hitCondition:z77.string().describe('Hit count condition, e.g., "== 5", ">= 10", "% 10 == 0"').optional()}}outputSchema(){return{id:z77.string().describe("Tracepoint ID"),urlPattern:z77.string().describe("URL pattern"),lineNumber:z77.number().describe("Line number"),columnNumber:z77.number().optional().describe("Column number"),condition:z77.string().optional().describe("Condition expression"),hitCondition:z77.string().optional().describe("Hit count condition"),resolvedLocations:z77.number().describe("Number of locations where tracepoint was resolved")}}async handle(context,args){let probe=await createProbe(context.storeKey,{kind:"tracepoint",urlPattern:args.urlPattern,lineNumber:args.lineNumber,columnNumber:args.columnNumber,condition:args.condition,hitCondition:args.hitCondition});return{id:probe.id,urlPattern:probe.urlPattern,lineNumber:probe.lineNumber,columnNumber:probe.columnNumber,condition:probe.condition,hitCondition:probe.hitCondition,resolvedLocations:probe.resolvedLocations}}};import{z as z78}from"zod";var ResolveSourceLocation2=class{static{__name(this,"ResolveSourceLocation")}name(){return"debug_resolve-source-location"}description(){return`
|
|
1056
|
-
Resolves a generated/bundled code location to its original source via source maps.
|
|
1057
|
-
Useful for translating minified stack traces or bundle line numbers to original TypeScript/JavaScript source.
|
|
1058
|
-
|
|
1059
|
-
Requires an active Node.js debug connection (call debug_connect first).
|
|
1060
|
-
Input: generated script URL (e.g. file path), line, column (1-based).
|
|
1061
|
-
Output: original source path, line, column when a source map is available.
|
|
1062
|
-
`}inputSchema(){return{url:z78.string().describe("Generated script URL (e.g. file:///path/to/dist/app.js)"),line:z78.number().int().positive().describe("Line number in generated code (1-based)"),column:z78.number().int().nonnegative().describe("Column number in generated code (1-based, default 1)").optional()}}outputSchema(){return{resolved:z78.boolean().describe("Whether the location was resolved to original source"),source:z78.string().optional().describe("Original source file path"),line:z78.number().optional().describe("Line number in original source (1-based)"),column:z78.number().optional().describe("Column number in original source (1-based)"),name:z78.string().optional().describe("Original identifier name if available")}}async handle(context,args){let resolved=await resolveSourceLocation(context.storeKey,args.url,args.line,args.column??1);return resolved?{resolved:!0,source:resolved.source,line:resolved.line,column:resolved.column,name:resolved.name}:{resolved:!1}}};import{z as z79}from"zod";var Status2=class{static{__name(this,"Status")}name(){return"debug_status"}description(){return`
|
|
1063
|
-
Returns the current Node.js debugging status including:
|
|
1064
|
-
- Whether connected and debugging is enabled
|
|
1065
|
-
- Source map status
|
|
1066
|
-
- Exceptionpoint state
|
|
1067
|
-
- Count of tracepoints, logpoints, watches
|
|
1068
|
-
- Snapshot statistics
|
|
1069
|
-
`}inputSchema(){return{}}outputSchema(){return{connected:z79.boolean().describe("Whether connected to a Node.js process"),enabled:z79.boolean().describe("Whether debugging is enabled"),pid:z79.number().optional().describe("Connected process PID"),hasSourceMaps:z79.boolean().describe("Whether source maps are loaded"),exceptionBreakpoint:z79.string().describe("Exceptionpoint state"),tracepointCount:z79.number().describe("Number of tracepoints"),logpointCount:z79.number().describe("Number of logpoints"),watchExpressionCount:z79.number().describe("Number of watch expressions"),snapshotStats:z79.any().nullable().describe("Snapshot statistics")}}async handle(context,_args){if(!context.isConnected)return{connected:!1,enabled:!1,hasSourceMaps:!1,exceptionBreakpoint:"none",tracepointCount:0,logpointCount:0,watchExpressionCount:0,snapshotStats:null};let key=context.storeKey,enabled=isDebuggingEnabled(key),probes=listProbes(key);return{connected:!0,enabled,pid:context.processInfo?.pid,hasSourceMaps:hasSourceMaps(key),exceptionBreakpoint:getExceptionBreakpoint(key),tracepointCount:probes.filter(p=>p.kind==="tracepoint").length,logpointCount:probes.filter(p=>p.kind==="logpoint").length,watchExpressionCount:listWatchExpressions(key).length,snapshotStats:enabled?getSnapshotStats(key):null}}};import{z as z80}from"zod";var AddWatch2=class{static{__name(this,"AddWatch")}name(){return"debug_add-watch"}description(){return`
|
|
1070
|
-
Adds a watch expression to be evaluated at every tracepoint hit on the Node.js process.
|
|
1071
|
-
Watch expression results are included in the snapshot's watchResults field.
|
|
1072
|
-
|
|
1073
|
-
Examples: "user.name", "this.state", "items.length", "JSON.stringify(config)"
|
|
1074
|
-
`}inputSchema(){return{expression:z80.string().describe("JavaScript expression to watch")}}outputSchema(){return{id:z80.string().describe("Watch expression ID"),expression:z80.string().describe("The expression")}}async handle(context,args){let watch=addWatchExpression(context.storeKey,args.expression);return{id:watch.id,expression:watch.expression}}},RemoveWatch2=class{static{__name(this,"RemoveWatch")}name(){return"debug_remove-watch"}description(){return"Removes a watch expression by its ID."}inputSchema(){return{id:z80.string().describe("Watch expression ID to remove")}}outputSchema(){return{removed:z80.boolean().describe("Whether the watch was removed")}}async handle(context,args){return{removed:removeWatchExpression(context.storeKey,args.id)}}},ListWatches2=class{static{__name(this,"ListWatches")}name(){return"debug_list-watches"}description(){return"Lists all active watch expressions."}inputSchema(){return{}}outputSchema(){return{watches:z80.array(z80.any()).describe("Active watch expressions")}}async handle(context,_args){return{watches:listWatchExpressions(context.storeKey)}}},ClearWatches2=class{static{__name(this,"ClearWatches")}name(){return"debug_clear-watches"}description(){return"Removes all watch expressions."}inputSchema(){return{}}outputSchema(){return{cleared:z80.number().describe("Number of watches cleared")}}async handle(context,_args){return{cleared:clearWatchExpressions(context.storeKey)}}};var tools13=[new Connect,new Disconnect,new Status2,new PutTracepoint2,new RemoveTracepoint2,new ListTracepoints2,new ClearTracepoints2,new PutLogpoint2,new RemoveLogpoint2,new ListLogpoints2,new ClearLogpoints2,new PutExceptionpoint2,new GetTracepointSnapshots2,new ClearTracepointSnapshots2,new GetLogpointSnapshots2,new ClearLogpointSnapshots2,new GetExceptionpointSnapshots2,new ClearExceptionpointSnapshots2,new GetLogs,new ResolveSourceLocation2,new AddWatch2,new RemoveWatch2,new ListWatches2,new ClearWatches2];import{z as z81}from"zod";var RunJsInNode=class{static{__name(this,"RunJsInNode")}name(){return"run_js-in-node"}description(){return`
|
|
1075
|
-
Runs custom JavaScript INSIDE the connected Node.js process using CDP Runtime.evaluate.
|
|
1076
|
-
|
|
1077
|
-
This code executes in the NODE PROCESS CONTEXT (real Node.js environment):
|
|
1078
|
-
- Has access to process, require, global, and all loaded modules
|
|
1079
|
-
- Can read/modify process state
|
|
1080
|
-
- Runs with full Node.js APIs (fs, http, etc.)
|
|
1081
|
-
|
|
1082
|
-
Typical use cases:
|
|
1083
|
-
- Inspect process state: process.memoryUsage(), process.uptime()
|
|
1084
|
-
- Call loaded modules: require('os').loadavg()
|
|
1085
|
-
- Read globals or cached data
|
|
1086
|
-
- One-off diagnostic commands
|
|
1087
|
-
|
|
1088
|
-
Notes:
|
|
1089
|
-
- Requires debug_connect first - must be connected to a Node.js process
|
|
1090
|
-
- Execution blocks the Node event loop until the script completes
|
|
1091
|
-
- Long-running scripts will block the process; use short expressions
|
|
1092
|
-
- Return value must be serializable (JSON-compatible)
|
|
1093
|
-
`}inputSchema(){return{script:z81.string().describe("JavaScript code to execute in the Node process."),timeoutMs:z81.number().int().min(100).max(3e4).describe("Max evaluation time in milliseconds (default: 5000, max: 30000).").optional()}}outputSchema(){return{result:z81.any().describe("The result of the evaluation. Can be primitives, arrays, or objects. Must be serializable (JSON-compatible).")}}async handle(context,args){return{result:await evaluateInNode(context.storeKey,args.script,args.timeoutMs??5e3)}}};var tools14=[new RunJsInNode];import{EventEmitter}from"node:events";import{WebSocket}from"ws";var NodeCDPSession=class extends EventEmitter{static{__name(this,"NodeCDPSession")}ws=null;reqId=0;pending=new Map;connected=!1;wsUrl;constructor(wsUrl){super(),this.wsUrl=wsUrl}async connect(){if(!this.connected)return new Promise((resolve,reject)=>{this.ws=new WebSocket(this.wsUrl);let timeout=setTimeout(()=>{reject(new Error(`Connection timeout to ${this.wsUrl}`)),this.ws?.close()},1e4);this.ws.on("open",()=>{clearTimeout(timeout),this.connected=!0,resolve()}),this.ws.on("error",err=>{clearTimeout(timeout),this.connected||reject(err)}),this.ws.on("close",()=>{this.connected=!1;for(let[id,handler]of this.pending)handler.reject(new Error("CDP session closed"));this.pending.clear()}),this.ws.on("message",data=>{try{let msg=JSON.parse(data.toString());this._handleMessage(msg)}catch{}})})}async send(method,params){if(!this.ws||!this.connected)throw new Error("CDP session is not connected");let id=++this.reqId;return new Promise((resolve,reject)=>{this.pending.set(id,{resolve,reject});let message=JSON.stringify({id,method,params:params||{}});this.ws.send(message,err=>{err&&(this.pending.delete(id),reject(err))}),setTimeout(()=>{this.pending.has(id)&&(this.pending.delete(id),reject(new Error(`CDP command timeout: ${method}`)))},3e4)})}async detach(){if(this.ws){this.connected=!1,this.ws.close(),this.ws=null;for(let[,handler]of this.pending)handler.reject(new Error("CDP session detached"));this.pending.clear()}}isConnected(){return this.connected}_handleMessage(msg){if(msg.id!==void 0){let handler=this.pending.get(msg.id);handler&&(this.pending.delete(msg.id),msg.error?handler.reject(new Error(`CDP error: ${msg.error.message||JSON.stringify(msg.error)}`)):handler.resolve(msg.result||{}))}else msg.method&&this.emit(msg.method,msg.params)}};async function createNodeCDPSession(wsUrl){let session=new NodeCDPSession(wsUrl);return await session.connect(),session}__name(createNodeCDPSession,"createNodeCDPSession");import{execSync}from"node:child_process";import*as http from"node:http";var DEFAULT_HOST="127.0.0.1",DEFAULT_PORT=9229,DEFAULT_TIMEOUT_MS7=1e4,ACTIVATION_POLL_INTERVAL_MS=200,MAX_INSPECTOR_SCAN_PORTS=20;async function discoverInspectorTargets(host=DEFAULT_HOST,port=DEFAULT_PORT,timeoutMs=5e3){return new Promise((resolve,reject)=>{let timeout=setTimeout(()=>{reject(new Error(`Inspector discovery timeout on ${host}:${port}`))},timeoutMs),req=http.get(`http://${host}:${port}/json/list`,res=>{let data="";res.on("data",chunk=>{data+=chunk}),res.on("end",()=>{clearTimeout(timeout);try{let targets=JSON.parse(data);resolve(targets)}catch{reject(new Error(`Invalid response from inspector at ${host}:${port}`))}})});req.on("error",err=>{clearTimeout(timeout),reject(new Error(`Cannot reach inspector at ${host}:${port}: ${err.message}`))}),req.end()})}__name(discoverInspectorTargets,"discoverInspectorTargets");async function scanForInspector(host=DEFAULT_HOST,startPort=DEFAULT_PORT,maxPorts=MAX_INSPECTOR_SCAN_PORTS){for(let port=startPort;port<startPort+maxPorts;port++)try{let targets=await discoverInspectorTargets(host,port,1e3);if(targets.length>0)return{port,targets}}catch{}return null}__name(scanForInspector,"scanForInspector");function findNodeProcesses(namePattern){try{let platform=process.platform,output;platform==="win32"?output=execSync(`wmic process where "name like '%node%'" get ProcessId,CommandLine /format:csv`,{encoding:"utf-8",timeout:5e3}):output=execSync('ps aux | grep -E "[n]ode|[t]s-node|[n]px"',{encoding:"utf-8",timeout:5e3});let processes=[];for(let line of output.split(`
|
|
1094
|
-
`)){let trimmed=line.trim();if(trimmed)if(platform==="win32"){let parts=trimmed.split(",");if(parts.length>=3){let pid=parseInt(parts[parts.length-1],10),command=parts.slice(1,-1).join(",");!isNaN(pid)&&pid>0&&processes.push({pid,command})}}else{let parts=trimmed.split(/\s+/);if(parts.length>=11){let pid=parseInt(parts[1],10),command=parts.slice(10).join(" ");!isNaN(pid)&&pid>0&&processes.push({pid,command})}}}if(namePattern){let regex=new RegExp(namePattern,"i");return processes.filter(p=>regex.test(p.command))}return processes}catch{return[]}}__name(findNodeProcesses,"findNodeProcesses");async function activateInspector(pid,host=DEFAULT_HOST,timeoutMs=DEFAULT_TIMEOUT_MS7){if(process.platform==="win32")throw new Error("SIGUSR1 activation is not supported on Windows. Start the Node.js process with --inspect flag or NODE_OPTIONS=--inspect instead.");try{process.kill(pid,0)}catch{throw new Error(`Process ${pid} does not exist or is not accessible`)}debug(`Sending SIGUSR1 to process ${pid} to activate V8 Inspector...`),process.kill(pid,"SIGUSR1");let startTime=Date.now();for(;Date.now()-startTime<timeoutMs;){let result=await scanForInspector(host,DEFAULT_PORT,10);if(result)return debug(`Inspector activated on port ${result.port} for process ${pid}`),result;await new Promise(resolve=>setTimeout(resolve,ACTIVATION_POLL_INTERVAL_MS))}throw new Error(`Timeout waiting for inspector to activate on process ${pid}`)}__name(activateInspector,"activateInspector");function resolveContainerId(containerName){try{let ids=execSync(`docker ps -q -f name=${containerName}`,{encoding:"utf-8",timeout:5e3}).trim().split(`
|
|
1095
|
-
`).filter(Boolean);return ids.length===0?null:(ids.length>1&&debug(`Multiple containers match "${containerName}", using first: ${ids[0]}`),ids[0])}catch(err){if(/Cannot connect to the Docker daemon|docker: command not found/i.test(err.message??""))throw new Error(`${err.message} When MCP runs in a container, mount /var/run/docker.sock and ensure the docker CLI is available.`);return null}}__name(resolveContainerId,"resolveContainerId");async function activateInspectorInContainer(containerId,host=DEFAULT_HOST,port=DEFAULT_PORT,timeoutMs=DEFAULT_TIMEOUT_MS7){if(process.platform==="win32")throw new Error("Docker container activation may have limitations on Windows. Ensure the container has port 9229 exposed and Node is started with --inspect.");let nodePid;try{let psOutput=execSync(`docker exec ${containerId} sh -c "ps aux 2>/dev/null | grep '[n]ode' | head -1"`,{encoding:"utf-8",timeout:5e3}).trim();if(!psOutput)throw new Error(`No Node.js process found inside container ${containerId}`);if(nodePid=psOutput.split(/\s+/).filter(Boolean)[1]||"",!nodePid||!/^\d+$/.test(nodePid))throw new Error(`Could not parse Node PID from container ${containerId}`)}catch(err){if(err.message?.includes("No Node.js process"))throw err;let dockerHint=/Cannot connect to the Docker daemon|docker: command not found/i.test(err.message??"")?" When MCP runs in a container, mount /var/run/docker.sock and ensure the docker CLI is available.":"";throw new Error(`Cannot find Node process in container ${containerId}: ${err.message}. Ensure Docker is running and the container has a Node.js process.${dockerHint}`)}debug(`Sending SIGUSR1 to Node process ${nodePid} inside container ${containerId}...`);try{execSync(`docker exec ${containerId} kill -USR1 ${nodePid}`,{encoding:"utf-8",timeout:5e3})}catch(err){let dockerHint=/Cannot connect to the Docker daemon|docker: command not found/i.test(err.message??"")?" When MCP runs in a container, mount /var/run/docker.sock and ensure the docker CLI is available.":"";throw new Error(`Failed to send SIGUSR1 to container ${containerId}: ${err.message}${dockerHint}`)}let startTime=Date.now();for(;Date.now()-startTime<timeoutMs;){try{let targets=await discoverInspectorTargets(host,port,2e3);if(targets.length>0)return debug(`Inspector active at ${host}:${port} for container ${containerId}`),{port,targets}}catch{}await new Promise(resolve=>setTimeout(resolve,ACTIVATION_POLL_INTERVAL_MS))}throw new Error(`Timeout waiting for inspector from container ${containerId}. Ensure the container exposes port 9229 (e.g. docker run -p 9229:9229 ...) and Node is started with --inspect or --inspect=0.0.0.0:9229.`)}__name(activateInspectorInContainer,"activateInspectorInContainer");async function connectToNodeProcess(options){let host=options.host||DEFAULT_HOST,timeoutMs=options.timeoutMs||DEFAULT_TIMEOUT_MS7,activateIfNeeded=options.activateIfNeeded!==!1;if(options.wsUrl)return debug(`Connecting to Node.js inspector via WebSocket: ${options.wsUrl}`),{session:await createNodeCDPSession(options.wsUrl),processInfo:{pid:0,inspectorActive:!0,webSocketUrl:options.wsUrl},target:{id:"direct",type:"node",title:"Direct WebSocket connection",url:"",webSocketDebuggerUrl:options.wsUrl}};let containerId=options.containerId??null;if(!containerId&&options.containerName&&(containerId=resolveContainerId(options.containerName),!containerId))throw new Error(`No running container found matching name: ${options.containerName}`);if(containerId){let port2=options.port||DEFAULT_PORT,targets2=[];try{targets2=await discoverInspectorTargets(host,port2,3e3)}catch{}if(targets2.length===0&&activateIfNeeded&&(debug(`Inspector not active. Activating via SIGUSR1 in container ${containerId}...`),targets2=(await activateInspectorInContainer(containerId,host,port2,timeoutMs)).targets),targets2.length===0)throw new Error(`Cannot connect to Node.js in container ${containerId}. Inspector not active. Ensure port 9229 is exposed (e.g. -p 9229:9229) and use activateIfNeeded or start Node with --inspect.`);let target=targets2[0],wsUrl=target.webSocketDebuggerUrl;return host!==DEFAULT_HOST&&(wsUrl=wsUrl.replace(/ws:\/\/[^:]+:/,`ws://${host}:`)),{session:await createNodeCDPSession(wsUrl),processInfo:{pid:0,inspectorActive:!0,inspectorHost:host,inspectorPort:port2,webSocketUrl:wsUrl,containerId},target}}let pid=options.pid,processCommand;if(!pid&&options.processName){let processes=findNodeProcesses(options.processName);if(processes.length===0)throw new Error(`No Node.js process found matching: ${options.processName}`);if(processes.length>1){let procList=processes.map(p=>` PID ${p.pid}: ${p.command}`).join(`
|
|
1096
|
-
`);throw new Error(`Multiple Node.js processes match "${options.processName}":
|
|
1097
|
-
${procList}
|
|
1098
|
-
Please specify a PID directly.`)}pid=processes[0].pid,processCommand=processes[0].command,debug(`Found Node.js process: PID ${pid} - ${processCommand}`)}let port=options.port||DEFAULT_PORT,targets=[];try{targets=await discoverInspectorTargets(host,port,3e3)}catch{}if(targets.length>0){let target=targets[0];debug(`Inspector already active at ${host}:${port}, connecting...`);let wsUrl=target.webSocketDebuggerUrl;return host!==DEFAULT_HOST&&(wsUrl=wsUrl.replace(/ws:\/\/[^:]+:/,`ws://${host}:`)),{session:await createNodeCDPSession(wsUrl),processInfo:{pid:pid||0,command:processCommand,inspectorActive:!0,inspectorHost:host,inspectorPort:port,webSocketUrl:wsUrl},target}}if(pid&&activateIfNeeded){debug(`Inspector not active on ${host}:${port}. Activating via SIGUSR1 on PID ${pid}...`);let{port:activePort,targets:activeTargets}=await activateInspector(pid,host,timeoutMs);if(activeTargets.length===0)throw new Error(`Inspector activated on port ${activePort} but no targets found`);let target=activeTargets[0],wsUrl=target.webSocketDebuggerUrl;return host!==DEFAULT_HOST&&(wsUrl=wsUrl.replace(/ws:\/\/[^:]+:/,`ws://${host}:`)),{session:await createNodeCDPSession(wsUrl),processInfo:{pid,command:processCommand,inspectorActive:!0,inspectorHost:host,inspectorPort:activePort,webSocketUrl:wsUrl},target}}throw pid?new Error(`Cannot connect to process ${pid}. Inspector is not active and activation failed. Try starting the process with NODE_OPTIONS=--inspect or --inspect flag.`):new Error("No target specified. Provide a PID, process name, port, or WebSocket URL. If the process is not started with --inspect, provide a PID to activate via SIGUSR1.")}__name(connectToNodeProcess,"connectToNodeProcess");var NodeToolSessionContext=class{static{__name(this,"NodeToolSessionContext")}_sessionId;_connection=null;_storeKey=null;closed=!1;constructor(sessionId){this._sessionId=sessionId}sessionId(){return this._sessionId}async connect(options){if(this._connection)throw new Error("Already connected to a Node.js process. Disconnect first.");debug(`Connecting to Node.js process with options: ${JSON.stringify(options)}`);let result=await connectToNodeProcess(options);return this._connection=result,this._storeKey=getStoreKey(result.processInfo.pid,result.processInfo.webSocketUrl),await enableDebugging(this._storeKey,result.session,{pid:result.processInfo.pid,command:result.processInfo.command}),debug(`Connected to Node.js process: PID=${result.processInfo.pid}, store=${this._storeKey}`),{processInfo:result.processInfo,target:result.target}}async disconnect(){!this._connection||!this._storeKey||(debug(`Disconnecting from Node.js process: ${this._storeKey}`),await detachDebugging(this._storeKey),await this._connection.session.detach(),this._connection=null,this._storeKey=null)}get storeKey(){if(!this._storeKey)throw new Error("Not connected to any Node.js process. Call connect first.");return this._storeKey}get isConnected(){return this._connection!==null&&this._connection.session.isConnected()}get processInfo(){return this._connection?.processInfo??null}async close(){return this.closed?!1:(await this.disconnect(),this.closed=!0,!0)}};var NodeToolExecutor=class{static{__name(this,"NodeToolExecutor")}sessionIdProvider;sessionContext;constructor(sessionIdProvider){this.sessionIdProvider=sessionIdProvider}_sessionContext(){if(!this.sessionContext){let sessionId=this.sessionIdProvider();this.sessionContext=new NodeToolSessionContext(sessionId),debug(`Created Node.js session context for session ${sessionId}`)}return this.sessionContext}async executeTool(tool,args){debug(`Executing Node.js tool ${tool.name()} with input: ${toJson(args)}`);try{let context=this._sessionContext(),result=await tool.handle(context,args);return debug(`Executed Node.js tool ${tool.name()} successfully`),result}catch(err){throw debug(`Error executing Node.js tool ${tool.name()}: ${err}`),err}}};var tools15=[...tools13,...tools14];function createToolExecutor2(sessionIdProvider){return new NodeToolExecutor(sessionIdProvider)}__name(createToolExecutor2,"createToolExecutor");var NodeCliProvider=class{static{__name(this,"NodeCliProvider")}platform="node";cliName="node-devtools-cli";tools=tools15;sessionDescription="Manage Node.js debugging sessions";cliExamples=["node-devtools-cli interactive","node-devtools-cli connect --pid 12345"];bashCompletionOptions="";bashCompletionCommands="daemon session tools config completion interactive connect disconnect status tracepoint logpoint exceptionpoint watch";zshCompletionOptions="";zshCompletionCommands=[{name:"daemon",description:"Manage the daemon server"},{name:"session",description:"Manage Node.js debug sessions"},{name:"tools",description:"List and inspect available tools"},{name:"config",description:"Show current configuration"},{name:"completion",description:"Generate shell completion scripts"},{name:"interactive",description:"Start interactive REPL mode"},{name:"connect",description:"Connect to a Node.js process"},{name:"disconnect",description:"Disconnect from current process"},{name:"status",description:"Show connection status"},{name:"tracepoint",description:"Tracepoint commands"},{name:"logpoint",description:"Logpoint commands"},{name:"exceptionpoint",description:"Exceptionpoint commands"},{name:"watch",description:"Watch expression commands"}];replPrompt="node> ";cliDescription="Node.js DevTools MCP CLI";packageName="browser-devtools-mcp";buildEnv(_opts){return{...process.env}}addOptions(cmd){return cmd}getConfig(){return{consoleMessagesBufferSize:NODE_CONSOLE_MESSAGES_BUFFER_SIZE}}formatConfig(configValues){return[" Node.js:",` Console Messages Buffer: ${configValues.consoleMessagesBufferSize??NODE_CONSOLE_MESSAGES_BUFFER_SIZE}`].join(`
|
|
1099
|
-
`)}formatConfigForRepl(_opts){return` console-messages-buffer = ${NODE_CONSOLE_MESSAGES_BUFFER_SIZE}`}},cliProvider2=new NodeCliProvider;var SERVER_INSTRUCTIONS2=`
|
|
1100
|
-
Node.js Backend Debugging Platform
|
|
1101
|
-
|
|
1102
|
-
This platform provides non-blocking V8 debugging for Node.js backend processes.
|
|
1103
|
-
It connects to running Node.js processes via the V8 Inspector Protocol (Chrome DevTools Protocol over WebSocket)
|
|
1104
|
-
and provides the same debugging capabilities as browser debugging.
|
|
1105
|
-
|
|
1106
|
-
**Connection Methods:**
|
|
1107
|
-
- By process ID (PID): Automatically activates the V8 Inspector via SIGUSR1 signal if not already active
|
|
1108
|
-
- By process name: Finds Node.js processes by name and connects
|
|
1109
|
-
- By port: Connects to an already-active inspector on a specific port
|
|
1110
|
-
- By WebSocket URL: Direct connection to a known inspector endpoint
|
|
1111
|
-
|
|
1112
|
-
**Debugging Capabilities:**
|
|
1113
|
-
- Tracepoints: Set non-blocking breakpoints that capture call stack, local variables, and watch expressions
|
|
1114
|
-
- Logpoints: Lightweight expression evaluation at specific code locations
|
|
1115
|
-
- Exceptionpoints: Automatically capture snapshots when exceptions occur (uncaught or all)
|
|
1116
|
-
- Watch expressions: Evaluate custom expressions at every tracepoint hit
|
|
1117
|
-
- Source map support: Resolves bundled/compiled code to original source locations
|
|
1118
|
-
- run_js-in-node: Execute JavaScript in the connected process (e.g., process.memoryUsage(), require())
|
|
1119
|
-
|
|
1120
|
-
**Key Features:**
|
|
1121
|
-
- Zero code changes required - connects to already-running processes
|
|
1122
|
-
- Non-blocking - execution resumes immediately after snapshot capture
|
|
1123
|
-
- Same V8 protocol as browser debugging - consistent experience across platforms
|
|
1124
|
-
|
|
1125
|
-
**Usage Flow:**
|
|
1126
|
-
1. Connect to a Node.js process using debug_connect (by PID, name, port, or WebSocket URL)
|
|
1127
|
-
2. Set tracepoints/logpoints at code locations of interest
|
|
1128
|
-
3. Trigger the code paths (e.g., make API requests)
|
|
1129
|
-
4. Retrieve captured snapshots with call stack, variables, and watch results
|
|
1130
|
-
5. Disconnect when done
|
|
1131
|
-
`,NODE_DEBUGGING_POLICY=`
|
|
1132
|
-
Node.js Debugging Best Practices:
|
|
1133
|
-
- Always connect before attempting to set probes
|
|
1134
|
-
- Use logpoints for lightweight monitoring, tracepoints for full context
|
|
1135
|
-
- Set watch expressions before tracepoints to capture specific values
|
|
1136
|
-
- Use source maps when debugging TypeScript or compiled code
|
|
1137
|
-
- Disconnect cleanly when done to avoid leaving inspector sessions open
|
|
1138
|
-
- Use exception breakpoints to catch unhandled errors
|
|
1139
|
-
`;var nodePlatformInfo={serverInfo:{instructions:SERVER_INSTRUCTIONS2,policies:[NODE_DEBUGGING_POLICY]},toolsInfo:{tools:tools15,createToolExecutor:createToolExecutor2},cliInfo:{cliProvider:cliProvider2}};function _resolvePlatformInfo(){return PLATFORM==="node"?nodePlatformInfo:platformInfo}__name(_resolvePlatformInfo,"_resolvePlatformInfo");var platformInfo2=_resolvePlatformInfo();export{platformInfo2 as platformInfo};
|