browser-devtools-mcp 0.2.8 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1139 +0,0 @@
1
- import{$ as ai,A as Qs,B as Zs,C as ei,D as ti,E as ni,L as J,N as ss,P as hn,Q as oi,R as ri,S as dt,T as Qt,U as is,V as Zt,Y as si,Z as ii,a as s,aa as li,c as Vs,ca as ui,ea as ci,fa as Bn,g as Gt,ga as An,h as Kt,ha as fn,i as Xt,ia as bt,j as Yt,k as Pn,ka as Ln,l as kn,la as mi,m as dn,n as bn,o as Rn,oa as pi,p as Gs,pa as di,q as Ks,qa as bi,r as Xs,ra as gi,s as rs,sa as Fn,t as Ys,ta as hi,u as gn,v as _n,va as fi,w as Js,x as Jt,y as Mn,ya as yi,z as Dn}from"./core-IV5QBQ2N.js";import{z as wi}from"zod";var Un=class{static{s(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:wi.string().describe("CSS selector for element to take snapshot.").optional()}}outputSchema(){return{output:wi.string().describe("Includes the page URL, title, and a YAML-formatted accessibility tree.")}}async handle(e,t){let n=await e.page.locator(t.selector||"body").ariaSnapshot();return{output:`
11
- - Page URL: ${e.page.url()}
12
- - Page Title: ${await e.page.title()}
13
- - Page/Component Snapshot:
14
- \`\`\`yaml
15
- ${n}
16
- \`\`\`
17
- `.trim()}}};import{z as S}from"zod";var Ti=!0,Si=!0,xi=!1,vi=!1,Ii=!1,Ci=80,Ei=["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"],Al=new Set(["button","link","textbox","checkbox","radio","combobox","switch","tab","menuitem","dialog","heading","listbox","listitem","option"]),Ll=12,Oi=2e3;function Fl(o){let e={};if(!o)return e;for(let t=0;t<o.length;t+=2){let n=String(o[t]),r=String(o[t+1]??"");e[n]=r}return e}s(Fl,"attrsToObj");var Hn=class{static{s(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:S.array(S.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:S.boolean().describe("Whether to include computed CSS styles for each node. Styles are extracted via runtime getComputedStyle().").optional().default(Ti),includeRuntimeVisual:S.boolean().describe("Whether to compute runtime visual information (bounding box, visibility, viewport).").optional().default(Si),checkOcclusion:S.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(xi),onlyVisible:S.boolean().describe("If true, only visually visible nodes are returned.").optional().default(vi),onlyInViewport:S.boolean().describe("If true, only nodes intersecting the viewport are returned.").optional().default(Ii),textPreviewMaxLength:S.number().int().positive().describe("Maximum length of the text preview extracted from each element.").optional().default(Ci),styleProperties:S.array(S.string()).describe("List of CSS computed style properties to extract.").optional().default([...Ei])}}outputSchema(){return{url:S.string().describe("The current page URL at the time the AX snapshot was captured."),title:S.string().describe("The document title of the page at the time of the snapshot."),axNodeCount:S.number().int().nonnegative().describe("Total number of nodes returned by Chromium Accessibility.getFullAXTree before filtering."),candidateCount:S.number().int().nonnegative().describe("Number of DOM-backed AX nodes that passed role filtering before enrichment."),enrichedCount:S.number().int().nonnegative().describe("Number of nodes included in the final enriched snapshot output."),truncatedBySafetyCap:S.boolean().describe("Indicates whether the result set was truncated by an internal safety cap to prevent excessive output size."),nodes:S.array(S.object({axNodeId:S.string().describe("Unique identifier of the accessibility node within the AX tree."),parentAxNodeId:S.string().nullable().describe("Parent AX node id in the full AX tree. Null if this node is a root."),childAxNodeIds:S.array(S.string()).describe("Child AX node ids in the full AX tree (may include nodes not present in the filtered output)."),role:S.string().nullable().describe("ARIA role of the accessibility node (e.g. button, link, textbox)."),name:S.string().nullable().describe("Accessible name computed by the browser accessibility engine."),ignored:S.boolean().nullable().describe("Whether the accessibility node is marked as ignored."),backendDOMNodeId:S.number().int().describe("Chromium backend DOM node identifier used to map AX nodes to DOM elements."),domNodeId:S.number().int().nullable().describe("Resolved DOM nodeId from CDP if available; may be null because nodeId is not guaranteed to be stable/resolved."),frameId:S.string().nullable().describe("Frame identifier if the node belongs to an iframe or subframe."),localName:S.string().nullable().describe("Lowercased DOM tag name of the mapped element (e.g. div, button, input)."),id:S.string().nullable().describe("DOM id attribute of the mapped element."),className:S.string().nullable().describe("DOM class attribute of the mapped element."),selectorHint:S.string().nullable().describe("Best-effort selector hint for targeting this element (prefers data-testid/data-selector/id)."),textPreview:S.string().nullable().describe("Short preview of rendered text content or aria-label, truncated to the configured maximum length."),value:S.any().nullable().describe("Raw AX value payload associated with the node, if present."),description:S.any().nullable().describe("Raw AX description payload associated with the node, if present."),properties:S.array(S.any()).nullable().describe("Additional AX properties exposed by the accessibility tree."),styles:S.record(S.string(),S.string()).optional().describe("Subset of computed CSS styles for the element as string key-value pairs."),runtime:S.object({boundingBox:S.object({x:S.number().describe("X coordinate of the element relative to the viewport."),y:S.number().describe("Y coordinate of the element relative to the viewport."),width:S.number().describe("Width of the element in CSS pixels."),height:S.number().describe("Height of the element in CSS pixels.")}).nullable().describe("Bounding box computed at runtime using getBoundingClientRect."),isVisible:S.boolean().describe("Whether the element is considered visually visible (display, visibility, opacity, and size)."),isInViewport:S.boolean().describe("Whether the element intersects the current viewport."),occlusion:S.object({samplePoints:S.array(S.object({x:S.number().describe("Sample point X (viewport coordinates) used for occlusion testing."),y:S.number().describe("Sample point Y (viewport coordinates) used for occlusion testing."),hit:S.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:S.boolean().describe("True if at least one sample point is covered by another element."),topElement:S.object({localName:S.string().nullable().describe("Tag name of the occluding element."),id:S.string().nullable().describe("DOM id of the occluding element (may be null if none)."),className:S.string().nullable().describe("DOM class of the occluding element (may be null if none)."),selectorHint:S.string().nullable().describe("Best-effort selector hint for the occluding element."),boundingBox:S.object({x:S.number().describe("X coordinate of the occluding element bounding box."),y:S.number().describe("Y coordinate of the occluding element bounding box."),width:S.number().describe("Width of the occluding element bounding box."),height:S.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:S.object({x:S.number().describe("Intersection rect X."),y:S.number().describe("Intersection rect Y."),width:S.number().describe("Intersection rect width."),height:S.number().describe("Intersection rect height."),area:S.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(e,t){let n=e.page,r=t.includeRuntimeVisual??Si,i=t.includeStyles??Ti,a=t.checkOcclusion??xi,l=t.onlyVisible??vi,u=t.onlyInViewport??Ii;if((l||u)&&!r)throw new Error("onlyVisible/onlyInViewport require includeRuntimeVisual=true.");if(a&&!r)throw new Error("checkOcclusion requires includeRuntimeVisual=true.");let m=t.textPreviewMaxLength??Ci,c=t.styleProperties&&t.styleProperties.length>0?t.styleProperties:Ei,p=Array.from(c).map(y=>y.toLowerCase()),g=t.roles&&t.roles.length>0?new Set(t.roles):new Set(Array.from(Al)),f=await n.context().newCDPSession(n);try{await f.send("DOM.enable"),await f.send("Accessibility.enable"),r&&await f.send("Runtime.enable");let y=await f.send("Accessibility.getFullAXTree"),P=y.nodes??y,T=new Map,W=new Map;for(let B of P){let V=String(B.nodeId),ae=(B.childIds??[]).map(ne=>String(ne));W.set(V,ae);for(let ne of ae)T.set(ne,V)}let K=P.filter(B=>{if(typeof B.backendDOMNodeId!="number")return!1;let V=B.role?.value??null;return V?g.has(String(V)):!1}),M=K.length,D=K.length>Oi;D&&(K=K.slice(0,Oi));let $=[...K],A=[],_=[],Q=s(async()=>{for(;$.length>0;){let B=$.shift();if(!B)return;let V=String(B.nodeId),Te=T.get(V)??null,ae=W.get(V)??[],ne=B.backendDOMNodeId,oe=null,pe=null,Ie=null,v=null,le=null;try{let fe=(await f.send("DOM.describeNode",{backendNodeId:ne}))?.node;if(fe){let Me=fe.nodeId;typeof Me=="number"&&Me>0?oe=Me:oe=null,pe=fe.localName??(fe.nodeName?String(fe.nodeName).toLowerCase():null);let Ve=Fl(fe.attributes);Ie=Ve.id??null,v=Ve.class??null}}catch{}if(r)try{le=(await f.send("DOM.resolveNode",{backendNodeId:ne}))?.object?.objectId??null}catch{}let X=B.role?.value?String(B.role.value):null,H=B.name?.value?String(B.name.value):null,Y=typeof B.ignored=="boolean"?B.ignored:null,Pe={axNodeId:V,parentAxNodeId:Te,childAxNodeIds:ae,role:X,name:H,ignored:Y,backendDOMNodeId:ne,domNodeId:oe,frameId:B.frameId??null,localName:pe,id:Ie,className:v,selectorHint:null,textPreview:null,value:B.value??null,description:B.description??null,properties:Array.isArray(B.properties)?B.properties:null},_e=A.push(Pe)-1;_[_e]=le}},"worker"),q=Array.from({length:Ll},()=>Q());if(await Promise.all(q),r){let V=(await f.send("Runtime.evaluate",{expression:"globalThis",returnByValue:!1}))?.result?.objectId;if(V){let Te=_.map(oe=>oe?{objectId:oe}:{value:null}),ne=(await f.send("Runtime.callFunctionOn",{objectId:V,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:m},{value:i},{value:p},{value:a},...Te]}))?.result?.value??[];for(let oe=0;oe<A.length;oe++){let pe=ne[oe];pe&&(A[oe].selectorHint=pe.selectorHint??null,A[oe].textPreview=pe.textPreview??null,pe.styles&&(A[oe].styles=pe.styles),pe.runtime&&(A[oe].runtime=pe.runtime))}}}let z=A;return(l||u)&&(z=z.filter(B=>!(!B.runtime||l&&!B.runtime.isVisible||u&&!B.runtime.isInViewport))),{url:String(n.url()),title:String(await n.title()),axNodeCount:P.length,candidateCount:M,enrichedCount:z.length,truncatedBySafetyCap:D,nodes:z}}finally{await f.detach().catch(()=>{})}}};var Ni=[new Un,new Hn];import{z as gt}from"zod";var Pi=5e4,Wn=class{static{s(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:gt.string().describe("CSS selector to limit the HTML content to a specific container.").optional(),removeScripts:gt.boolean().describe('Remove all script tags from the HTML (default: "true").').optional().default(!0),removeComments:gt.boolean().describe('Remove all HTML comments (default: "false").').optional().default(!1),removeStyles:gt.boolean().describe('Remove all style tags from the HTML (default: "false").').optional().default(!1),removeMeta:gt.boolean().describe('Remove all meta tags from the HTML (default: "false").').optional().default(!1),cleanHtml:gt.boolean().describe('Perform comprehensive HTML cleaning (default: "false").').optional().default(!1),minify:gt.boolean().describe('Minify the HTML output (default: "false").').optional().default(!1),maxLength:gt.number().int().positive().describe(`Maximum number of characters to return (default: "${Pi}").`).optional().default(Pi)}}outputSchema(){return{output:gt.string().describe("The requested HTML content of the page.")}}async handle(e,t){let{selector:n,removeScripts:r,removeComments:i,removeStyles:a,removeMeta:l,minify:u,cleanHtml:m,maxLength:c}=t,p;if(n){let W=await e.page.$(n);if(!W)throw new Error(`Element with selector "${n}" not found`);p=await W.evaluate(K=>K.outerHTML)}else p=await e.page.content();let g=r||m,f=i||m,y=a||m,P=l||m;(g||f||y||P||u)&&(p=await e.page.evaluate(W=>{let K=s((B,V)=>B[V],"g"),M=K(W,"html"),D=K(W,"removeScripts"),$=K(W,"removeComments"),A=K(W,"removeStyles"),_=K(W,"removeMeta"),Q=K(W,"minify"),q=document.createElement("template");q.innerHTML=M;let z=q.content;if(D&&z.querySelectorAll("script").forEach(V=>V.remove()),A&&z.querySelectorAll("style").forEach(V=>V.remove()),_&&z.querySelectorAll("meta").forEach(V=>V.remove()),$){let B=s(V=>{let Te=V.childNodes;for(let ae=Te.length-1;ae>=0;ae--){let ne=Te[ae];ne.nodeType===8?V.removeChild(ne):ne.nodeType===1&&B(ne)}},"removeComments");B(z)}let ee=q.innerHTML;return Q&&(ee=ee.replace(/>\s+</g,"><").trim()),ee},Object.fromEntries([["html",p],["removeScripts",g],["removeComments",f],["removeStyles",y],["removeMeta",P],["minify",u]])));let T=p;return T.length>c&&(T=T.slice(0,c)+`
266
- <!-- Output truncated due to size limits -->`),{output:T}}};import{z as as}from"zod";var ki=5e4,qn=class{static{s(this,"GetAsText")}name(){return"content_get-as-text"}description(){return"Gets the visible text content of the current page."}inputSchema(){return{selector:as.string().describe("CSS selector to limit the text content to a specific container.").optional(),maxLength:as.number().int().positive().describe(`Maximum number of characters to return (default: "${ki}").`).optional().default(ki)}}outputSchema(){return{output:as.string().describe("The requested text content of the page.")}}async handle(e,t){let{selector:n,maxLength:r}=t,a=await e.page.evaluate(l=>{let m=s((y,P)=>y[P],"g")(l,"selector"),c=m?document.querySelector(m):document.body;if(!c)throw new Error(`Element with selector "${m}" not found`);let p=document.createTreeWalker(c,NodeFilter.SHOW_TEXT,{acceptNode:s(y=>{let P=window.getComputedStyle(y.parentElement);return P.display!=="none"&&P.visibility!=="hidden"?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT},"acceptNode")}),g="",f;for(;f=p.nextNode();){let y=f.textContent?.trim();y&&(g+=y+`
267
- `)}return g.trim()},Object.fromEntries([["selector",n]]));return a.length>r&&(a=a.slice(0,r)+`
268
- [Output truncated due to size limits]`),{output:a}}};function ve(o){let e=Object.keys(o).filter(t=>isNaN(Number(t))).map(t=>o[t]);if(e.length===0)throw new Error("Enum has no values");return e}s(ve,"getEnumKeyTuples");function st(o,e){let t=Object.keys(o).filter(i=>isNaN(Number(i))).map(i=>o[i]),n=e?.caseInsensitive??!0,r=new Map(t.map(i=>[n?i.toLowerCase():i,i]));return i=>{let a=n?i.toLowerCase():i,l=r.get(a);if(l===void 0)throw new Error(`Invalid enum value: "${i}"`);return l}}s(st,"createEnumTransformer");function jn(o=new Date){let e=s(t=>String(t).padStart(2,"0"),"pad");return o.getFullYear()+e(o.getMonth()+1)+e(o.getDate())+"-"+e(o.getHours())+e(o.getMinutes())+e(o.getSeconds())}s(jn,"formattedTimeForFilename");import Ul from"node:os";import Hl from"node:path";import{z as it}from"zod";var Ri=(r=>(r.PIXEL="px",r.INCH="in",r.CENTIMETER="cm",r.MILLIMETER="mm",r))(Ri||{}),$n=(p=>(p.LETTER="Letter",p.LEGAL="Legal",p.TABLOID="Tabloid",p.LEDGER="Ledger",p.A0="A0",p.A1="A1",p.A2="A2",p.A3="A3",p.A4="A4",p.A5="A5",p.A6="A6",p))($n||{}),ls="page",St="1cm",Wl="A4",ql={top:St,right:St,bottom:St,left:St},zn=class{static{s(this,"SaveAsPdf")}name(){return"content_save-as-pdf"}description(){return"Saves the current page as a PDF file."}inputSchema(){return{outputPath:it.string().describe("Directory path where PDF will be saved. By default OS tmp directory is used.").optional().default(Ul.tmpdir()),name:it.string().describe(`Name of the save/export. Default value is "${ls}". 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(ls),format:it.enum(ve($n)).transform(st($n)).describe(`Page format. Valid values are: ${ve($n)}.`).optional().default(Wl),printBackground:it.boolean().describe('Whether to print background graphics (default: "false").').optional().default(!1),margin:it.object({top:it.string().describe("Top margin.").default(St),right:it.string().describe("Right margin.").default(St),bottom:it.string().describe("Bottom margin.").default(St),left:it.string().describe("Left margin.").default(St)}).describe(`Page margins. Numeric margin values labeled with units ("100px", "10cm", etc ...). Unlabeled values are treated as pixels. Valid units are: ${ve(Ri)}.`).optional()}}outputSchema(){return{filePath:it.string().describe("Full path of the saved PDF file.")}}async handle(e,t){let n=`${t.name||ls}-${jn()}.pdf`,r=Hl.resolve(t.outputPath,n),i={path:r,format:t.format,printBackground:t.printBackground,margin:t.margin||ql};return await e.page.pdf(i),{filePath:r}}};import jl from"node:os";import $l from"node:path";import Vn from"jpeg-js";import{PNG as zl}from"pngjs";import{z as Xe}from"zod";var Gn=(t=>(t.PNG="png",t.JPEG="jpeg",t))(Gn||{}),us="screenshot",_i="png",Mi=100,Kn=class{static{s(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:Xe.string().describe("Directory path where screenshot will be saved. By default OS tmp directory is used.").optional().default(jl.tmpdir()),name:Xe.string().describe(`Name of the screenshot. Default value is "${us}". 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(us),selector:Xe.string().describe("CSS selector for element to take screenshot.").optional(),fullPage:Xe.boolean().describe('Whether to take a screenshot of the full scrollable page, instead of the currently visible viewport (default: "false").').optional().default(!1),type:Xe.enum(ve(Gn)).transform(st(Gn)).describe(`Page format. Valid values are: ${ve(Gn)}`).optional().default(_i),quality:Xe.number().int().min(0).max(Mi).describe("The quality of the image, between 0-100. Not applicable to png images.").optional(),includeBase64:Xe.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:Xe.string().describe("Full path of the saved screenshot file."),image:Xe.object({data:Xe.any().describe("Base64-encoded image data."),mimeType:Xe.string().describe("MIME type of the image.")}).optional().describe('Image data included only when "includeBase64" input parameter is set to true.')}}_scaleImageToSize(e,t){let{data:n,width:r,height:i}=e,a=Math.max(1,Math.floor(t.width)),l=Math.max(1,Math.floor(t.height));if(r===a&&i===l)return e;if(r<=0||i<=0)throw new Error("Invalid input image");if(t.width<=0||t.height<=0||!isFinite(t.width)||!isFinite(t.height))throw new Error("Invalid output dimensions");let u=s(($,A,_)=>$<A?A:$>_?_:$,"clamp"),m=s(($,A)=>{let _=$*$,Q=_*$;A[0]=-.5*$+1*_-.5*Q,A[1]=1-2.5*_+1.5*Q,A[2]=.5*$+2*_-1.5*Q,A[3]=-.5*_+.5*Q},"weights"),c=r*4,p=a*4,g=new Int32Array(a*4),f=new Float32Array(a*4),y=new Float32Array(4),P=r/a;for(let $=0;$<a;$++){let A=($+.5)*P-.5,_=Math.floor(A),Q=A-_;m(Q,y);let q=$*4,z=u(_-1,0,r-1),ee=u(_+0,0,r-1),B=u(_+1,0,r-1),V=u(_+2,0,r-1);g[q+0]=z<<2,g[q+1]=ee<<2,g[q+2]=B<<2,g[q+3]=V<<2,f[q+0]=y[0],f[q+1]=y[1],f[q+2]=y[2],f[q+3]=y[3]}let T=new Int32Array(l*4),W=new Float32Array(l*4),K=new Float32Array(4),M=i/l;for(let $=0;$<l;$++){let A=($+.5)*M-.5,_=Math.floor(A),Q=A-_;m(Q,K);let q=$*4,z=u(_-1,0,i-1),ee=u(_+0,0,i-1),B=u(_+1,0,i-1),V=u(_+2,0,i-1);T[q+0]=z*c,T[q+1]=ee*c,T[q+2]=B*c,T[q+3]=V*c,W[q+0]=K[0],W[q+1]=K[1],W[q+2]=K[2],W[q+3]=K[3]}let D=new Uint8Array(a*l*4);for(let $=0;$<l;$++){let A=$*4,_=T[A+0],Q=T[A+1],q=T[A+2],z=T[A+3],ee=W[A+0],B=W[A+1],V=W[A+2],Te=W[A+3],ae=$*p;for(let ne=0;ne<a;ne++){let oe=ne*4,pe=g[oe+0],Ie=g[oe+1],v=g[oe+2],le=g[oe+3],X=f[oe+0],H=f[oe+1],Y=f[oe+2],Pe=f[oe+3],_e=ae+(ne<<2);for(let me=0;me<4;me++){let fe=n[_+pe+me]*X+n[_+Ie+me]*H+n[_+v+me]*Y+n[_+le+me]*Pe,Me=n[Q+pe+me]*X+n[Q+Ie+me]*H+n[Q+v+me]*Y+n[Q+le+me]*Pe,Ve=n[q+pe+me]*X+n[q+Ie+me]*H+n[q+v+me]*Y+n[q+le+me]*Pe,tt=n[z+pe+me]*X+n[z+Ie+me]*H+n[z+v+me]*Y+n[z+le+me]*Pe,Rt=fe*ee+Me*B+Ve*V+tt*Te;D[_e+me]=Rt<0?0:Rt>255?255:Rt|0}}}return{data:Buffer.from(D.buffer),width:a,height:l}}_scaleImageToFitMessage(e,t){let r=12058624e-1,i=1568,a=t==="png"?zl.sync.read(e):Vn.decode(e,{maxMemoryUsageInMB:512}),l=a.width*a.height,u=Math.min(i/a.width,i/a.height,Math.sqrt(r/l));u>1&&(u=1);let m=a.width*u|0,c=a.height*u|0,p=this._scaleImageToSize(a,{width:m,height:c}),g,f=t,y=t==="png"?75:70;t==="png"?(g=Vn.encode(p,y).data,f="jpeg"):g=Vn.encode(p,y).data;let P=0,T=5;for(;g.length>819200&&P<T;)y=Math.max(50,y-10),y<=50&&g.length>819200&&(u*=.85,m=Math.max(200,a.width*u|0),c=Math.max(200,a.height*u|0),p=this._scaleImageToSize(a,{width:m,height:c})),g=Vn.encode(p,y).data,P++;return g}async handle(e,t){let n=t.type||_i,r=`${t.name||us}-${jn()}.${n}`,i=$l.resolve(t.outputPath,r),a=n==="png"?void 0:t.quality??Mi,l={path:i,type:n,fullPage:!!t.fullPage,quality:a};if(t.selector){let c=await e.page.$(t.selector);if(!c)throw new Error(`Element not found: ${t.selector}`);l.element=c}let u=await e.page.screenshot(l),m={filePath:i};return t.includeBase64&&(m.image={data:this._scaleImageToFitMessage(u,n),mimeType:`image/${n}`}),m}};var Di=[new Wn,new qn,new zn,new Kn];import{z as ke}from"zod";var cs={maxSnapshots:1e3,maxCallStackDepth:20,maxFramesWithScopes:5,maxAsyncStackSegments:10,maxFramesPerAsyncSegment:10,maxDOMMutations:100,maxDOMHtmlSnippetLength:200,maxPendingRequests:1e3,maxResponseBodyLength:1e4,networkCleanupTimeoutMs:5e3},ms=new WeakMap;function Ht(){let o=Date.now(),e=Math.floor(Math.random()*1e6);return`${o.toString(36)}-${e.toString(36)}`}s(Ht,"_generateId");function Vl(o,e){try{let t=o.trim();return/^[=<>!%]/.test(t)&&(t=`hitCount ${t}`),!!new Function("hitCount",`return (${t});`)(e)}catch{return!1}}s(Vl,"_evaluateHitCondition");async function Gl(o,e,t){let n={};for(let r of t.values())try{let i=await o.evaluateOnCallFrame(e,r.expression);if(i.exceptionDetails)n[r.expression]=`[Error: ${i.exceptionDetails.text||"Evaluation failed"}]`;else{let a=await o.extractValueDeep(i.result,2);n[r.expression]=a}}catch(i){n[r.expression]=`[Error: ${i.message||"Unknown error"}]`}return n}s(Gl,"_evaluateWatchExpressionsOnFrame");function Ai(o,e,t,n){let r=ms.get(o);if(r)return r;let i=new oi(e,t),a=new ri(e),l={...cs,...n},u={v8Api:i,sourceMapResolver:a,probes:new Map,watchExpressions:new Map,domBreakpoints:new Map,networkBreakpoints:new Map,snapshots:[],snapshotSequence:0,config:l,enabled:!1,sourceMapsLoaded:!1,exceptionBreakpoint:"none",networkInterceptionEnabled:!1,recentDOMMutations:[]};return ms.set(o,u),u}s(Ai,"_ensureStore");function he(o){return ms.get(o)}s(he,"_getStore");async function Kl(o,e,t=3){let n=[];for(let r of e.scopeChain)if(!(r.type==="global"||r.type==="script"||r.type==="with"||r.type==="eval"||r.type==="wasm-expression-stack")){if(n.length>=t)break;try{let i=await o.getScopeVariables(r),a=[];for(let[l,u]of Object.entries(i))a.push({name:l,value:u,type:typeof u});n.push({type:r.type,name:r.name,variables:a})}catch{}}return n}s(Kl,"_captureScopes");async function Xl(o,e,t,n){let r=[];t&&(r=await Kl(o,e));let i;if(n){let a=n.generatedToOriginal(e.location.scriptId,e.location.lineNumber,e.location.columnNumber??0);a&&(i={source:a.source,line:a.line+1,column:a.column!==void 0?a.column+1:void 0,name:a.name})}return{functionName:e.functionName||"(anonymous)",url:e.url||"",lineNumber:e.location.lineNumber+1,columnNumber:e.location.columnNumber!==void 0?e.location.columnNumber+1:void 0,scriptId:e.location.scriptId,scopes:r,originalLocation:i}}s(Xl,"_callFrameToSnapshot");function Yl(o,e,t,n){if(!o)return;let r=t??cs.maxAsyncStackSegments,i=n??cs.maxFramesPerAsyncSegment,a=[],l=o,u=0;for(;l&&u<r;){let m=[];for(let c of l.callFrames.slice(0,i)){let p;if(e){let g=e.generatedToOriginal(c.location.scriptId,c.location.lineNumber,c.location.columnNumber??0);g&&(p={source:g.source,line:g.line+1,column:g.column!==void 0?g.column+1:void 0,name:g.name})}m.push({functionName:c.functionName||"(anonymous)",url:c.url||"",lineNumber:c.location.lineNumber+1,columnNumber:c.location.columnNumber!==void 0?c.location.columnNumber+1:void 0,originalLocation:p})}m.length>0&&a.push({description:l.description,callFrames:m}),l=l.parent,u++}if(a.length!==0)return{segments:a}}s(Yl,"_convertAsyncStackTrace");async function He(o,e,t){let n=Ai(o,e,t?.v8Options,t?.config);if(!n.enabled){await n.v8Api.enable(),n.v8Api.on("scriptParsed",r=>{n.sourceMapResolver.registerScript(r)});for(let r of n.v8Api.getScripts())n.sourceMapResolver.registerScript(r);n.v8Api.on("paused",async r=>{let i=Date.now();try{let a=r.reason==="exception"||r.reason==="promiseRejection",l=r.reason==="DOM",u=r.hitBreakpoints||[],m,c=!0,p,g;if(l&&r.data){let T=r.data;for(let W of n.domBreakpoints.values())if(W.enabled&&(W.nodeId===T.nodeId||!T.nodeId)){p=W,g={type:W.type,selector:W.selector,targetNode:T.targetNode?`<${T.targetNode.nodeName?.toLowerCase()||"unknown"}>`:void 0,attributeName:T.attributeName||W.attributeName};break}}if(p&&g)try{let T=await e.evaluate(W=>{let K=window;if(!K.__domBreakpointMutations)return null;let M=K.__domBreakpointMutations;for(let D=M.length-1;D>=0;D--)if(M[D].breakpointId===W)return M[D];return null},p.id);T&&(g.oldValue=T.oldValue,g.newValue=T.newValue,g.targetNode=T.targetOuterHTML,T.attributeName&&(g.attributeName=T.attributeName))}catch{}for(let T of n.probes.values()){if(!T.enabled)continue;if(T.v8BreakpointIds.some(K=>u.includes(K))){m=T,T.hitCondition&&(c=Vl(T.hitCondition,T.hitCount+1));break}}let f=m!==void 0&&c,y=a&&n.exceptionBreakpoint!=="none",P=p!==void 0;if(m&&(m.hitCount++,m.lastHitAt=Date.now()),p&&(p.hitCount++,p.lastHitAt=Date.now()),(f||y||P)&&r.callFrames.length>0){let T=r.callFrames[0],W;if(m&&m.kind==="logpoint"&&m.logExpression)try{let ee=await n.v8Api.evaluateOnCallFrame(T.callFrameId,m.logExpression,{returnByValue:!0,generatePreview:!0});W=n.v8Api.extractValue(ee.result)}catch{W="[evaluation error]"}let K;if(a&&r.data){let ee=r.data;K={type:r.reason==="promiseRejection"?"promiseRejection":"exception",message:ee.description||ee.value||String(ee),name:ee.className,stack:ee.description}}let M,D=n.sourceMapResolver.generatedToOriginal(T.location.scriptId,T.location.lineNumber,T.location.columnNumber??0);D&&(M={source:D.source,line:D.line+1,column:D.column!==void 0?D.column+1:void 0,name:D.name});let $=m?.id??p?.id??"__exception__",A=m?.kind==="logpoint",_=[];if(!A){let ee=r.callFrames.slice(0,n.config.maxCallStackDepth);for(let B=0;B<ee.length;B++){let V=ee[B],Te=B<n.config.maxFramesWithScopes,ae=await Xl(n.v8Api,V,Te,n.sourceMapResolver);_.push(ae)}}let Q;A||(Q=Yl(r.asyncStackTrace,n.sourceMapResolver,n.config.maxAsyncStackSegments,n.config.maxFramesPerAsyncSegment));let q;!A&&n.watchExpressions.size>0&&(q=await Gl(n.v8Api,T.callFrameId,n.watchExpressions));let z={id:Ht(),probeId:$,timestamp:Date.now(),sequenceNumber:++n.snapshotSequence,url:T.url||"",lineNumber:T.location.lineNumber+1,columnNumber:T.location.columnNumber!==void 0?T.location.columnNumber+1:void 0,originalLocation:M,exception:K,domChange:g,callStack:_,asyncStackTrace:Q,logResult:W,watchResults:q,captureTimeMs:Date.now()-i};n.snapshots.push(z),n.snapshots.length>n.config.maxSnapshots&&n.snapshots.splice(0,n.snapshots.length-n.config.maxSnapshots)}}finally{await n.v8Api.resume()}}),n.enabled=!0,n.sourceMapResolver.loadAllSourceMaps().then(()=>{n.sourceMapsLoaded=!0}).catch(()=>{})}}s(He,"enableDebugging");function N(o){return he(o)?.enabled??!1}s(N,"isDebuggingEnabled");async function Li(o,e,t,n,r=1){let i=Ai(o,e);i.enabled||await He(o,e);let a=await i.sourceMapResolver.resolveLocationByUrl(t,n,r);return a?{source:a.source,line:a.line+1,column:a.column+1,name:a.name}:null}s(Li,"resolveSourceLocation");async function Fi(o,e){let t=he(o);if(!t||!t.enabled)throw new Error("Debugging is not enabled");await t.v8Api.setPauseOnExceptions(e),t.exceptionBreakpoint=e}s(Fi,"setExceptionBreakpoint");function yn(o){return he(o)?.exceptionBreakpoint??"none"}s(yn,"getExceptionBreakpoint");function Ui(o){return he(o)?.sourceMapResolver.hasSourceMaps()??!1}s(Ui,"hasSourceMaps");async function Xn(o,e){let t=he(o);if(!t||!t.enabled)throw new Error("Debugging is not enabled");let n=Ht(),r;e.condition?r=`(${e.condition})`:r="true";let i=e.lineNumber-1,a=(e.columnNumber??1)-1,l=t.sourceMapResolver.originalToGenerated(e.urlPattern,i,a),u,m=0;if(l)u=(await t.v8Api.setBreakpoint({scriptId:l.scriptId,lineNumber:l.location.line,columnNumber:l.location.column},r)).breakpointId,m=1;else{let g=e.urlPattern.replace(/\\([.*+?^${}()|[\]\\/-])/g,"$1").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*").replace(/\\\?/g,"."),f=await t.v8Api.setBreakpointByUrl({urlRegex:g,lineNumber:e.lineNumber-1,columnNumber:e.columnNumber?e.columnNumber-1:void 0,condition:r});u=f.breakpointId,m=f.locations.length}let c={id:n,kind:e.kind,enabled:!0,urlPattern:e.urlPattern,lineNumber:e.lineNumber,columnNumber:e.columnNumber,condition:e.condition,logExpression:e.logExpression,hitCondition:e.hitCondition,v8BreakpointIds:[u],resolvedLocations:m,hitCount:0,createdAt:Date.now()};return t.probes.set(n,c),c}s(Xn,"createProbe");async function xt(o,e){let t=he(o);if(!t)return!1;let n=t.probes.get(e);if(!n)return!1;for(let r of n.v8BreakpointIds)try{await t.v8Api.removeBreakpoint(r)}catch{}return t.probes.delete(e),!0}s(xt,"removeProbe");function Ce(o){let e=he(o);return e?Array.from(e.probes.values()):[]}s(Ce,"listProbes");function Yn(o,e){let t=he(o);if(t)return t.probes.get(e)}s(Yn,"getProbe");function vt(o){let e=he(o);return e?[...e.snapshots]:[]}s(vt,"getSnapshots");function at(o,e){let t=he(o);return t?t.snapshots.filter(n=>n.probeId===e):[]}s(at,"getSnapshotsByProbe");function Ae(o,e){let t=he(o);if(!t)return 0;let n=t.snapshots.length;return t.snapshots=t.snapshots.filter(r=>r.probeId!==e),n-t.snapshots.length}s(Ae,"clearSnapshotsByProbe");function Hi(o){let e=he(o);if(!e||e.snapshots.length===0)return{totalSnapshots:0,snapshotsByProbe:{},averageCaptureTimeMs:0};let t={},n=0;for(let r of e.snapshots)t[r.probeId]=(t[r.probeId]||0)+1,n+=r.captureTimeMs;return{totalSnapshots:e.snapshots.length,snapshotsByProbe:t,oldestTimestamp:e.snapshots[0].timestamp,newestTimestamp:e.snapshots[e.snapshots.length-1].timestamp,averageCaptureTimeMs:n/e.snapshots.length}}s(Hi,"getSnapshotStats");function Wi(o,e){let t=he(o);if(!t)throw new Error("Debug store not initialized");let n=Ht(),r={id:n,expression:e,createdAt:Date.now()};return t.watchExpressions.set(n,r),r}s(Wi,"addWatchExpression");function qi(o,e){let t=he(o);return t?t.watchExpressions.delete(e):!1}s(qi,"removeWatchExpression");function Jn(o){let e=he(o);return e?Array.from(e.watchExpressions.values()):[]}s(Jn,"listWatchExpressions");function ji(o){let e=he(o);if(!e)return 0;let t=e.watchExpressions.size;return e.watchExpressions.clear(),t}s(ji,"clearWatchExpressions");async function $i(o,e,t){let n=he(o);if(!n||!n.enabled)throw new Error("Debugging is not enabled");let r=await n.v8Api.getCdp();await r.send("DOM.enable");let{root:i}=await r.send("DOM.getDocument",{depth:0}),{nodeId:a}=await r.send("DOM.querySelector",{nodeId:i.nodeId,selector:t.selector});if(!a||a===0)throw new Error(`Element not found: ${t.selector}`);let l=t.type==="subtree-modified"?"subtree-modified":t.type==="attribute-modified"?"attribute-modified":"node-removed";await r.send("DOMDebugger.setDOMBreakpoint",{nodeId:a,type:l});let u=Ht(),m={id:u,selector:t.selector,type:t.type,attributeName:t.attributeName,enabled:!0,nodeId:a,hitCount:0,createdAt:Date.now()};return n.domBreakpoints.set(u,m),await e.evaluate(c=>{let p=s((A,_)=>A[_],"g"),g=p(c,"selector"),f=p(c,"breakpointId"),y=p(c,"type"),P=p(c,"attrName"),T=p(c,"maxMutations"),W=p(c,"maxHtmlSnippetLength"),K=document.querySelector(g);if(!K)return;let M=window;M.__domBreakpointData=M.__domBreakpointData||{},M.__domBreakpointMutations=M.__domBreakpointMutations||[],M.__domBreakpointData[f]={selector:g,type:y,attrName:P,currentAttrs:{}};for(let A of K.attributes)M.__domBreakpointData[f].currentAttrs[A.name]=A.value;let D=new MutationObserver(A=>{for(let _ of A){let Q=_.target;if(_.type==="attributes"){let q=_.attributeName||"";if(P&&P!==q)continue;let z={breakpointId:f,selector:g,type:"attribute-modified",attributeName:q,oldValue:_.oldValue,newValue:Q.getAttribute(q),targetOuterHTML:Q.outerHTML.substring(0,W),timestamp:Date.now()};M.__domBreakpointMutations.push(z),M.__domBreakpointMutations.length>T&&M.__domBreakpointMutations.shift(),M.__domBreakpointData[f].currentAttrs[q]=Q.getAttribute(q)}else if(_.type==="childList"){let q={breakpointId:f,selector:g,type:"subtree-modified",addedNodes:_.addedNodes.length,removedNodes:_.removedNodes.length,targetOuterHTML:Q.outerHTML.substring(0,W),timestamp:Date.now()};M.__domBreakpointMutations.push(q),M.__domBreakpointMutations.length>T&&M.__domBreakpointMutations.shift()}}}),$={attributes:y==="attribute-modified",attributeOldValue:y==="attribute-modified",childList:y==="subtree-modified"||y==="node-removed",subtree:y==="subtree-modified"};P&&($.attributeFilter=[P]),D.observe(K,$),M.__domBreakpointObservers=M.__domBreakpointObservers||{},M.__domBreakpointObservers[f]=D},Object.fromEntries([["selector",t.selector],["breakpointId",u],["type",t.type],["attrName",t.attributeName],["maxMutations",n.config.maxDOMMutations],["maxHtmlSnippetLength",n.config.maxDOMHtmlSnippetLength]])),m}s($i,"setDOMBreakpoint");async function ps(o,e,t){let n=he(o);if(!n)return!1;let r=n.domBreakpoints.get(e);if(!r||!r.nodeId)return!1;try{let i=await n.v8Api.getCdp(),a=r.type==="subtree-modified"?"subtree-modified":r.type==="attribute-modified"?"attribute-modified":"node-removed";await i.send("DOMDebugger.removeDOMBreakpoint",{nodeId:r.nodeId,type:a})}catch{}if(t)try{await t.evaluate(i=>{let a=window;a.__domBreakpointObservers&&a.__domBreakpointObservers[i]&&(a.__domBreakpointObservers[i].disconnect(),delete a.__domBreakpointObservers[i]),a.__domBreakpointData&&delete a.__domBreakpointData[i],a.__domBreakpointMutations&&(a.__domBreakpointMutations=a.__domBreakpointMutations.filter(l=>l.breakpointId!==i))},e)}catch{}return n.domBreakpoints.delete(e)}s(ps,"removeDOMBreakpoint");function It(o){let e=he(o);return e?Array.from(e.domBreakpoints.values()):[]}s(It,"listDOMBreakpoints");async function zi(o,e){let t=he(o);if(!t)return 0;let n=Array.from(t.domBreakpoints.keys());for(let r of n)await ps(o,r,e);return n.length}s(zi,"clearDOMBreakpoints");async function Jl(o,e){if(o.networkInterceptionEnabled)return;let t=await o.v8Api.getCdp();await t.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]}),t.on("Fetch.requestPaused",async r=>{let i=r.requestId,a=r.request.url,l=r.request.method;try{let u;for(let m of o.networkBreakpoints.values()){if(!m.enabled)continue;let c=m.urlPattern.replace(/\\([.*+?^${}()|[\]\\/-])/g,"$1");if(new RegExp(c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")).test(a)&&!(m.method&&m.method.toUpperCase()!==l.toUpperCase())&&m.timing==="request"){u=m;break}}if(u&&u.timing==="request"){let m={url:a,method:l,requestHeaders:r.request.headers,requestBody:r.request.postData,resourceType:r.resourceType,timing:"request"},c={id:Ht(),probeId:u.id,timestamp:Date.now(),sequenceNumber:++o.snapshotSequence,url:a,lineNumber:0,networkRequest:m,callStack:[],captureTimeMs:0};o.watchExpressions.size>0&&(c.watchResults=await Bi(o,e)),o.snapshots.push(c),o.snapshots.length>o.config.maxSnapshots&&o.snapshots.splice(0,o.snapshots.length-o.config.maxSnapshots),u.hitCount++,u.lastHitAt=Date.now()}await t.send("Fetch.continueRequest",{requestId:i})}catch{try{await t.send("Fetch.continueRequest",{requestId:i})}catch{}}}),await t.send("Network.enable");let n=new Map;t.on("Network.requestWillBeSent",r=>{if(n.set(r.requestId,{method:r.request.method,postData:r.request.postData}),n.size>o.config.maxPendingRequests){let i=n.keys().next().value;i&&n.delete(i)}}),t.on("Network.responseReceived",async r=>{let i=r.requestId,a=r.response.url,l=n.get(i),u=l?.method||r.type||"GET",m=r.response.status;for(let c of o.networkBreakpoints.values()){if(!c.enabled||c.timing!=="response")continue;let p=c.urlPattern.replace(/\\([.*+?^${}()|[\]\\/-])/g,"$1");if(!new RegExp(p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")).test(a)||c.method&&c.method.toUpperCase()!==u.toUpperCase()||c.onError&&m<400)continue;let f;try{let T=await t.send("Network.getResponseBody",{requestId:i});T.base64Encoded?f=Buffer.from(T.body,"base64").toString("utf-8"):f=T.body,f&&f.length>o.config.maxResponseBodyLength&&(f=f.substring(0,o.config.maxResponseBodyLength)+"... [truncated]")}catch{}let y={url:a,method:u,requestBody:l?.postData,status:m,statusText:r.response.statusText,responseHeaders:r.response.headers,responseBody:f,resourceType:r.type,timing:"response"},P={id:Ht(),probeId:c.id,timestamp:Date.now(),sequenceNumber:++o.snapshotSequence,url:a,lineNumber:0,networkRequest:y,callStack:[],captureTimeMs:0};o.watchExpressions.size>0&&(P.watchResults=await Bi(o,e)),o.snapshots.push(P),o.snapshots.length>o.config.maxSnapshots&&o.snapshots.splice(0,o.snapshots.length-o.config.maxSnapshots),c.hitCount++,c.lastHitAt=Date.now(),n.delete(i);break}}),t.on("Network.loadingFinished",r=>{setTimeout(()=>{n.delete(r.requestId)},o.config.networkCleanupTimeoutMs)}),o.networkInterceptionEnabled=!0}s(Jl,"_enableNetworkInterception");async function Bi(o,e){let t={};for(let n of o.watchExpressions.values())try{let r=await e.evaluate(i=>{try{return(0,eval)(i)}catch(a){return`[Error: ${a.message}]`}},n.expression);t[n.expression]=r}catch(r){t[n.expression]=`[Error: ${r.message}]`}return t}s(Bi,"_evaluateWatchExpressions");async function Vi(o,e,t){let n=he(o);if(!n||!n.enabled)throw new Error("Debugging is not enabled");await Jl(n,e);let r=Ht(),i={id:r,urlPattern:t.urlPattern,method:t.method,timing:t.timing||"request",onError:t.onError,enabled:!0,hitCount:0,createdAt:Date.now()};return n.networkBreakpoints.set(r,i),i}s(Vi,"setNetworkBreakpoint");function Gi(o,e){let t=he(o);return t?t.networkBreakpoints.delete(e):!1}s(Gi,"removeNetworkBreakpoint");function Ct(o){let e=he(o);return e?Array.from(e.networkBreakpoints.values()):[]}s(Ct,"listNetworkBreakpoints");function Ki(o){let e=he(o);if(!e)return 0;let t=e.networkBreakpoints.size;return e.networkBreakpoints.clear(),t}s(Ki,"clearNetworkBreakpoints");var Qn=class{static{s(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:ke.boolean().describe("Whether debugging is enabled"),hasSourceMaps:ke.boolean().describe("Whether source maps are loaded"),exceptionBreakpoint:ke.string().describe("Exceptionpoint state (none, uncaught, all)"),tracepointCount:ke.number().describe("Number of tracepoints"),logpointCount:ke.number().describe("Number of logpoints"),watchExpressionCount:ke.number().describe("Number of watch expressions"),dompointCount:ke.number().describe("Number of dompoints"),netpointCount:ke.number().describe("Number of netpoints"),snapshotStats:ke.object({totalSnapshots:ke.number(),snapshotsByProbe:ke.record(ke.number()),oldestTimestamp:ke.number().optional(),newestTimestamp:ke.number().optional(),averageCaptureTimeMs:ke.number()}).nullable().describe("Snapshot statistics")}}async handle(e,t){if(!N(e.browserContext))return{enabled:!1,hasSourceMaps:!1,exceptionBreakpoint:"none",tracepointCount:0,logpointCount:0,watchExpressionCount:0,dompointCount:0,netpointCount:0,snapshotStats:null};let r=Ce(e.browserContext),i=r.filter(l=>l.kind==="tracepoint").length,a=r.filter(l=>l.kind==="logpoint").length;return{enabled:!0,hasSourceMaps:Ui(e.browserContext),exceptionBreakpoint:yn(e.browserContext),tracepointCount:i,logpointCount:a,watchExpressionCount:Jn(e.browserContext).length,dompointCount:It(e.browserContext).length,netpointCount:Ct(e.browserContext).length,snapshotStats:Hi(e.browserContext)}}};import{z as Et}from"zod";var Zn=class{static{s(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:Et.string().describe("Generated script URL (e.g. https://example.com/bundle.js or relative path)"),line:Et.number().int().positive().describe("Line number in generated code (1-based)"),column:Et.number().int().nonnegative().describe("Column number in generated code (1-based, default 1)").optional()}}outputSchema(){return{resolved:Et.boolean().describe("Whether the location was resolved to original source"),source:Et.string().optional().describe("Original source file path"),line:Et.number().optional().describe("Line number in original source (1-based)"),column:Et.number().optional().describe("Column number in original source (1-based)"),name:Et.string().optional().describe("Original identifier name if available")}}async handle(e,t){let n=await Li(e.browserContext,e.page,t.url,t.line,t.column??1);return n?{resolved:!0,source:n.source,line:n.line,column:n.column,name:n.name}:{resolved:!1}}};import{z as $e}from"zod";var eo=class{static{s(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:$e.string().describe('Script URL pattern (e.g., "app.js"). Auto-escaped, do not add backslashes.'),lineNumber:$e.number().int().positive().describe("Line number (1-based)"),columnNumber:$e.number().int().nonnegative().describe("Column number (1-based). Optional.").optional(),condition:$e.string().describe("Conditional expression - only triggers if this evaluates to true").optional(),hitCondition:$e.string().describe('Hit count condition, e.g., "== 5" (5th hit), ">= 10" (10th and after), "% 10 == 0" (every 10th)').optional()}}outputSchema(){return{id:$e.string().describe("Tracepoint ID"),urlPattern:$e.string().describe("URL pattern"),lineNumber:$e.number().describe("Line number"),columnNumber:$e.number().optional().describe("Column number"),condition:$e.string().optional().describe("Condition expression"),hitCondition:$e.string().optional().describe("Hit count condition"),resolvedLocations:$e.number().describe("Number of locations where tracepoint was resolved")}}async handle(e,t){N(e.browserContext)||await He(e.browserContext,e.page);let n=await Xn(e.browserContext,{kind:"tracepoint",urlPattern:t.urlPattern,lineNumber:t.lineNumber,columnNumber:t.columnNumber,condition:t.condition,hitCondition:t.hitCondition});return{id:n.id,urlPattern:n.urlPattern,lineNumber:n.lineNumber,columnNumber:n.columnNumber,condition:n.condition,hitCondition:n.hitCondition,resolvedLocations:n.resolvedLocations}}};import{z as ds}from"zod";var to=class{static{s(this,"RemoveTracepoint")}name(){return"debug_remove-tracepoint"}description(){return"Removes a tracepoint by its ID."}inputSchema(){return{id:ds.string().describe("Tracepoint ID to remove")}}outputSchema(){return{success:ds.boolean().describe("Whether the tracepoint was removed"),message:ds.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{success:!1,message:"No active tracepoints"};let n=Yn(e.browserContext,t.id);if(!n||n.kind!=="tracepoint")return{success:!1,message:`Tracepoint ${t.id} not found`};let r=await xt(e.browserContext,t.id);return{success:r,message:r?`Tracepoint ${t.id} removed`:"Failed to remove tracepoint"}}};import{z as We}from"zod";var no=class{static{s(this,"ListTracepoints")}name(){return"debug_list-tracepoints"}description(){return"Lists all active tracepoints."}inputSchema(){return{}}outputSchema(){return{tracepoints:We.array(We.object({id:We.string(),urlPattern:We.string(),lineNumber:We.number(),columnNumber:We.number().optional(),condition:We.string().optional(),hitCondition:We.string().optional(),enabled:We.boolean(),resolvedLocations:We.number(),hitCount:We.number(),lastHitAt:We.number().optional()})).describe("List of tracepoints"),total:We.number().describe("Total count")}}async handle(e,t){if(!N(e.browserContext))return{tracepoints:[],total:0};let r=Ce(e.browserContext).filter(i=>i.kind==="tracepoint").map(i=>({id:i.id,urlPattern:i.urlPattern,lineNumber:i.lineNumber,columnNumber:i.columnNumber,condition:i.condition,hitCondition:i.hitCondition,enabled:i.enabled,resolvedLocations:i.resolvedLocations,hitCount:i.hitCount,lastHitAt:i.lastHitAt}));return{tracepoints:r,total:r.length}}};import{z as Xi}from"zod";var oo=class{static{s(this,"ClearTracepoints")}name(){return"debug_clear-tracepoints"}description(){return"Removes all tracepoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:Xi.number().describe("Number of tracepoints cleared"),message:Xi.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No tracepoints to clear"};let n=Ce(e.browserContext).filter(i=>i.kind==="tracepoint"),r=0;for(let i of n)await xt(e.browserContext,i.id)&&r++;return{clearedCount:r,message:`Cleared ${r} tracepoint(s)`}}};import{z as Le}from"zod";var ro=class{static{s(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:Le.string().describe('Script URL pattern (e.g., "app.js"). Auto-escaped, do not add backslashes.'),lineNumber:Le.number().int().positive().describe("Line number (1-based)"),logExpression:Le.string().describe("Expression to evaluate and log when hit"),columnNumber:Le.number().int().nonnegative().describe("Column number (1-based). Optional.").optional(),condition:Le.string().describe("Conditional expression - logpoint only hits if this evaluates to true").optional(),hitCondition:Le.string().describe('Hit count condition, e.g., "== 5" (5th hit), ">= 10" (10th and after), "% 10 == 0" (every 10th)').optional()}}outputSchema(){return{id:Le.string().describe("Debug point ID"),urlPattern:Le.string().describe("URL pattern"),lineNumber:Le.number().describe("Line number"),logExpression:Le.string().describe("Log expression"),columnNumber:Le.number().optional().describe("Column number"),condition:Le.string().optional().describe("Condition expression"),hitCondition:Le.string().optional().describe("Hit count condition"),resolvedLocations:Le.number().describe("Number of locations where logpoint was resolved")}}async handle(e,t){N(e.browserContext)||await He(e.browserContext,e.page);let n=await Xn(e.browserContext,{kind:"logpoint",urlPattern:t.urlPattern,lineNumber:t.lineNumber,logExpression:t.logExpression,columnNumber:t.columnNumber,condition:t.condition,hitCondition:t.hitCondition});return{id:n.id,urlPattern:n.urlPattern,lineNumber:n.lineNumber,logExpression:n.logExpression||t.logExpression,columnNumber:n.columnNumber,condition:n.condition,hitCondition:n.hitCondition,resolvedLocations:n.resolvedLocations}}};import{z as bs}from"zod";var so=class{static{s(this,"RemoveLogpoint")}name(){return"debug_remove-logpoint"}description(){return"Removes a logpoint by its ID."}inputSchema(){return{id:bs.string().describe("Logpoint ID to remove")}}outputSchema(){return{success:bs.boolean().describe("Whether the logpoint was removed"),message:bs.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{success:!1,message:"No active logpoints"};let n=Yn(e.browserContext,t.id);if(!n||n.kind!=="logpoint")return{success:!1,message:`Logpoint ${t.id} not found`};let r=await xt(e.browserContext,t.id);return{success:r,message:r?`Logpoint ${t.id} removed`:"Failed to remove logpoint"}}};import{z as Fe}from"zod";var io=class{static{s(this,"ListLogpoints")}name(){return"debug_list-logpoints"}description(){return"Lists all active logpoints."}inputSchema(){return{}}outputSchema(){return{logpoints:Fe.array(Fe.object({id:Fe.string(),urlPattern:Fe.string(),lineNumber:Fe.number(),logExpression:Fe.string(),columnNumber:Fe.number().optional(),condition:Fe.string().optional(),hitCondition:Fe.string().optional(),enabled:Fe.boolean(),resolvedLocations:Fe.number(),hitCount:Fe.number(),lastHitAt:Fe.number().optional()})).describe("List of logpoints"),total:Fe.number().describe("Total count")}}async handle(e,t){if(!N(e.browserContext))return{logpoints:[],total:0};let r=Ce(e.browserContext).filter(i=>i.kind==="logpoint").map(i=>({id:i.id,urlPattern:i.urlPattern,lineNumber:i.lineNumber,logExpression:i.logExpression||"",columnNumber:i.columnNumber,condition:i.condition,hitCondition:i.hitCondition,enabled:i.enabled,resolvedLocations:i.resolvedLocations,hitCount:i.hitCount,lastHitAt:i.lastHitAt}));return{logpoints:r,total:r.length}}};import{z as Yi}from"zod";var ao=class{static{s(this,"ClearLogpoints")}name(){return"debug_clear-logpoints"}description(){return"Removes all logpoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:Yi.number().describe("Number of logpoints cleared"),message:Yi.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No logpoints to clear"};let n=Ce(e.browserContext).filter(i=>i.kind==="logpoint"),r=0;for(let i of n)await xt(e.browserContext,i.id)&&r++;return{clearedCount:r,message:`Cleared ${r} logpoint(s)`}}};import{z as lo}from"zod";var uo=class{static{s(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:lo.enum(["none","uncaught","all"]).describe("Exception tracepoint state")}}outputSchema(){return{previousState:lo.string().describe("Previous state"),currentState:lo.string().describe("Current state"),message:lo.string().describe("Status message")}}async handle(e,t){N(e.browserContext)||await He(e.browserContext,e.page);let n=yn(e.browserContext);await Fi(e.browserContext,t.state);let r=yn(e.browserContext);return{previousState:n,currentState:r,message:`Exception tracepoint set to: ${r}`}}};import{z as Tn}from"zod";import{z as w}from"zod";var gs=w.object({source:w.string().describe("Original source file path"),line:w.number().describe("1-based line number"),column:w.number().optional().describe("1-based column number"),name:w.string().optional().describe("Original identifier name")}),Ql=w.object({name:w.string().describe("Variable name"),value:w.any().describe("Variable value"),type:w.string().describe("Variable type")}),Zl=w.object({type:w.string().describe("Scope type (global, local, closure, etc.)"),name:w.string().optional().describe("Scope name"),variables:w.array(Ql).describe("Variables in this scope")}),hs=w.object({functionName:w.string().describe("Function name"),url:w.string().describe("Script URL"),lineNumber:w.number().describe("1-based line number"),columnNumber:w.number().optional().describe("1-based column number"),scriptId:w.string().describe("V8 script ID"),scopes:w.array(Zl).describe("Variable scopes"),originalLocation:gs.optional().describe("Original source location")}),eu=w.object({functionName:w.string().describe("Function name"),url:w.string().describe("Script URL"),lineNumber:w.number().describe("1-based line number"),columnNumber:w.number().optional().describe("1-based column number"),originalLocation:gs.optional().describe("Original source location")}),tu=w.object({description:w.string().optional().describe("Async boundary (Promise.then, setTimeout, etc.)"),callFrames:w.array(eu).describe("Frames in this segment")}),fs=w.object({segments:w.array(tu).describe("Chain of async segments")}),wn=w.object({id:w.string().describe("Snapshot ID"),probeId:w.string().describe("Probe ID that triggered this snapshot"),timestamp:w.number().describe("Unix timestamp (ms)"),sequenceNumber:w.number().describe("Monotonic sequence number for ordering"),url:w.string().describe("Script URL where snapshot was taken"),lineNumber:w.number().describe("1-based line number"),columnNumber:w.number().optional().describe("1-based column number"),originalLocation:gs.optional().describe("Original source location"),captureTimeMs:w.number().describe("Time taken to capture snapshot (ms)")}),Ji=wn.extend({callStack:w.array(hs).describe("Call stack with local variables"),asyncStackTrace:fs.optional().describe("Async stack trace"),watchResults:w.record(w.any()).optional().describe("Watch expression results")}),Qi=wn.extend({logResult:w.any().optional().describe("Result of log expression evaluation")}),nu=w.object({type:w.enum(["exception","promiseRejection"]).describe("Exception type"),message:w.string().describe("Exception message"),name:w.string().optional().describe("Exception name/class"),stack:w.string().optional().describe("Stack trace string")}),Zi=wn.extend({exception:nu.optional().describe("Exception information"),callStack:w.array(hs).describe("Call stack at exception"),asyncStackTrace:fs.optional().describe("Async stack trace"),watchResults:w.record(w.any()).optional().describe("Watch expression results")}),ou=w.object({type:w.enum(["subtree-modified","attribute-modified","node-removed"]).describe("DOM mutation type"),selector:w.string().describe("CSS selector of watched element"),targetNode:w.string().optional().describe("Outer HTML snippet of target"),attributeName:w.string().optional().describe("Changed attribute name"),oldValue:w.string().optional().describe("Previous value"),newValue:w.string().optional().describe("New value")}),ea=wn.extend({domChange:ou.optional().describe("DOM change information"),callStack:w.array(hs).describe("Call stack when DOM changed"),asyncStackTrace:fs.optional().describe("Async stack trace"),watchResults:w.record(w.any()).optional().describe("Watch expression results")}),ru=w.object({url:w.string().describe("Request URL"),method:w.string().describe("HTTP method"),requestHeaders:w.record(w.string()).optional().describe("Request headers"),requestBody:w.string().optional().describe("Request body"),status:w.number().optional().describe("Response status code"),statusText:w.string().optional().describe("Response status text"),responseHeaders:w.record(w.string()).optional().describe("Response headers"),responseBody:w.string().optional().describe("Response body"),resourceType:w.string().optional().describe("Resource type (xhr, fetch, etc.)"),timing:w.enum(["request","response"]).describe("When snapshot was taken"),duration:w.number().optional().describe("Request duration (ms)"),error:w.string().optional().describe("Error message if failed")}),ta=wn.extend({networkRequest:ru.optional().describe("Network request/response info")});var co=class{static{s(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:Tn.string().describe("Filter by specific tracepoint ID").optional(),fromSequence:Tn.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:Tn.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:Tn.array(Ji).describe("Array of tracepoint snapshots"),total:Tn.number().describe("Total number of matching snapshots")}}async handle(e,t){if(!N(e.browserContext))return{snapshots:[],total:0};let n;if(t.probeId)n=at(e.browserContext,t.probeId);else{let i=new Set(Ce(e.browserContext).filter(a=>a.kind==="tracepoint").map(a=>a.id));n=vt(e.browserContext).filter(a=>i.has(a.probeId))}t.fromSequence!==void 0&&(n=n.filter(i=>i.sequenceNumber>t.fromSequence));let r=n.length;return t.limit&&n.length>t.limit&&(n=n.slice(0,t.limit)),{snapshots:n,total:r}}};import{z as ys}from"zod";var mo=class{static{s(this,"ClearTracepointSnapshots")}name(){return"debug_clear-tracepoint-snapshots"}description(){return"Clears snapshots captured by tracepoints. Optionally filter by specific tracepoint ID."}inputSchema(){return{probeId:ys.string().describe("Clear only snapshots for this tracepoint ID").optional()}}outputSchema(){return{clearedCount:ys.number().describe("Number of snapshots cleared"),message:ys.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No snapshots to clear"};let n=0;if(t.probeId)n=Ae(e.browserContext,t.probeId);else{let r=Ce(e.browserContext).filter(i=>i.kind==="tracepoint").map(i=>i.id);for(let i of r)n+=Ae(e.browserContext,i)}return{clearedCount:n,message:`Cleared ${n} tracepoint snapshot(s)`}}};import{z as Sn}from"zod";var po=class{static{s(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:Sn.string().describe("Filter by specific logpoint ID").optional(),fromSequence:Sn.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:Sn.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:Sn.array(Qi).describe("Array of logpoint snapshots"),total:Sn.number().describe("Total number of matching snapshots")}}async handle(e,t){if(!N(e.browserContext))return{snapshots:[],total:0};let n;if(t.probeId)n=at(e.browserContext,t.probeId);else{let a=new Set(Ce(e.browserContext).filter(l=>l.kind==="logpoint").map(l=>l.id));n=vt(e.browserContext).filter(l=>a.has(l.probeId))}t.fromSequence!==void 0&&(n=n.filter(a=>a.sequenceNumber>t.fromSequence));let r=n.length;return t.limit&&n.length>t.limit&&(n=n.slice(0,t.limit)),{snapshots:n.map(a=>({id:a.id,probeId:a.probeId,timestamp:a.timestamp,sequenceNumber:a.sequenceNumber,url:a.url,lineNumber:a.lineNumber,columnNumber:a.columnNumber,originalLocation:a.originalLocation,captureTimeMs:a.captureTimeMs,logResult:a.logResult})),total:r}}};import{z as ws}from"zod";var bo=class{static{s(this,"ClearLogpointSnapshots")}name(){return"debug_clear-logpoint-snapshots"}description(){return"Clears snapshots captured by logpoints. Optionally filter by specific logpoint ID."}inputSchema(){return{probeId:ws.string().describe("Clear only snapshots for this logpoint ID").optional()}}outputSchema(){return{clearedCount:ws.number().describe("Number of snapshots cleared"),message:ws.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No snapshots to clear"};let n=0;if(t.probeId)n=Ae(e.browserContext,t.probeId);else{let r=Ce(e.browserContext).filter(i=>i.kind==="logpoint").map(i=>i.id);for(let i of r)n+=Ae(e.browserContext,i)}return{clearedCount:n,message:`Cleared ${n} logpoint snapshot(s)`}}};import{z as go}from"zod";var ho=class{static{s(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:go.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:go.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:go.array(Zi).describe("Array of exceptionpoint snapshots"),total:go.number().describe("Total number of matching snapshots")}}async handle(e,t){if(!N(e.browserContext))return{snapshots:[],total:0};let n=at(e.browserContext,"__exception__");t.fromSequence!==void 0&&(n=n.filter(i=>i.sequenceNumber>t.fromSequence));let r=n.length;return t.limit&&n.length>t.limit&&(n=n.slice(0,t.limit)),{snapshots:n,total:r}}};import{z as na}from"zod";var fo=class{static{s(this,"ClearExceptionpointSnapshots")}name(){return"debug_clear-exceptionpoint-snapshots"}description(){return"Clears all snapshots captured by exceptionpoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:na.number().describe("Number of snapshots cleared"),message:na.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No snapshots to clear"};let n=Ae(e.browserContext,"__exception__");return{clearedCount:n,message:`Cleared ${n} exceptionpoint snapshot(s)`}}};import{z as xn}from"zod";var yo=class{static{s(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:xn.string().describe("Filter by specific dompoint ID").optional(),fromSequence:xn.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:xn.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:xn.array(ea).describe("Array of dompoint snapshots"),total:xn.number().describe("Total number of matching snapshots")}}async handle(e,t){if(!N(e.browserContext))return{snapshots:[],total:0};let n;if(t.probeId)n=at(e.browserContext,t.probeId);else{let i=new Set(It(e.browserContext).map(a=>a.id));n=vt(e.browserContext).filter(a=>i.has(a.probeId))}t.fromSequence!==void 0&&(n=n.filter(i=>i.sequenceNumber>t.fromSequence));let r=n.length;return t.limit&&n.length>t.limit&&(n=n.slice(0,t.limit)),{snapshots:n,total:r}}};import{z as Ts}from"zod";var wo=class{static{s(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:Ts.string().describe("Optional dompoint ID to clear snapshots for").optional()}}outputSchema(){return{clearedCount:Ts.number().describe("Number of snapshots cleared"),message:Ts.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No snapshots to clear"};let n=0;if(t.probeId)n=Ae(e.browserContext,t.probeId);else{let r=It(e.browserContext);for(let i of r)n+=Ae(e.browserContext,i.id)}return{clearedCount:n,message:`Cleared ${n} dompoint snapshot(s)`}}};import{z as vn}from"zod";var To=class{static{s(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:vn.string().describe("Filter by specific netpoint ID").optional(),fromSequence:vn.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:vn.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:vn.array(ta).describe("Array of netpoint snapshots"),total:vn.number().describe("Total number of matching snapshots")}}async handle(e,t){if(!N(e.browserContext))return{snapshots:[],total:0};let n;if(t.probeId)n=at(e.browserContext,t.probeId);else{let i=new Set(Ct(e.browserContext).map(a=>a.id));n=vt(e.browserContext).filter(a=>i.has(a.probeId))}t.fromSequence!==void 0&&(n=n.filter(i=>i.sequenceNumber>t.fromSequence));let r=n.length;return t.limit&&n.length>t.limit&&(n=n.slice(0,t.limit)),{snapshots:n,total:r}}};import{z as Ss}from"zod";var So=class{static{s(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:Ss.string().describe("Optional netpoint ID to clear snapshots for").optional()}}outputSchema(){return{clearedCount:Ss.number().describe("Number of snapshots cleared"),message:Ss.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No snapshots to clear"};let n=0;if(t.probeId)n=Ae(e.browserContext,t.probeId);else{let r=Ct(e.browserContext);for(let i of r)n+=Ae(e.browserContext,i.id)}return{clearedCount:n,message:`Cleared ${n} netpoint snapshot(s)`}}};import{z as xo}from"zod";var vo=class{static{s(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:xo.string().describe("JavaScript expression to watch")}}outputSchema(){return{id:xo.string().describe("Watch expression ID"),expression:xo.string().describe("The watch expression"),message:xo.string().describe("Status message")}}async handle(e,t){N(e.browserContext)||await He(e.browserContext,e.page);let n=Wi(e.browserContext,t.expression);return{id:n.id,expression:n.expression,message:`Watch expression added: ${t.expression}`}}};import{z as xs}from"zod";var Io=class{static{s(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:xs.string().describe("Watch expression ID to remove")}}outputSchema(){return{success:xs.boolean().describe("Whether the watch was removed"),message:xs.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{success:!1,message:"Debugging is not active"};let n=qi(e.browserContext,t.id);return{success:n,message:n?`Watch expression ${t.id} removed`:`Watch expression ${t.id} not found`}}};import{z as en}from"zod";var Co=class{static{s(this,"ListWatches")}name(){return"debug_list-watches"}description(){return`
381
- Lists all active watch expressions.
382
- `}inputSchema(){return{}}outputSchema(){return{watches:en.array(en.object({id:en.string(),expression:en.string(),createdAt:en.number()})).describe("List of watch expressions"),total:en.number().describe("Total count")}}async handle(e,t){if(!N(e.browserContext))return{watches:[],total:0};let r=Jn(e.browserContext).map(i=>({id:i.id,expression:i.expression,createdAt:i.createdAt}));return{watches:r,total:r.length}}};import{z as oa}from"zod";var Eo=class{static{s(this,"ClearWatches")}name(){return"debug_clear-watches"}description(){return`
383
- Removes all watch expressions.
384
- `}inputSchema(){return{}}outputSchema(){return{clearedCount:oa.number().describe("Number of watch expressions cleared"),message:oa.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No watch expressions to clear"};let n=ji(e.browserContext);return{clearedCount:n,message:`Cleared ${n} watch expression(s)`}}};import{z as ht}from"zod";var Oo=class{static{s(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:ht.string().describe("CSS selector for the target element"),type:ht.enum(["subtree-modified","attribute-modified","node-removed"]).describe("Type of DOM change to monitor"),attributeName:ht.string().describe("For attribute-modified: specific attribute to monitor").optional()}}outputSchema(){return{id:ht.string().describe("Dompoint ID"),selector:ht.string().describe("CSS selector"),type:ht.string().describe("Dompoint type"),attributeName:ht.string().optional().describe("Monitored attribute"),nodeId:ht.number().optional().describe("CDP node ID"),message:ht.string().describe("Status message")}}async handle(e,t){N(e.browserContext)||await He(e.browserContext,e.page);let n=await $i(e.browserContext,e.page,{selector:t.selector,type:t.type,attributeName:t.attributeName});return{id:n.id,selector:n.selector,type:n.type,attributeName:n.attributeName,nodeId:n.nodeId,message:`Dompoint set on "${t.selector}" for ${t.type}`}}};import{z as vs}from"zod";var No=class{static{s(this,"RemoveDompoint")}name(){return"debug_remove-dompoint"}description(){return"Removes a dompoint by its ID."}inputSchema(){return{id:vs.string().describe("Dompoint ID to remove")}}outputSchema(){return{success:vs.boolean().describe("Whether the dompoint was removed"),message:vs.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{success:!1,message:"No active dompoints"};let n=await ps(e.browserContext,t.id,e.page);return{success:n,message:n?`Dompoint ${t.id} removed`:`Dompoint ${t.id} not found`}}};import{z as lt}from"zod";var Po=class{static{s(this,"ListDompoints")}name(){return"debug_list-dompoints"}description(){return"Lists all active dompoints."}inputSchema(){return{}}outputSchema(){return{dompoints:lt.array(lt.object({id:lt.string(),selector:lt.string(),type:lt.string(),attributeName:lt.string().optional(),enabled:lt.boolean(),hitCount:lt.number(),lastHitAt:lt.number().optional()})).describe("List of dompoints"),total:lt.number().describe("Total count")}}async handle(e,t){if(!N(e.browserContext))return{dompoints:[],total:0};let r=It(e.browserContext).map(i=>({id:i.id,selector:i.selector,type:i.type,attributeName:i.attributeName,enabled:i.enabled,hitCount:i.hitCount,lastHitAt:i.lastHitAt}));return{dompoints:r,total:r.length}}};import{z as ra}from"zod";var ko=class{static{s(this,"ClearDompoints")}name(){return"debug_clear-dompoints"}description(){return"Removes all dompoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:ra.number().describe("Number of dompoints cleared"),message:ra.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No dompoints to clear"};let n=await zi(e.browserContext,e.page);return{clearedCount:n,message:`Cleared ${n} dompoint(s)`}}};import{z as ut}from"zod";var Ro=class{static{s(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:ut.string().describe("Glob pattern to match request URLs"),method:ut.string().describe("HTTP method filter (GET, POST, PUT, DELETE, etc.)").optional(),timing:ut.enum(["request","response"]).describe('When to trigger: "request" or "response". Default: "request"').optional().default("request"),onError:ut.boolean().describe("Only trigger on error responses (4xx, 5xx)").optional()}}outputSchema(){return{id:ut.string().describe("Netpoint ID"),urlPattern:ut.string().describe("URL pattern"),method:ut.string().optional().describe("HTTP method filter"),timing:ut.string().describe("Trigger timing"),onError:ut.boolean().optional().describe("Error-only filter"),message:ut.string().describe("Status message")}}async handle(e,t){N(e.browserContext)||await He(e.browserContext,e.page);let n=await Vi(e.browserContext,e.page,{urlPattern:t.urlPattern,method:t.method,timing:t.timing||"request",onError:t.onError});return{id:n.id,urlPattern:n.urlPattern,method:n.method,timing:n.timing,onError:n.onError,message:`Netpoint set for ${t.urlPattern} on ${t.timing||"request"}`}}};import{z as Is}from"zod";var _o=class{static{s(this,"RemoveNetpoint")}name(){return"debug_remove-netpoint"}description(){return"Removes a netpoint by its ID."}inputSchema(){return{id:Is.string().describe("Netpoint ID to remove")}}outputSchema(){return{success:Is.boolean().describe("Whether the netpoint was removed"),message:Is.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{success:!1,message:"No active netpoints"};let n=Gi(e.browserContext,t.id);return{success:n,message:n?`Netpoint ${t.id} removed`:`Netpoint ${t.id} not found`}}};import{z as Ye}from"zod";var Mo=class{static{s(this,"ListNetpoints")}name(){return"debug_list-netpoints"}description(){return"Lists all active netpoints."}inputSchema(){return{}}outputSchema(){return{netpoints:Ye.array(Ye.object({id:Ye.string(),urlPattern:Ye.string(),method:Ye.string().optional(),timing:Ye.string(),onError:Ye.boolean().optional(),enabled:Ye.boolean(),hitCount:Ye.number(),lastHitAt:Ye.number().optional()})).describe("List of netpoints"),total:Ye.number().describe("Total count")}}async handle(e,t){if(!N(e.browserContext))return{netpoints:[],total:0};let r=Ct(e.browserContext).map(i=>({id:i.id,urlPattern:i.urlPattern,method:i.method,timing:i.timing,onError:i.onError,enabled:i.enabled,hitCount:i.hitCount,lastHitAt:i.lastHitAt}));return{netpoints:r,total:r.length}}};import{z as sa}from"zod";var Do=class{static{s(this,"ClearNetpoints")}name(){return"debug_clear-netpoints"}description(){return"Removes all netpoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:sa.number().describe("Number of netpoints cleared"),message:sa.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No netpoints to clear"};let n=Ki(e.browserContext);return{clearedCount:n,message:`Cleared ${n} netpoint(s)`}}};var ia=[new Qn,new Zn,new eo,new to,new no,new oo,new ro,new so,new io,new ao,new uo,new co,new mo,new po,new bo,new ho,new fo,new yo,new wo,new To,new So,new vo,new Io,new Co,new Eo,new Oo,new No,new Po,new ko,new Ro,new _o,new Mo,new Do];import Cs from"sharp";import su from"ssim.js";var iu=!1,au=10;function lu(o){return Number.isFinite(o)?Math.max(0,Math.min(1,o)):0}s(lu,"_clamp01");async function aa(o,e,t,n){let r;if(n==="semantic"){r=Cs(o).resize(e,t,{fit:"cover",position:"centre"});let l=Math.max(1,Math.floor(e/2)),u=Math.max(1,Math.floor(t/2));r=r.resize(l,u,{fit:"cover",position:"centre"}).grayscale(iu).blur(au)}else r=Cs(o).resize(e,t,{fit:"cover",position:"centre"});let i=await r.ensureAlpha().raw().toBuffer({resolveWithObject:!0});return{data:new Uint8ClampedArray(i.data.buffer,i.data.byteOffset,i.data.byteLength),width:i.info.width,height:i.info.height}}s(aa,"_loadNormalized");function uu(o,e){let t=su({data:o.data,width:o.width,height:o.height},{data:e.data,width:e.width,height:e.height}),n=Number(t.mssim??t.ssim??0);return lu(n)}s(uu,"_computeSsim");async function la(o,e,t){let n=t?.mode??"semantic",r=t?.canvasWidth,i=t?.canvasHeight;if(typeof r!="number"||!Number.isFinite(r)||r<=0||typeof i!="number"||!Number.isFinite(i)||i<=0){let m=await Cs(e.image).metadata();if(r=m.width??0,i=m.height??0,r<=0||i<=0)throw new Error("Failed to read Figma image dimensions.")}let a=await aa(e.image,r,i,n),l=await aa(o.image,r,i,n);return{score:uu(a,l)}}s(la,"compare");function ua(o,e){let t=Math.min(o.length,e.length),n=0;for(let r=0;r<t;r++)n+=o[r]*e[r];return n}s(ua,"dot");function Es(o){let e=0;for(let t=0;t<o.length;t++){let n=o[t];e+=n*n}return Math.sqrt(e)}s(Es,"norm");function ca(o){let e=Es(o);if(e===0)return o.slice();let t=new Array(o.length);for(let n=0;n<o.length;n++)t[n]=o[n]/e;return t}s(ca,"l2Normalize");function Bo(o,e,t){if(t){let r=ca(o),i=ca(e);return ua(r,i)}let n=Es(o)*Es(e);return n===0?0:ua(o,e)/n}s(Bo,"cosineSimilarity");import{BedrockRuntimeClient as ma,InvokeModelCommand as cu}from"@aws-sdk/client-bedrock-runtime";import{fromIni as mu}from"@aws-sdk/credential-providers";import pu from"sharp";var du=1024,bu=90,gu=1024;async function hu(o,e,t){let n=pu(o),r=t?.maxDim||du;if(n=n.resize({width:r,height:r,fit:"inside",withoutEnlargement:!0}),e==="png")return await n.png().toBuffer();let i=t?.jpegQuality||bu;return await n.jpeg({quality:i}).toBuffer()}s(hu,"_prepareImage");var fu=new Set(["amazon.titan-embed-image-v1"]),yu="amazon.titan-embed-image-v1",tn;function wu(){return Dn&&!!Jt}s(wu,"_isAwsBedrockActive");function Tu(){if(tn)return tn;let o=Jt;if(!o)return;let e=Mn;return e?(tn=new ma({region:o,credentials:mu({profile:e})}),tn):(tn=new ma({region:o}),tn)}s(Tu,"_getOrCreateBedrockClient");async function Su(o,e,t,n){let i={inputImage:(await hu(o.image,o.type,t)).toString("base64"),embeddingConfig:{outputEmbeddingLength:gu}},a=new cu({modelId:n,contentType:"application/json",accept:"application/json",body:Buffer.from(JSON.stringify(i),"utf-8")}),l=await e.send(a),u=l?.body instanceof Uint8Array?l.body:new Uint8Array(l?.body??[]),m=Buffer.from(u).toString("utf-8"),c;try{c=m?JSON.parse(m):{}}catch{throw new Error(`Amazon Bedrock Titan returned non-JSON response for embeddings: ${m.slice(0,300)}`)}let p=c?.embedding??c?.embeddings?.[0]??c?.outputEmbedding??c?.vector;if(!Array.isArray(p)||p.length===0||typeof p[0]!="number")throw new Error(`Unexpected Amazon Bedrock Titan image embedding response format: ${m.slice(0,500)}`);return p}s(Su,"_embedImageWithAmazonBedrockTitan");async function xu(o,e,t){let n=e?.modelId??Qs??yu;if(!fu.has(n))throw new Error(`Unsupported Amazon Bedrock image embedding model id: ${n}`);return await Su(o,t,e,n)}s(xu,"_embedImageWithAmazonBedrock");async function pa(o,e){if(wu()){let t=Tu();return t?xu(o,e,t):void 0}}s(pa,"_embedImage");async function da(o,e,t){let n=typeof t?.normalize=="boolean"?t.normalize:!0,r=await pa(e,t);if(!r)return;let i=await pa(o,t);return i?{score:Bo(r,i,n)}:void 0}s(da,"compare");import{BedrockRuntimeClient as ba,InvokeModelCommand as vu}from"@aws-sdk/client-bedrock-runtime";import{fromIni as Iu}from"@aws-sdk/credential-providers";import Cu from"sharp";var Eu=`
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 Ou(o){return o?.prompt??Eu.trim()}s(Ou,"_resolvePrompt");function Nu(o){return typeof o?.maxDim=="number"&&o.maxDim>0?Math.floor(o.maxDim):1024}s(Nu,"_resolveMaxDim");function Pu(o){return o?.imageFormat==="jpeg"?"jpeg":"png"}s(Pu,"_resolveImageFormat");function ku(o){let e=o?.jpegQuality;return typeof e=="number"&&e>=50&&e<=100?Math.floor(e):90}s(ku,"_resolveJpegQuality");async function Ru(o,e){let t=Nu(e),n=Pu(e),r=ku(e),i=Cu(o).resize({width:t,height:t,fit:"inside",withoutEnlargement:!0}),a,l;return n==="png"?(a=await i.png().toBuffer(),l="image/png"):(a=await i.jpeg({quality:r}).toBuffer(),l="image/jpeg"),{bytes:a,mimeType:l}}s(Ru,"_preprocessImage");var _u=new Set(["amazon.titan-embed-text-v2:0"]),Mu="amazon.titan-embed-text-v2:0",Du=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"]),Bu="anthropic.claude-3-sonnet-20240229-v1:0",nn;function fa(){return Dn&&!!Jt}s(fa,"_isAwsBedrockActive");function ya(){if(nn)return nn;let o=Jt;if(!o)return;let e=Mn;return e?(nn=new ba({region:o,credentials:Iu({profile:e})}),nn):(nn=new ba({region:o}),nn)}s(ya,"_getOrCreateBedrockClient");async function wa(o,e,t){let n=new vu({modelId:e,contentType:"application/json",accept:"application/json",body:Buffer.from(JSON.stringify(t))}),r=await o.send(n),i=Buffer.from(r.body).toString("utf-8");return JSON.parse(i)}s(wa,"_invokeBedrock");async function Au(o,e,t,n){let{bytes:r,mimeType:i}=await Ru(o.image,e),l={anthropic_version:"bedrock-2023-05-31",max_tokens:1e4,temperature:0,messages:[{role:"user",content:[{type:"text",text:Ou(e)},{type:"image",source:{type:"base64",media_type:i,data:r.toString("base64")}}]}]},u=await wa(t,n,l),m=u?.content?.[0]?.text??u?.output_text??u?.completion;if(!m||!m.trim())throw new Error("Amazon Bedrock Claude returned empty description.");return m.trim()}s(Au,"_describeUIWithAmazonBedrockClaude");async function Lu(o,e,t){let i=(await wa(e,t,{inputText:o}))?.embedding;if(!Array.isArray(i)||typeof i[0]!="number")throw new Error("Unexpected embedding response for Amazon Bedrock Titan text embedding.");return i}s(Lu,"_embedTextWithAmazonBedrockTitan");async function Fu(o,e,t){let n=e?.visionModelId??ei??Bu;if(!Du.has(n))throw new Error(`Unsupported Amazon Bedrock vision model id: ${n}`);return await Au(o,e,t,n)}s(Fu,"_describeUIWithAmazonBedrock");async function Uu(o,e,t){let n=e?.textEmbedModelId??Zs??Mu;if(!_u.has(n))throw new Error(`Unsupported Amazon Bedrock text embedding model id: ${n}`);return await Lu(o,t,n)}s(Uu,"_embedTextWithAmazonBedrock");async function ga(o,e){if(fa()){let t=ya();return t?Fu(o,e,t):void 0}}s(ga,"_describeUI");async function ha(o,e){if(fa()){let t=ya();return t?Uu(o,e,t):void 0}}s(ha,"_embedTextVector");async function Ta(o,e,t){let n=typeof t?.normalize=="boolean"?t.normalize:!0,r=await ga(e,t);if(!r)return;let i=await ga(o,t);if(!i)return;let a=await ha(r,t);if(!a)return;let l=await ha(i,t);return l?{score:Bo(a,l,n)}:void 0}s(Ta,"compare");var Hu=.25,Wu=.5,qu=.25;function Ao(o){return Number.isFinite(o)?Math.max(0,Math.min(1,o)):0}s(Ao,"_clamp01");function Os(o,e){return typeof o=="number"&&Number.isFinite(o)&&o>0?o:e}s(Os,"_weightOrDefault");async function Sa(o,e,t){let n=[],r=Os(t?.weights?.mssim,Hu),i=Os(t?.weights?.vectorEmbedding,Wu),a=Os(t?.weights?.textEmbedding,qu),l=await la(o,e,t?.mssim),u=Ao(l.score);n.push(`mssim=${u.toFixed(5)}`);let m;try{let P=await da(o,e,t?.imageEmbedding);P&&typeof P.score=="number"?(m=Ao(P.score),n.push(`image-embedding=${m.toFixed(5)}`)):n.push("image-embedding=skipped (inactive)")}catch(P){n.push(`image-embedding=skipped (${P instanceof Error?P.message:String(P)})`)}let c;try{let P=await Ta(o,e,t?.textEmbedding);P&&typeof P.score=="number"?(c=Ao(P.score),n.push(`text-embedding=${c.toFixed(5)}`)):n.push("text-embedding=skipped (inactive)")}catch(P){n.push(`text-embedding=skipped (${P instanceof Error?P.message:String(P)})`)}let p=[{name:"mssim",score:u,weight:r}];typeof m=="number"&&p.push({name:"image-embedding",score:m,weight:i}),typeof c=="number"&&p.push({name:"text-embedding",score:c,weight:a});let g=p.reduce((P,T)=>P+T.weight,0),f=g>0?p.reduce((P,T)=>P+T.score*(T.weight/g),0):0,y=Ao(f);return n.push(`combined=${y.toFixed(5)} (signals=${p.map(P=>P.name).join(", ")})`),{score:y,notes:n}}s(Sa,"compareWithNotes");import ju from"node:crypto";function $u(){let o=ti;if(!o)throw new Error("No Figma access token configured");return o}s($u,"_requireFigmaToken");function zu(o){return o==="jpg"?{mimeType:"image/jpeg",type:"jpeg"}:{mimeType:"image/png",type:"png"}}s(zu,"_mimeTypeFor");function Vu(o){let e=ju.createHash("sha256");return e.update(o.fileKey),e.update("|"),e.update(o.nodeId),e.update("|"),e.update(o.format??"png"),e.update("|"),e.update(String(o.scale??2)),e.digest("hex").slice(0,24)}s(Vu,"_buildCacheKey");async function Gu(o,e){let t=await fetch(o,{method:"GET",headers:{"X-Figma-Token":e,Accept:"application/json"}}),n=await t.text(),r;try{r=n?JSON.parse(n):{}}catch{throw new Error(`Figma API returned non-JSON response (status=${t.status}). Body: ${n.slice(0,500)}`)}if(!t.ok){let i=typeof r?.err=="string"?r.err:`Figma API error (status=${t.status})`;throw new Error(i)}return r}s(Gu,"_fetchJson");async function Ku(o){let e=await fetch(o,{method:"GET"});if(!e.ok){let n=await e.text().catch(()=>"");throw new Error(`Failed to download Figma rendered image (status=${e.status}): ${n.slice(0,300)}`)}let t=await e.arrayBuffer();return Buffer.from(t)}s(Ku,"_fetchBinary");async function xa(o){let e=$u(),t=o.format??"png",n=typeof o.scale=="number"&&o.scale>0?o.scale:2,{mimeType:r,type:i}=zu(t),a=ni,l=o.fileKey,u=o.nodeId,m=`${a}/images/${encodeURIComponent(l)}?ids=${encodeURIComponent(u)}&format=${encodeURIComponent(t)}&scale=${encodeURIComponent(String(n))}`,c=await Gu(m,e),p=c.images?.[u];if(!p){let P=typeof c.err=="string"&&c.err.trim()?c.err:"Figma did not return an image URL for the given nodeId.";throw new Error(P)}let g=await Ku(p),f=Vu(o),y={image:g,mimeType:r,type:i,cacheKey:f};return o.includeId===!0&&(y.nodeId=u,y.fileKey=l),y}s(xa,"getFigmaDesignScreenshot");import{z as be}from"zod";var va="png",Xu=!0,Ia="semantic",Lo=class{static{s(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:be.string().min(1).describe("Figma file key (the part after /file/ in Figma URL)."),figmaNodeId:be.string().min(1).describe('Figma node id to render (frame/component node id like "12:34").'),selector:be.string().optional().describe("Optional CSS selector to compare only a specific region of the page."),fullPage:be.boolean().optional().default(Xu).describe("If true, captures the full scrollable page. Ignored when selector is provided."),figmaScale:be.number().int().positive().optional().describe("Optional scale factor for Figma raster export (e.g. 1, 2, 3)."),figmaFormat:be.enum(["png","jpg"]).optional().describe("Optional raster format for Figma snapshot."),weights:be.object({mssim:be.number().positive().optional().describe("Weight for MSSIM signal."),imageEmbedding:be.number().positive().optional().describe("Weight for image embedding signal."),textEmbedding:be.number().positive().optional().describe("Weight for vision\u2192text\u2192text embedding signal.")}).optional().describe("Optional weights to combine signals. Only active signals participate."),mssimMode:be.enum(["raw","semantic"]).optional().default(Ia).describe("MSSIM mode. semantic is more robust for real-data vs design-data comparisons."),maxDim:be.number().int().positive().optional().describe("Optional preprocessing max dimension forwarded to compare pipeline."),jpegQuality:be.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:be.number().describe("Combined similarity score in the range [0..1]. Higher means more similar."),notes:be.array(be.string()).describe("Human-readable notes explaining which signals were used and their individual scores."),meta:be.object({pageUrl:be.string().describe("URL of the page that was compared."),pageTitle:be.string().describe("Title of the page that was compared."),figmaFileKey:be.string().describe("Figma file key used for the design snapshot."),figmaNodeId:be.string().describe("Figma node id used for the design snapshot."),selector:be.string().nullable().describe("Selector used for page screenshot, if any. Null means full page."),fullPage:be.boolean().describe("Whether the page screenshot was full-page."),pageImageType:be.enum(["png","jpeg"]).describe("Image type of the captured page screenshot."),figmaImageType:be.enum(["png","jpeg"]).describe("Image type of the captured Figma snapshot.")}).describe("Metadata about what was compared.")}}async handle(e,t){let n=String(e.page.url()),r=String(await e.page.title()),i=t.figmaFormat??"png",a=typeof t.figmaScale=="number"?t.figmaScale:void 0,l=await xa({fileKey:t.figmaFileKey,nodeId:t.figmaNodeId,format:i,scale:a}),u;if(typeof t.selector=="string"&&t.selector.trim()){let g=t.selector.trim(),f=e.page.locator(g);if(await f.count()===0)throw new Error(`Element not found for selector: ${g}`);u=await f.first().screenshot({type:va})}else{let g=t.fullPage!==!1;u=await e.page.screenshot({type:va,fullPage:g})}let m={image:u,type:"png",name:"page"},c={image:l.image,type:l.type==="jpeg"?"jpeg":"png",name:"figma"},p=await Sa(m,c,{weights:t.weights?{mssim:t.weights.mssim,vectorEmbedding:t.weights.imageEmbedding,textEmbedding:t.weights.textEmbedding}:void 0,mssim:{mode:t.mssimMode??Ia},imageEmbedding:{maxDim:t.maxDim,jpegQuality:typeof t.jpegQuality=="number"?t.jpegQuality:void 0},textEmbedding:{maxDim:t.maxDim,jpegQuality:typeof t.jpegQuality=="number"?t.jpegQuality:void 0}});return{score:p.score,notes:p.notes,meta:{pageUrl:n,pageTitle:r,figmaFileKey:t.figmaFileKey,figmaNodeId:t.figmaNodeId,selector:typeof t.selector=="string"&&t.selector.trim()?t.selector.trim():null,fullPage:typeof t.selector=="string"&&t.selector.trim()?!1:t.fullPage!==!1,pageImageType:"png",figmaImageType:l.type}}}};var Ca=[new Lo];import{z as Ea}from"zod";var Yu=1e4,Fo=class{static{s(this,"Click")}name(){return"interaction_click"}description(){return"Clicks an element on the page."}inputSchema(){return{selector:Ea.string().describe("CSS selector for the element to click."),timeoutMs:Ea.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(e,t){let n=t.timeoutMs??Yu;return await(await e.page.waitForSelector(t.selector,{state:"visible",timeout:n})).click(),{}}};import{z as Ns}from"zod";var Ju=1e4,Uo=class{static{s(this,"Drag")}name(){return"interaction_drag"}description(){return"Drags an element to a target location."}inputSchema(){return{sourceSelector:Ns.string().describe("CSS selector for the element to drag."),targetSelector:Ns.string().describe("CSS selector for the target location."),timeoutMs:Ns.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(e,t){let n=t.timeoutMs??Ju,r=await e.page.waitForSelector(t.sourceSelector,{state:"visible",timeout:n}),i=await e.page.waitForSelector(t.targetSelector,{state:"visible",timeout:n}),a=await r.boundingBox(),l=await i.boundingBox();if(!a||!l)throw new Error("Could not get element positions for drag operation");return await e.page.mouse.move(a.x+a.width/2,a.y+a.height/2),await e.page.mouse.down(),await e.page.mouse.move(l.x+l.width/2,l.y+l.height/2),await e.page.mouse.up(),{}}};import{z as Ps}from"zod";var Qu=1e4,Ho=class{static{s(this,"Fill")}name(){return"interaction_fill"}description(){return"Fills out an input field."}inputSchema(){return{selector:Ps.string().describe("CSS selector for the input field."),value:Ps.string().describe("Value to fill."),timeoutMs:Ps.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(e,t){let n=t.timeoutMs??Qu;return await(await e.page.waitForSelector(t.selector,{state:"visible",timeout:n})).fill(t.value),{}}};import{z as Oa}from"zod";var Zu=1e4,Wo=class{static{s(this,"Hover")}name(){return"interaction_hover"}description(){return"Hovers an element on the page."}inputSchema(){return{selector:Oa.string().describe("CSS selector for the element to hover."),timeoutMs:Oa.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(e,t){let n=t.timeoutMs??Zu;return await(await e.page.waitForSelector(t.selector,{state:"visible",timeout:n})).hover(),{}}};import{z as on}from"zod";var Na=50,Pa=10,ec=1e4,qo=class{static{s(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:on.string().describe('Keyboard key to press (e.g. "Enter", "ArrowDown", "a").'),selector:on.string().describe("Optional CSS selector to focus before sending the key.").optional(),holdMs:on.number().int().min(0).describe("Optional duration in milliseconds to hold the key. With repeat=true, this is the total repeat duration.").optional(),repeat:on.boolean().optional().default(!1).describe("If true, simulates key auto-repeat by pressing the key repeatedly (useful for scrolling)."),repeatIntervalMs:on.number().int().min(Pa).optional().default(Na).describe("Interval between repeated key presses in ms (only when repeat=true)."),timeoutMs:on.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(e,t){if(t.selector){let l=t.timeoutMs??ec;await(await e.page.waitForSelector(t.selector,{state:"visible",timeout:l})).focus()}let n=t.holdMs??0,r=t.repeat===!0;if(n<=0||r===!1)return await e.page.keyboard.press(t.key,n>0?{delay:n}:void 0),{};let i=typeof t.repeatIntervalMs=="number"&&Number.isFinite(t.repeatIntervalMs)&&t.repeatIntervalMs>=Pa?Math.floor(t.repeatIntervalMs):Na,a=Date.now();for(;Date.now()-a<n;)await e.page.keyboard.press(t.key),await e.page.waitForTimeout(i);return{}}};import{z as Je}from"zod";var tc=200,nc=200,jo=class{static{s(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:Je.number().int().min(tc).describe("Target viewport width in CSS pixels."),height:Je.number().int().min(nc).describe("Target viewport height in CSS pixels.")}}outputSchema(){return{requested:Je.object({width:Je.number().int().describe("Requested viewport width (CSS pixels)."),height:Je.number().int().describe("Requested viewport height (CSS pixels).")}).describe("Requested viewport configuration."),viewport:Je.object({innerWidth:Je.number().int().describe("window.innerWidth after resize (CSS pixels)."),innerHeight:Je.number().int().describe("window.innerHeight after resize (CSS pixels)."),outerWidth:Je.number().int().describe("window.outerWidth after resize (CSS pixels)."),outerHeight:Je.number().int().describe("window.outerHeight after resize (CSS pixels)."),devicePixelRatio:Je.number().describe("window.devicePixelRatio after resize.")}).describe("Viewport metrics observed inside the page after resizing.")}}async handle(e,t){await e.page.setViewportSize({width:t.width,height:t.height});let n=await e.page.evaluate(()=>({innerWidth:window.innerWidth,innerHeight:window.innerHeight,outerWidth:window.outerWidth,outerHeight:window.outerHeight,devicePixelRatio:window.devicePixelRatio}));return{requested:{width:t.width,height:t.height},viewport:{innerWidth:Number(n.innerWidth),innerHeight:Number(n.innerHeight),outerWidth:Number(n.outerWidth),outerHeight:Number(n.outerHeight),devicePixelRatio:Number(n.devicePixelRatio)}}}};import{z as ue}from"zod";var oc=200,rc=200,$o=class{static{s(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:ue.number().int().min(oc).optional().describe('Target window width in pixels (required when state="normal").'),height:ue.number().int().min(rc).optional().describe('Target window height in pixels (required when state="normal").'),state:ue.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:ue.object({width:ue.number().int().nullable().describe("Requested window width (pixels). Null if not provided."),height:ue.number().int().nullable().describe("Requested window height (pixels). Null if not provided."),state:ue.enum(["normal","maximized","minimized","fullscreen"]).describe("Requested window state.")}).describe("Requested window change parameters."),before:ue.object({windowId:ue.number().int().describe("CDP window id for the current target."),state:ue.string().nullable().describe("Window state before resizing."),left:ue.number().int().nullable().describe("Window left position before resizing."),top:ue.number().int().nullable().describe("Window top position before resizing."),width:ue.number().int().nullable().describe("Window width before resizing."),height:ue.number().int().nullable().describe("Window height before resizing.")}).describe("Window bounds before resizing."),after:ue.object({windowId:ue.number().int().describe("CDP window id for the current target."),state:ue.string().nullable().describe("Window state after resizing."),left:ue.number().int().nullable().describe("Window left position after resizing."),top:ue.number().int().nullable().describe("Window top position after resizing."),width:ue.number().int().nullable().describe("Window width after resizing."),height:ue.number().int().nullable().describe("Window height after resizing.")}).describe("Window bounds after resizing."),viewport:ue.object({innerWidth:ue.number().int().describe("window.innerWidth after resizing (CSS pixels)."),innerHeight:ue.number().int().describe("window.innerHeight after resizing (CSS pixels)."),outerWidth:ue.number().int().describe("window.outerWidth after resizing (CSS pixels)."),outerHeight:ue.number().int().describe("window.outerHeight after resizing (CSS pixels)."),devicePixelRatio:ue.number().describe("window.devicePixelRatio after resizing.")}).describe("Page viewport metrics after resizing (helps verify responsive behavior).")}}async handle(e,t){let n=t.state??"normal",r=t.width,i=t.height;if(n==="normal"&&(typeof r!="number"||typeof i!="number"))throw new Error('state="normal" requires both width and height.');let a=e.page,l=await a.context().newCDPSession(a);try{let u=await l.send("Browser.getWindowForTarget",{}),m=Number(u.windowId),c=u.bounds??{},p={windowId:m,state:typeof c.windowState=="string"?c.windowState:null,left:typeof c.left=="number"?c.left:null,top:typeof c.top=="number"?c.top:null,width:typeof c.width=="number"?c.width:null,height:typeof c.height=="number"?c.height:null},g={};n!=="normal"?g.windowState=n:(g.windowState="normal",g.width=r,g.height=i),await l.send("Browser.setWindowBounds",{windowId:m,bounds:g});let y=(await l.send("Browser.getWindowForTarget",{})).bounds??{},P={windowId:m,state:typeof y.windowState=="string"?y.windowState:null,left:typeof y.left=="number"?y.left:null,top:typeof y.top=="number"?y.top:null,width:typeof y.width=="number"?y.width:null,height:typeof y.height=="number"?y.height:null},T=await a.evaluate(()=>({innerWidth:window.innerWidth,innerHeight:window.innerHeight,outerWidth:window.outerWidth,outerHeight:window.outerHeight,devicePixelRatio:window.devicePixelRatio})),W={innerWidth:Number(T.innerWidth),innerHeight:Number(T.innerHeight),outerWidth:Number(T.outerWidth),outerHeight:Number(T.outerHeight),devicePixelRatio:Number(T.devicePixelRatio)};return{requested:{width:typeof r=="number"?r:null,height:typeof i=="number"?i:null,state:n},before:p,after:P,viewport:W}}catch(u){let m=String(u?.message??u);throw new Error(`Failed to resize real browser window via CDP. This tool works best on Chromium-based browsers. Original error: ${m}`)}finally{await l.detach().catch(()=>{})}}};import{z as ks}from"zod";var sc=1e4,zo=class{static{s(this,"Select")}name(){return"interaction_select"}description(){return"Select an element on the page with the given value"}inputSchema(){return{selector:ks.string().describe("CSS selector for element to select."),value:ks.string().describe("Value to select."),timeoutMs:ks.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(e,t){let n=t.timeoutMs??sc;return await(await e.page.waitForSelector(t.selector,{state:"visible",timeout:n})).selectOption(t.value),{}}};import{z as te}from"zod";var ka="auto",Ra="by",Vo=class{static{s(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:te.enum(["by","to","top","bottom","left","right"]).optional().default(Ra).describe('Scroll mode. "by" uses dx/dy, "to" uses x/y, and top/bottom/left/right jump to edges.'),selector:te.string().optional().describe("Optional CSS selector for a scrollable container. If omitted, scrolls the document viewport."),dx:te.number().optional().describe('Horizontal scroll delta in pixels (used when mode="by"). Default: 0.'),dy:te.number().optional().describe('Vertical scroll delta in pixels (used when mode="by"). Default: 0.'),x:te.number().optional().describe('Absolute horizontal scroll position in pixels (used when mode="to").'),y:te.number().optional().describe('Absolute vertical scroll position in pixels (used when mode="to").'),behavior:te.enum(["auto","smooth"]).optional().default(ka).describe('Native scroll behavior. Use "auto" for deterministic automation.')}}outputSchema(){return{mode:te.enum(["by","to","top","bottom","left","right"]).describe("The scroll mode used."),selector:te.string().nullable().describe("The selector of the scroll container if provided; otherwise null (document viewport)."),behavior:te.enum(["auto","smooth"]).describe("The scroll behavior used."),before:te.object({x:te.number().describe("ScrollLeft before scrolling."),y:te.number().describe("ScrollTop before scrolling."),scrollWidth:te.number().describe("Total scrollable width before scrolling."),scrollHeight:te.number().describe("Total scrollable height before scrolling."),clientWidth:te.number().describe("Viewport/container client width before scrolling."),clientHeight:te.number().describe("Viewport/container client height before scrolling.")}).describe("Scroll metrics before the scroll action."),after:te.object({x:te.number().describe("ScrollLeft after scrolling."),y:te.number().describe("ScrollTop after scrolling."),scrollWidth:te.number().describe("Total scrollable width after scrolling."),scrollHeight:te.number().describe("Total scrollable height after scrolling."),clientWidth:te.number().describe("Viewport/container client width after scrolling."),clientHeight:te.number().describe("Viewport/container client height after scrolling.")}).describe("Scroll metrics after the scroll action."),canScrollX:te.boolean().describe("Whether horizontal scrolling is possible (scrollWidth > clientWidth)."),canScrollY:te.boolean().describe("Whether vertical scrolling is possible (scrollHeight > clientHeight)."),maxScrollX:te.number().describe("Maximum horizontal scrollLeft (scrollWidth - clientWidth)."),maxScrollY:te.number().describe("Maximum vertical scrollTop (scrollHeight - clientHeight)."),isAtLeft:te.boolean().describe("Whether the scroll position is at the far left."),isAtRight:te.boolean().describe("Whether the scroll position is at the far right."),isAtTop:te.boolean().describe("Whether the scroll position is at the very top."),isAtBottom:te.boolean().describe("Whether the scroll position is at the very bottom.")}}async handle(e,t){let n=t.mode??Ra,r=t.selector,i=t.behavior??ka,a=t.dx??0,l=t.dy??0,u=t.x,m=t.y;if(n==="to"&&typeof u!="number"&&typeof m!="number")throw new Error('mode="to" requires at least one of x or y.');if(n==="by"&&a===0&&l===0)throw new Error('mode="by" requires dx and/or dy to be non-zero.');let c=await e.page.evaluate(p=>{let g=s((v,le)=>v[le],"g"),f=g(p,"modeEval"),y=g(p,"selectorEval"),P=g(p,"dxEval"),T=g(p,"dyEval"),W=g(p,"xEval"),K=g(p,"yEval"),M=g(p,"behaviorEval"),D=s(()=>{if(y){let le=document.querySelector(y);if(!le)throw new Error(`Element with selector "${y}" not found`);return le}let v=document.scrollingElement||document.documentElement||document.body;if(!v)throw new Error("No scrolling element available.");return v},"getTarget"),$=s(v=>({x:v.scrollLeft,y:v.scrollTop,scrollWidth:v.scrollWidth,scrollHeight:v.scrollHeight,clientWidth:v.clientWidth,clientHeight:v.clientHeight}),"readMetrics"),A=s((v,le,X)=>v<le?le:v>X?X:v,"clamp"),_=s(v=>{let le=Math.max(0,v.scrollWidth-v.clientWidth),X=Math.max(0,v.scrollHeight-v.clientHeight);if(f==="by"){let H=A(v.scrollLeft+P,0,le),Y=A(v.scrollTop+T,0,X);v.scrollTo({left:H,top:Y,behavior:M});return}if(f==="to"){let H=typeof W=="number"?A(W,0,le):v.scrollLeft,Y=typeof K=="number"?A(K,0,X):v.scrollTop;v.scrollTo({left:H,top:Y,behavior:M});return}if(f==="top"){v.scrollTo({top:0,left:v.scrollLeft,behavior:M});return}if(f==="bottom"){v.scrollTo({top:X,left:v.scrollLeft,behavior:M});return}if(f==="left"){v.scrollTo({left:0,top:v.scrollTop,behavior:M});return}if(f==="right"){v.scrollTo({left:le,top:v.scrollTop,behavior:M});return}},"doScroll"),Q=D(),q=$(Q);_(Q);let z=$(Q),ee=Math.max(0,z.scrollWidth-z.clientWidth),B=Math.max(0,z.scrollHeight-z.clientHeight),V=z.scrollWidth>z.clientWidth,Te=z.scrollHeight>z.clientHeight,ae=1,ne=z.x<=ae,oe=z.x>=ee-ae,pe=z.y<=ae,Ie=z.y>=B-ae;return{before:q,after:z,canScrollX:V,canScrollY:Te,maxScrollX:ee,maxScrollY:B,isAtLeft:ne,isAtRight:oe,isAtTop:pe,isAtBottom:Ie}},Object.fromEntries([["modeEval",n],["selectorEval",r],["dxEval",a],["dyEval",l],["xEval",u],["yEval",m],["behaviorEval",i]]));return{mode:n,selector:r??null,behavior:i,before:c.before,after:c.after,canScrollX:c.canScrollX,canScrollY:c.canScrollY,maxScrollX:c.maxScrollX,maxScrollY:c.maxScrollY,isAtLeft:c.isAtLeft,isAtRight:c.isAtRight,isAtTop:c.isAtTop,isAtBottom:c.isAtBottom}}};var _a=[new Fo,new Uo,new Ho,new Wo,new qo,new jo,new $o,new zo,new Vo];import{z as rn}from"zod";var ic=0,ac="load",Go=class{static{s(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:rn.number().int().nonnegative().describe("Maximum operation time in milliseconds. Defaults to `0` - no timeout.").optional().default(ic),waitUntil:rn.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(ac)}}outputSchema(){return{url:rn.string().describe("Contains the URL of the navigated page.").optional(),status:rn.number().int().positive().describe("Contains the status code of the navigated page (e.g., 200 for a success).").optional(),statusText:rn.string().describe('Contains the status text of the navigated page (e.g. usually an "OK" for a success).').optional(),ok:rn.boolean().describe("Contains a boolean stating whether the navigated page was successful (status in the range 200-299) or not.").optional()}}async handle(e,t){let n=await e.page.goBack({timeout:t.timeout,waitUntil:t.waitUntil});return{url:n?.url(),status:n?.status(),statusText:n?.statusText(),ok:n?.ok()}}};import{z as sn}from"zod";var lc=0,uc="load",Ko=class{static{s(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:sn.number().int().nonnegative().describe("Maximum operation time in milliseconds. Defaults to `0` - no timeout.").optional().default(lc),waitUntil:sn.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(uc)}}outputSchema(){return{url:sn.string().describe("Contains the URL of the navigated page.").optional(),status:sn.number().int().positive().describe("Contains the status code of the navigated page (e.g., 200 for a success).").optional(),statusText:sn.string().describe('Contains the status text of the navigated page (e.g. usually an "OK" for a success).').optional(),ok:sn.boolean().describe("Contains a boolean stating whether the navigated page was successful (status in the range 200-299) or not.").optional()}}async handle(e,t){let n=await e.page.goForward({timeout:t.timeout,waitUntil:t.waitUntil});return{url:n?.url(),status:n?.status(),statusText:n?.statusText(),ok:n?.ok()}}};import{z as Wt}from"zod";var cc=0,mc="load",Xo=class{static{s(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:Wt.string().describe("URL to navigate page to. The url should include scheme, e.g. `http://`, `https://`."),timeout:Wt.number().int().nonnegative().describe("Maximum operation time in milliseconds. Defaults to `0` - no timeout.").optional().default(cc),waitUntil:Wt.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(mc)}}outputSchema(){return{url:Wt.string().describe("Contains the URL of the navigated page.").optional(),status:Wt.number().int().positive().describe("Contains the status code of the navigated page (e.g., 200 for a success).").optional(),statusText:Wt.string().describe('Contains the status text of the navigated page (e.g. usually an "OK" for a success).').optional(),ok:Wt.boolean().describe("Contains a boolean stating whether the navigated page was successful (status in the range 200-299) or not.").optional()}}async handle(e,t){let n=await e.page.goto(t.url,{timeout:t.timeout,waitUntil:t.waitUntil});return{url:n?.url(),status:n?.status(),statusText:n?.statusText(),ok:n?.ok()}}};import{z as an}from"zod";var pc=0,dc="load",Yo=class{static{s(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:an.number().int().nonnegative().describe("Maximum operation time in milliseconds. Defaults to `0` - no timeout.").optional().default(pc),waitUntil:an.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(dc)}}outputSchema(){return{url:an.string().describe("Contains the URL of the reloaded page.").optional(),status:an.number().int().positive().describe("Contains the status code of the reloaded page (e.g., 200 for a success).").optional(),statusText:an.string().describe('Contains the status text of the reloaded page (e.g. usually an "OK" for a success).').optional(),ok:an.boolean().describe("Contains a boolean stating whether the reloaded page was successful (status in the range 200-299) or not.").optional()}}async handle(e,t){let n=await e.page.reload({timeout:t.timeout,waitUntil:t.waitUntil});return{url:n?.url(),status:n?.status(),statusText:n?.statusText(),ok:n?.ok()}}};var Ma=[new Go,new Ko,new Xo,new Yo];import{z as Oe}from"zod";var Jo=class{static{s(this,"GetConsoleMessages")}name(){return"o11y_get-console-messages"}description(){return"Retrieves console messages/logs from the browser with filtering options."}inputSchema(){return{type:Oe.enum(ve(dt)).transform(st(dt)).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): ${ve(dt)}.`).optional(),search:Oe.string().describe("Text to search for in console messages.").optional(),timestamp:Oe.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:Oe.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:Oe.object({count:Oe.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:Oe.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:Oe.array(Oe.object({type:Oe.string().describe("Type of the console message."),text:Oe.string().describe("Text of the console message."),location:Oe.object({url:Oe.string().describe("URL of the resource."),lineNumber:Oe.number().nonnegative().describe("0-based line number in the resource."),columnNumber:Oe.number().nonnegative().describe("0-based column number in the resource.")}).describe("Location of the console message in the resource.").optional(),timestamp:Oe.number().int().nonnegative().describe("Unix epoch timestamp (in milliseconds) of the console message."),sequenceNumber:Oe.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(e,t){let n=t.type?Qt[t.type]?.code:void 0,r=e.getConsoleMessages().filter(l=>{let u=!0;return n!==void 0&&(u=l.level.code>=n),u&&t.timestamp&&(u=l.timestamp>=t.timestamp),u&&t.sequenceNumber&&(u=l.sequenceNumber>t.sequenceNumber),u&&t.search&&(u=l.text.includes(t.search)),u});return{messages:(t.limit?.count?t.limit.from==="start"?r.slice(0,t.limit.count):r.slice(-t.limit.count):r).map(l=>({type:l.type,text:l.text,location:l.location?{url:l.location.url,lineNumber:l.location.lineNumber,columnNumber:l.location.columnNumber}:void 0,timestamp:l.timestamp,sequenceNumber:l.sequenceNumber}))}}};import{z as re}from"zod";var Qo=class{static{s(this,"GetHttpRequests")}name(){return"o11y_get-http-requests"}description(){return"Retrieves HTTP requests from the browser with filtering options."}inputSchema(){return{resourceType:re.enum(ve(Zt)).transform(st(Zt)).describe(`
583
- Resource type of the HTTP requests to retrieve.
584
- Valid values are: ${ve(Zt)}.`).optional(),status:re.object({min:re.number().int().positive().describe("Minimum status code of the HTTP requests to retrieve.").optional(),max:re.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:re.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:re.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:re.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:re.object({count:re.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:re.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:re.array(re.object({url:re.string().describe("HTTP request url."),method:re.enum(ve(is)).describe(`HTTP request method. Valid values are: ${ve(is)}`),headers:re.record(re.string(),re.string()).describe("HTTP request headers as key-value pairs."),body:re.string().describe("HTTP request body if available.").optional(),resourceType:re.enum(ve(Zt)).describe(`
602
- HTTP request resource type as it was perceived by the rendering engine.
603
- Valid values are: ${ve(Zt)}`),failure:re.string().describe("Error message of the HTTP request if failed.").optional(),duration:re.number().describe('HTTP request duration in milliseconds. "-1" if not available (no response).').optional(),response:re.object({status:re.number().int().positive().describe("HTTP response status code."),statusText:re.string().describe("HTTP response status text."),headers:re.record(re.string(),re.string()).describe("HTTP response headers as key-value pairs."),body:re.string().describe("HTTP response body if available.").optional()}).describe("HTTP response.").optional(),ok:re.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:re.number().int().nonnegative().describe("Unix epoch timestamp (in milliseconds) of the HTTP request."),sequenceNumber:re.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(e,t){let n=e.getHttpRequests().filter(a=>{let l=!0;return l&&t.resourceType&&(l=a.resourceType===t.resourceType),l&&t.status&&(l&&t.status.min&&(l=a.response?a.response.status>=t.status.min:!1),l&&t.status.max&&(l=a.response?a.response.status<=t.status.max:!1)),l&&t.ok!==void 0&&(l=a.ok),l&&t.timestamp&&(l=a.timestamp>=t.timestamp),l&&t.sequenceNumber&&(l=a.sequenceNumber>t.sequenceNumber),l});return{requests:(t.limit?.count?t.limit.from==="start"?n.slice(0,t.limit.count):n.slice(-t.limit.count):n).map(a=>({url:a.url,method:a.method,headers:a.headers,body:a.body,resourceType:a.resourceType,failure:a.failure,duration:a.duration,response:a.response?{status:a.response.status,statusText:a.response.statusText,headers:a.response.headers,body:a.response.body}:void 0,ok:a.ok,timestamp:a.timestamp,sequenceNumber:a.sequenceNumber}))}}};import{z as bc}from"zod";var Zo=class{static{s(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:bc.string().describe("The OpenTelemetry compatible trace id of the current session if available.").optional()}}async handle(e,t){return{traceId:await e.getTraceId()}}};import{z as j}from"zod";var Da=0,gc=3e4;function er(o,e,t){return typeof o!="number"||!Number.isFinite(o)?{rating:"not_available",value:null,unit:"ms",thresholds:{good:e,poor:t}}:o<=e?{rating:"good",value:o,unit:"ms",thresholds:{good:e,poor:t}}:o>t?{rating:"poor",value:o,unit:"ms",thresholds:{good:e,poor:t}}:{rating:"needs_improvement",value:o,unit:"ms",thresholds:{good:e,poor:t}}}s(er,"rateMs");function hc(o,e,t){return typeof o!="number"||!Number.isFinite(o)?{rating:"not_available",value:null,unit:"score",thresholds:{good:e,poor:t}}:o<=e?{rating:"good",value:o,unit:"score",thresholds:{good:e,poor:t}}:o>t?{rating:"poor",value:o,unit:"score",thresholds:{good:e,poor:t}}:{rating:"needs_improvement",value:o,unit:"score",thresholds:{good:e,poor:t}}}s(hc,"rateScore");function Rs(o){return o==="needs_improvement"?"needs improvement":o==="not_available"?"not available":o}s(Rs,"formatRating");function fc(o){let e=o.ratings.lcp.rating,t=o.ratings.inp.rating,n=o.ratings.cls.rating,r=o.ratings.ttfb.rating,i=o.ratings.fcp.rating,a=e==="good"&&t==="good"&&n==="good",l=[];a?l.push("Core Web Vitals look good (LCP, INP and CLS are all within recommended thresholds)."):l.push("Core Web Vitals need attention. Focus on the worst-rated metric first (LCP, INP, or CLS).");let u=[],m=[],c=[],p=[],g=[],f=[];return o.lcpSelectorHint&&f.push(`LCP element hint (best-effort): ${o.lcpSelectorHint}`),e==="poor"||e==="needs_improvement"?(u.push("Optimize the LCP element (often the hero image, headline, or main content above the fold)."),u.push("Reduce render-blocking resources (critical CSS, JS). Consider inlining critical CSS and deferring non-critical JS."),u.push('Preload the LCP resource (e.g., <link rel="preload"> for the hero image/font) and ensure it is discoverable without heavy JS.'),u.push("Improve server response and caching. A slow TTFB often delays LCP."),u.push("Avoid client-only rendering for above-the-fold content when possible; stream/SSR critical content.")):e==="good"?u.push("LCP is within the recommended threshold. Keep the above-the-fold path lean."):u.push("LCP is not available in this browser/session. Consider using Chromium or a page-load scenario that produces LCP entries."),t==="poor"||t==="needs_improvement"?(m.push("Break up long main-thread tasks. Aim to keep tasks under ~50ms (split work, yield to the event loop)."),m.push("Reduce expensive work in input handlers (click, pointer, key events). Move non-urgent work to idle time."),m.push("Avoid synchronous layout thrash during interactions (batch DOM reads/writes, reduce forced reflow)."),m.push("Defer heavy third-party scripts and reduce JavaScript bundle size to improve responsiveness.")):t==="good"?m.push("INP is within the recommended threshold. Keep interaction handlers lightweight."):m.push("INP is not available in this browser/session. It requires Event Timing support and user interactions."),n==="poor"||n==="needs_improvement"?(c.push("Reserve space for images/iframes/ads (set width/height or aspect-ratio) to prevent layout jumps."),c.push("Avoid inserting content above existing content unless it is in response to a user interaction."),c.push("Use stable font loading (font-display: swap/optional) and consider preloading critical fonts to reduce text shifts."),c.push("Be careful with late-loading banners/toasts; render them in reserved containers.")):n==="good"?c.push("CLS is within the recommended threshold. Keep layout stable during load and async updates."):c.push("CLS is not available in this browser/session. Consider Chromium or a scenario with visible layout changes."),r==="poor"||r==="needs_improvement"?(p.push("Improve backend latency: reduce server processing time, optimize DB queries, and eliminate unnecessary middleware."),p.push("Enable CDN/edge caching where possible. Use caching headers and avoid dynamic responses for static content."),p.push("Reduce cold-start and TLS overhead (keep-alive, warm pools, edge runtimes).")):r==="good"?p.push("TTFB is good. Backend/network latency is unlikely to be the primary bottleneck."):p.push("TTFB is not available in this browser/session."),i==="poor"||i==="needs_improvement"?(g.push("Reduce render-blocking CSS/JS and prioritize critical content for first paint."),g.push("Optimize above-the-fold resources and avoid large synchronous scripts during initial load."),g.push("Consider code-splitting and preloading critical assets to improve first paint.")):i==="good"?g.push("FCP is good. The page provides early visual feedback."):g.push("FCP is not available in this browser/session."),f.push("For reliable debugging, capture metrics after navigation and after user actions that trigger loading or layout changes."),f.push("If values look unstable, try adding waitMs (e.g., 1000-3000) and re-measure after the UI settles."),{coreWebVitalsPassed:a,summary:l,lcp:u,inp:m,cls:c,ttfb:p,fcp:g,general:f}}s(fc,"buildRecommendations");var tr=class{static{s(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:j.number().int().min(0).max(gc).optional().default(Da).describe("Optional wait duration in milliseconds before reading metrics (default: 0)."),includeDebug:j.boolean().optional().default(!1).describe("If true, returns additional debug details such as entry counts and LCP element hint.")}}outputSchema(){let e=j.object({rating:j.enum(["good","needs_improvement","poor","not_available"]).describe("Rating based on Google thresholds."),value:j.number().nullable().describe("Metric value (null if unavailable)."),unit:j.enum(["ms","score"]).describe("Unit of the metric."),thresholds:j.object({good:j.number().describe('Upper bound for the "good" rating.'),poor:j.number().describe('Lower bound for the "poor" rating.')}).describe("Thresholds used for rating.")});return{url:j.string().describe("Current page URL."),title:j.string().describe("Current page title."),timestampMs:j.number().int().describe("Unix epoch timestamp (ms) when the metrics were captured."),metrics:j.object({lcpMs:j.number().nullable().describe("Largest Contentful Paint in milliseconds."),inpMs:j.number().nullable().describe("Interaction to Next Paint in milliseconds (best-effort approximation)."),cls:j.number().nullable().describe("Cumulative Layout Shift score."),ttfbMs:j.number().nullable().describe("Time to First Byte in milliseconds."),fcpMs:j.number().nullable().describe("First Contentful Paint in milliseconds.")}).describe("Raw metric values (null if unavailable)."),ratings:j.object({lcp:e.describe("LCP rating."),inp:e.describe("INP rating."),cls:e.describe("CLS rating."),ttfb:e.describe("TTFB rating."),fcp:e.describe("FCP rating.")}).describe("Ratings computed from Google thresholds."),recommendations:j.object({coreWebVitalsPassed:j.boolean().describe('True if all Core Web Vitals are rated "good".'),summary:j.array(j.string()).describe("High-level summary and prioritization guidance."),lcp:j.array(j.string()).describe("Recommendations for improving LCP."),inp:j.array(j.string()).describe("Recommendations for improving INP."),cls:j.array(j.string()).describe("Recommendations for improving CLS."),ttfb:j.array(j.string()).describe("Recommendations for improving TTFB."),fcp:j.array(j.string()).describe("Recommendations for improving FCP."),general:j.array(j.string()).describe("General measurement and debugging notes.")}).describe("Recommendations based on the measured values and their ratings."),notes:j.array(j.string()).describe("Notes about metric availability, browser limitations, and interpretation."),debug:j.object({waitMs:j.number().int().describe("Actual wait duration used before reading metrics."),entries:j.object({navigation:j.number().int().describe("Count of navigation entries."),paint:j.number().int().describe("Count of paint entries."),lcp:j.number().int().describe("Count of largest-contentful-paint entries."),layoutShift:j.number().int().describe("Count of layout-shift entries."),eventTiming:j.number().int().describe("Count of event timing entries.")}).describe("Counts of PerformanceEntry types used to compute metrics."),lastLcpSelectorHint:j.string().nullable().describe("Best-effort selector hint for the last LCP element (if available)."),lastLcpTagName:j.string().nullable().describe("Tag name of the last LCP element (if available).")}).optional().describe("Optional debug details.")}}async handle(e,t){let n=t.waitMs??Da,r=t.includeDebug===!0,i=String(e.page.url()),a=String(await e.page.title()),l=Date.now(),u=await e.page.evaluate(async M=>{let D=s((H,Y)=>H[Y],"g"),$=D(M,"waitMsEval"),A=D(M,"includeDebugEval"),_=[],Q=s(H=>new Promise(Y=>{setTimeout(()=>Y(),H)}),"sleep");$>0&&await Q($);let q=null,z=performance.getEntriesByType("navigation")??[];if(z.length>0){let H=z[0];typeof H.responseStart=="number"&&H.responseStart>=0&&(q=H.responseStart)}else _.push("TTFB: navigation entries not available (older browser or restricted timing).");let ee=null,B=performance.getEntriesByType("paint")??[],V=B.find(H=>H.name==="first-contentful-paint");V&&typeof V.startTime=="number"?ee=V.startTime:_.push("FCP: paint entries not available (browser may not support Paint Timing).");let Te=null,ae=null,ne=performance.getEntriesByType("largest-contentful-paint")??[];if(ne.length>0){let H=ne[ne.length-1];typeof H.startTime=="number"&&(Te=H.startTime),H.element&&H.element instanceof Element&&(ae=H.element)}else _.push("LCP: largest-contentful-paint entries not available (requires LCP support).");let oe=s(H=>{if(!H)return null;let Y=H.getAttribute("data-testid")||H.getAttribute("data-test-id")||H.getAttribute("data-test");if(Y&&Y.trim())return'[data-testid="'+Y.replace(/"/g,'\\"')+'"]';let Pe=H.getAttribute("data-selector");if(Pe&&Pe.trim())return'[data-selector="'+Pe.replace(/"/g,'\\"')+'"]';if(H.id)try{return"#"+CSS.escape(H.id)}catch{return"#"+String(H.id)}return H.tagName?H.tagName.toLowerCase():null},"selectorHintFor"),pe=null,Ie=performance.getEntriesByType("layout-shift")??[];if(Ie.length>0){let H=0;for(let Y of Ie)Y&&Y.hadRecentInput===!0||typeof Y.value=="number"&&(H+=Y.value);pe=H}else _.push("CLS: layout-shift entries not available (requires Layout Instability API support).");let v=null,le=performance.getEntriesByType("event")??[];if(le.length>0){let H=0;for(let Y of le){let Pe=typeof Y.interactionId=="number"?Y.interactionId:0,_e=typeof Y.duration=="number"?Y.duration:0;Pe>0&&_e>H&&(H=_e)}H>0?v=H:_.push("INP: event timing entries exist but no interactionId-based events were found.")}else _.push("INP: event timing entries not available (requires Event Timing API support).");_.length===0?_.push("All requested metrics were available."):_.push("Some metrics may be null due to browser support limitations.");let X={metrics:{ttfbMs:q,fcpMs:ee,lcpMs:Te,cls:pe,inpMs:v},notes:_,lcp:{selectorHint:oe(ae),tagName:ae?String(ae.tagName).toLowerCase():null},debug:{waitMs:$,entries:{navigation:z.length,paint:B.length,lcp:ne.length,layoutShift:Ie.length,eventTiming:le.length}}};return A?(X.debug.lastLcpSelectorHint=X.lcp.selectorHint,X.debug.lastLcpTagName=X.lcp.tagName):delete X.debug,X},Object.fromEntries([["waitMsEval",n],["includeDebugEval",r]])),m=typeof u?.metrics?.lcpMs=="number"?u.metrics.lcpMs:null,c=typeof u?.metrics?.inpMs=="number"?u.metrics.inpMs:null,p=typeof u?.metrics?.cls=="number"?u.metrics.cls:null,g=typeof u?.metrics?.ttfbMs=="number"?u.metrics.ttfbMs:null,f=typeof u?.metrics?.fcpMs=="number"?u.metrics.fcpMs:null,y={lcp:er(m,2500,4e3),inp:er(c,200,500),cls:hc(p,.1,.25),ttfb:er(g,800,1800),fcp:er(f,1800,3e3)},P=typeof u?.lcp?.selectorHint=="string"?u.lcp.selectorHint:null,T=fc({ratings:y,lcpSelectorHint:P}),W=Array.isArray(u?.notes)?u.notes:[];W.push(`Ratings: LCP=${Rs(y.lcp.rating)}, INP=${Rs(y.inp.rating)}, CLS=${Rs(y.cls.rating)}.`);let K={url:i,title:a,timestampMs:l,metrics:{lcpMs:m,inpMs:c,cls:p,ttfbMs:g,fcpMs:f},ratings:y,recommendations:T,notes:W};return r&&u?.debug&&(K.debug=u.debug),K}};import yc from"node:crypto";function nr(){return yc.randomBytes(16).toString("hex")}s(nr,"newTraceId");import{z as wc}from"zod";var or=class{static{s(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:wc.string().describe("The generated new OpenTelemetry compatible trace id.")}}async handle(e,t){let n=nr();return await e.setTraceId(n),{traceId:n}}};import{z as Tc}from"zod";var rr=class{static{s(this,"SetTraceId")}name(){return"o11y_set-trace-id"}description(){return"Sets the OpenTelemetry compatible trace id of the current session."}inputSchema(){return{traceId:Tc.string().describe("The OpenTelemetry compatible trace id to be set.")}}outputSchema(){return{}}async handle(e,t){return await e.setTraceId(t.traceId),{}}};var Ba=[new Jo,new Qo,new Zo,new tr,new or,new rr];import{z as U}from"zod";var Aa=30,La=2e3,Fa=!0,Sc=25,xc=5e4,sr=class{static{s(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:U.string().optional().describe("CSS selector for the target element. If provided, takes precedence over x/y."),x:U.number().int().optional().describe("Viewport X coordinate in CSS pixels. Used when selector is not provided."),y:U.number().int().optional().describe("Viewport Y coordinate in CSS pixels. Used when selector is not provided."),maxStackDepth:U.number().int().positive().optional().default(Aa).describe("Maximum number of component frames to return in the component stack."),includePropsPreview:U.boolean().optional().default(Fa).describe("If true, includes a best-effort, truncated props preview for the nearest component."),maxPropsPreviewChars:U.number().int().positive().optional().default(La).describe("Maximum characters for props preview (after safe stringification).")}}outputSchema(){return{target:U.object({selector:U.string().nullable(),point:U.object({x:U.number().int().nullable(),y:U.number().int().nullable()}),found:U.boolean(),domHint:U.string().nullable(),elementPath:U.string().nullable()}),react:U.object({detected:U.boolean(),detectionReason:U.string(),fiberKey:U.string().nullable(),hostMapping:U.object({fiberOnTargetElement:U.boolean().describe("Whether the initial fiber pointer was found directly on the target element."),anchorDomHint:U.string().nullable().describe("DOM hint of the element where fiber pointer was found (target or ancestor)."),targetDomHint:U.string().nullable().describe("DOM hint of the actual target element."),hostFiberMatchedTarget:U.boolean().describe("Whether we found the exact host fiber for target element (fiber.stateNode === targetEl) via subtree scan."),subtreeScanNodesScanned:U.number().int().describe("Number of fiber nodes scanned during subtree search."),subtreeScanMaxNodes:U.number().int().describe("Maximum fiber nodes allowed to scan (safety cap)."),strategy:U.enum(["direct-on-target","ancestor-subtree-scan","ancestor-fallback"]).describe("Mapping strategy used to produce the final stack.")}),nearestComponent:U.object({name:U.string().nullable(),displayName:U.string().nullable(),kind:U.enum(["function","class","unknown"]),debugSource:U.object({fileName:U.string().optional(),lineNumber:U.number().int().optional(),columnNumber:U.number().int().optional()}).optional(),propsPreview:U.string().optional()}).nullable(),componentStack:U.array(U.object({name:U.string().nullable(),displayName:U.string().nullable(),kind:U.enum(["function","class","unknown"]),debugSource:U.object({fileName:U.string().optional(),lineNumber:U.number().int().optional(),columnNumber:U.number().int().optional()}).optional()})),componentStackText:U.string(),wrappersDetected:U.array(U.string()),wrapperFrames:U.array(U.object({wrapper:U.string(),frameIndex:U.number().int(),frameLabel:U.string()})),notes:U.array(U.string())})}}async handle(e,t){let n=typeof t.selector=="string"&&t.selector.trim()?t.selector.trim():void 0,r=typeof t.x=="number"&&Number.isFinite(t.x)?Math.floor(t.x):void 0,i=typeof t.y=="number"&&Number.isFinite(t.y)?Math.floor(t.y):void 0;if(!n&&(typeof r!="number"||typeof i!="number"))throw new Error("Provide either selector, or both x and y for elementFromPoint.");let a=typeof t.maxStackDepth=="number"&&t.maxStackDepth>0?Math.floor(t.maxStackDepth):Aa,l=t.includePropsPreview===void 0?Fa:t.includePropsPreview===!0,u=typeof t.maxPropsPreviewChars=="number"&&Number.isFinite(t.maxPropsPreviewChars)&&t.maxPropsPreviewChars>0?Math.floor(t.maxPropsPreviewChars):La;return await e.page.evaluate(c=>{let p=s((h,I)=>h[I],"g"),g=p(c,"selectorEval"),f=p(c,"xEval"),y=p(c,"yEval"),P=p(c,"maxStackDepthEval"),T=p(c,"includePropsPreviewEval"),W=p(c,"maxPropsPreviewCharsEval"),K=p(c,"maxElementPathDepthEval"),M=p(c,"maxFiberNodesToScanEval"),D=[];function $(h){if(!h)return null;let I=h.tagName.toLowerCase(),C=h.id&&h.id.trim()?"#"+h.id.trim():"",k=typeof h.className=="string"?h.className:"",L=k?"."+k.trim().split(/\s+/).slice(0,4).join("."):"";return I+C+L}s($,"domHint");function A(h,I){if(!h)return null;let C=[],k=h,L=0;for(;k&&L<I;){let F=k.tagName?k.tagName.toLowerCase():"unknown",Z=k.id&&k.id.trim()?"#"+k.id.trim():"",ie=typeof k.className=="string"?k.className:"",de=ie?ie.trim().split(/\s+/).filter(Boolean).slice(0,3):[],Ee=de.length>0?"."+de.join("."):"",Ge="";try{let Bt=k.parentElement;if(Bt){let pn=Array.from(Bt.children).filter(At=>At.tagName===k.tagName);if(pn.length>1){let At=pn.indexOf(k)+1;At>0&&(Ge=`:nth-of-type(${At})`)}}}catch{}C.push(`${F}${Z}${Ee}${Ge}`),k=k.parentElement,L++}return C.reverse(),C.join(" > ")}s(A,"buildElementPath");function _(h){if(!h)return null;let I=Object.getOwnPropertyNames(h);for(let C of I)if(C.startsWith("__reactFiber$")||C.startsWith("__reactInternalInstance$"))return C;return null}s(_,"findFiberKeyOn");function Q(h){if(!h)return null;let I=_(h);if(I){let k=h[I];if(k)return{fiber:k,fiberKey:I,onTarget:!0,anchorEl:h}}let C=h;for(;C;){let k=_(C);if(k){let L=C[k];if(L)return{fiber:L,fiberKey:k,onTarget:!1,anchorEl:C}}C=C.parentElement}return null}s(Q,"findFiberForElement");function q(h,I,C){if(!h)return{hostFiber:null,scanned:0,found:!1};if(h.stateNode===I)return{hostFiber:h,scanned:1,found:!0};let k=[],L=new Set;k.push(h),L.add(h);let F=0;for(;k.length>0;){let Z=k.shift();if(F++,Z&&Z.stateNode===I)return{hostFiber:Z,scanned:F,found:!0};if(F>=C)return{hostFiber:null,scanned:F,found:!1};let ie=Z?Z.child:null;ie&&!L.has(ie)&&(L.add(ie),k.push(ie));let de=Z?Z.sibling:null;de&&!L.has(de)&&(L.add(de),k.push(de))}return{hostFiber:null,scanned:F,found:!1}}s(q,"findHostFiberForDomElement");function z(h){if(!h)return!1;let I=h.prototype;return!!(I&&I.isReactComponent)}s(z,"isClassComponentType");function ee(h){if(!h)return null;if(typeof h=="function"){let I=h.displayName;return typeof I=="string"&&I.trim()?I.trim():typeof h.name=="string"&&h.name.trim()?h.name.trim():"Anonymous"}if(typeof h=="object"){let I=h.displayName;if(typeof I=="string"&&I.trim())return I.trim();let C=h.render;if(typeof C=="function"){let k=C.displayName;return typeof k=="string"&&k.trim()?k.trim():typeof C.name=="string"&&C.name.trim()?C.name.trim():"Anonymous"}}return null}s(ee,"typeDisplayName");function B(h){if(!h)return null;if(typeof h=="function")return typeof h.name=="string"&&h.name.trim()?h.name.trim():null;if(typeof h=="object"){let I=h.render;return typeof I=="function"&&typeof I.name=="string"&&I.name.trim()?I.name.trim():null}return null}s(B,"typeName");function V(h){if(!h)return h;if(typeof h=="object"){let I=h.render;if(typeof I=="function")return I}return h}s(V,"unwrapType");function Te(h){return h?typeof V(h.type??h.elementType)=="function":!1}s(Te,"isMeaningfulComponentFiber");function ae(h){if(!h)return"unknown";let I=V(h.type??h.elementType);return typeof I=="function"?z(I)?"class":"function":"unknown"}s(ae,"inferKind");function ne(h){let I=h?h._debugSource:void 0;if(!I||typeof I!="object")return;let C={};return typeof I.fileName=="string"&&(C.fileName=I.fileName),typeof I.lineNumber=="number"&&(C.lineNumber=I.lineNumber),typeof I.columnNumber=="number"&&(C.columnNumber=I.columnNumber),Object.keys(C).length>0?C:void 0}s(ne,"getDebugSource");function oe(h,I){let C=new WeakSet;function k(F,Z){if(F===null)return null;let ie=typeof F;if(ie==="string")return F.length>500?F.slice(0,500)+"\u2026":F;if(ie==="number"||ie==="boolean")return F;if(ie==="bigint")return String(F);if(ie!=="undefined"){if(ie==="function")return"[function]";if(ie==="symbol")return String(F);if(ie==="object"){if(F instanceof Element)return"[Element "+(F.tagName?F.tagName.toLowerCase():"")+"]";if(F instanceof Window)return"[Window]";if(F instanceof Document)return"[Document]";if(F instanceof Date)return F.toISOString();if(C.has(F))return"[circular]";if(C.add(F),Array.isArray(F))return Z<=0?"[array len="+F.length+"]":F.slice(0,20).map(Ge=>k(Ge,Z-1));if(Z<=0)return"[object]";let de={},Ee=Object.keys(F).slice(0,40);for(let Ge of Ee)try{de[Ge]=k(F[Ge],Z-1)}catch{de[Ge]="[unreadable]"}return de}return String(F)}}s(k,"helper");let L="";try{L=JSON.stringify(k(h,2))}catch{try{L=String(h)}catch{L="[unserializable]"}}return L.length>I?L.slice(0,I)+"\u2026(truncated)":L}s(oe,"safeStringify");function pe(h){return h.map(C=>{let k=C?.displayName,L=C?.name;return typeof k=="string"&&k.trim()?k.trim():typeof L=="string"&&L.trim()?L.trim():"Anonymous"}).filter(C=>!!C).reverse().join(" > ")}s(pe,"stackTextFromFrames");function Ie(h){let I=V(h.type??h.elementType),C=B(I),k=ee(I),L=ae(h),F=ne(h),Z={name:C,displayName:k,kind:L};return F&&(Z.debugSource=F),Z}s(Ie,"frameFromFiber");function v(h){let I=h.displayName?h.displayName:"",C=h.name?h.name:"",k=h.debugSource,L=k&&typeof k=="object"?`${String(k.fileName??"")}:${String(k.lineNumber??"")}:${String(k.columnNumber??"")}`:"";return`${I}|${C}|${h.kind}|${L}`}s(v,"makeFrameKey");function le(h){let I=[],C=null;for(let k of h){let L=v(k);C&&L===C||(I.push(k),C=L)}return I}s(le,"collapseConsecutiveDuplicates");function X(h){let I=new Set;function C(L){let F=L.trim().toLowerCase();F&&I.add(F)}s(C,"canonicalAdd");for(let L of h){let F=typeof L.displayName=="string"&&L.displayName.trim()?L.displayName.trim():typeof L.name=="string"&&L.name.trim()?L.name.trim():"";if(!F)continue;let Z=F.toLowerCase();/^memo(\(|$)/i.test(F)&&C("memo"),Z.includes("forwardref")&&C("forwardref"),Z.includes(".provider")&&C("context-provider"),Z.includes(".consumer")&&C("context-consumer"),Z.includes("suspense")&&C("suspense"),Z.includes("fragment")&&C("fragment"),Z.includes("strictmode")&&C("strictmode"),Z.includes("profiler")&&C("profiler")}let k=Array.from(I);return k.sort((L,F)=>L<F?-1:L>F?1:0),k}s(X,"detectWrappers");function H(h,I){let C=[],k=new Set(I.map(L=>L.toLowerCase()));for(let L=0;L<h.length;L++){let F=h[L],Z=F.displayName&&F.displayName.trim()?F.displayName.trim():F.name&&F.name.trim()?F.name.trim():"Anonymous",ie=Z.toLowerCase();for(let de of k){let Ee=!1;de==="memo"?Ee=/^memo(\(|$)/i.test(Z):de==="forwardref"?Ee=ie.includes("forwardref"):de==="context-provider"?Ee=ie.includes(".provider"):de==="context-consumer"?Ee=ie.includes(".consumer"):de==="suspense"?Ee=ie.includes("suspense"):de==="fragment"?Ee=ie.includes("fragment"):de==="strictmode"?Ee=ie.includes("strictmode"):de==="profiler"&&(Ee=ie.includes("profiler")),Ee&&C.push({wrapper:de,frameIndex:L,frameLabel:Z})}}return C}s(H,"findWrapperFrames");let Y=null;if(g&&g.trim())try{Y=document.querySelector(g)}catch{Y=null}else typeof f=="number"&&typeof y=="number"&&(Y=document.elementFromPoint(f,y));let Pe=!!Y,_e=$(Y),me=A(Y,K);if(!Pe)return{target:{selector:g??null,point:{x:typeof f=="number"?f:null,y:typeof y=="number"?y: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:M,strategy:"ancestor-fallback"},nearestComponent:null,componentStack:[],componentStackText:"",wrappersDetected:[],wrapperFrames:[],notes:["No DOM element could be resolved; cannot inspect React."]}};let fe=Q(Y);if(!fe)return D.push("No React fiber pointer found on the element or its ancestors."),D.push("This can happen if the page is not React, uses a different renderer, or runs with hardened/minified internals."),{target:{selector:g??null,point:{x:typeof f=="number"?f:null,y:typeof y=="number"?y:null},found:!0,domHint:_e,elementPath:me},react:{detected:!1,detectionReason:"React fiber not found on element/ancestors.",fiberKey:null,hostMapping:{fiberOnTargetElement:!1,anchorDomHint:null,targetDomHint:_e,hostFiberMatchedTarget:!1,subtreeScanNodesScanned:0,subtreeScanMaxNodes:M,strategy:"ancestor-fallback"},nearestComponent:null,componentStack:[],componentStackText:"",wrappersDetected:[],wrapperFrames:[],notes:D}};let Me=fe.fiber,Ve=fe.onTarget,tt=0,Rt=$(fe.anchorEl),yt="direct-on-target";if(!fe.onTarget){yt="ancestor-fallback";let h=q(fe.fiber,Y,M);tt=h.scanned,h.found&&h.hostFiber?(Me=h.hostFiber,Ve=!0,yt="ancestor-subtree-scan",D.push(`Mapped target DOM element to host fiber by scanning fiber subtree (scanned=${tt}).`)):(Ve=!1,D.push(`Could not find exact host fiber for the target element in the ancestor fiber subtree (scanned=${tt}). Falling back to ancestor fiber stack; some frames may be unrelated.`))}let jt={fiberOnTargetElement:fe.onTarget,anchorDomHint:Rt,targetDomHint:_e,hostFiberMatchedTarget:Ve,subtreeScanNodesScanned:tt,subtreeScanMaxNodes:M,strategy:yt},mt=null,_t=Me;for(;_t;){if(Te(_t)){mt=_t;break}_t=_t.return??null}mt||D.push("Fiber was found, but no meaningful function/class component was detected in the return chain.");let $t=[],mn=new Set,pt=mt;for(;pt&&$t.length<P;){if(mn.has(pt)){D.push("Detected a cycle in fiber.return chain; stopping stack traversal.");break}mn.add(pt),Te(pt)&&$t.push(Ie(pt)),pt=pt.return??null}let zt=$t.length>0?le($t):[],es=pe(zt),Vt=X(zt),ts=H(zt,Vt);Vt.length>=3&&D.push(`Wrapper-heavy stack detected (${Vt.join(", ")}). Interpreting nearestComponent may require skipping wrappers.`);let Mt=null;if(mt&&(Mt=Ie(mt),T))try{let h=mt.memoizedProps;h!==void 0?Mt.propsPreview=oe(h,W):D.push("memoizedProps not available on nearest component fiber.")}catch{D.push("Failed to read memoizedProps for nearest component (best-effort).")}return D.push("React Fiber inspection uses non-public internals; fields are best-effort."),D.push("Component names may come from displayName, wrappers, third-party libraries, or minified production builds."),yt==="ancestor-fallback"&&D.push("Host mapping fallback was used; consider selecting a deeper/more specific DOM element for a more accurate component stack."),{target:{selector:g??null,point:{x:typeof f=="number"?f:null,y:typeof y=="number"?y:null},found:!0,domHint:_e,elementPath:me},react:{detected:!0,detectionReason:yt==="direct-on-target"?"React fiber found on the target element.":yt==="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:fe.fiberKey,hostMapping:jt,nearestComponent:Mt,componentStack:zt,componentStackText:es,wrappersDetected:Vt,wrapperFrames:ts,notes:D}}},Object.fromEntries([["selectorEval",n??null],["xEval",typeof r=="number"?r:null],["yEval",typeof i=="number"?i:null],["maxStackDepthEval",a],["includePropsPreviewEval",l],["maxPropsPreviewCharsEval",u],["maxElementPathDepthEval",Sc],["maxFiberNodesToScanEval",xc]]))}};import{z as O}from"zod";var Ua="contains",Ha=200,Wa=!0,qa=!0,ja=80,$a=5,vc=50,Ic=20,Cc=25e4,ir=class{static{s(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:O.string().optional().describe("DOM CSS selector used as an anchor to pick a concrete component instance near that element."),anchorX:O.number().int().nonnegative().optional().describe("Anchor X coordinate (viewport pixels)."),anchorY:O.number().int().nonnegative().optional().describe("Anchor Y coordinate (viewport pixels)."),componentName:O.string().optional().describe("React component name/displayName to search in the Fiber graph."),matchStrategy:O.enum(["exact","contains"]).optional().default(Ua).describe("How to match componentName against Fiber type/displayName."),fileNameHint:O.string().optional().describe('Best-effort debug source file hint (usually endsWith match), e.g., "UserCard.tsx".'),lineNumber:O.number().int().positive().optional().describe("Optional debug source line number hint (dev builds only)."),maxElements:O.number().int().positive().optional().default(Ha).describe("Maximum number of DOM elements to return from the selected component subtree."),onlyVisible:O.boolean().optional().default(Wa).describe("If true, only visually visible elements are returned."),onlyInViewport:O.boolean().optional().default(qa).describe("If true, only elements intersecting the viewport are returned."),textPreviewMaxLength:O.number().int().positive().optional().default(ja).describe("Max length for per-element text preview (innerText/textContent/aria-label)."),maxMatches:O.number().int().positive().optional().default($a).describe("Max number of matching component candidates to return/rank.")}}outputSchema(){return{reactDetected:O.boolean().describe("True if __REACT_DEVTOOLS_GLOBAL_HOOK__ looks available."),fiberDetected:O.boolean().describe("True if DOM appears to contain React Fiber pointers (__reactFiber$...)."),rootDiscovery:O.enum(["devtools-hook","dom-fiber-scan","none"]).describe("How roots were discovered."),component:O.object({name:O.string().nullable(),displayName:O.string().nullable(),debugSource:O.object({fileName:O.string().nullable(),lineNumber:O.number().int().nullable(),columnNumber:O.number().int().nullable()}).nullable(),componentStack:O.array(O.string()),selection:O.enum(["anchor","query","query+anchor","unknown"]),scoring:O.object({score:O.number(),nameMatched:O.boolean(),debugSourceMatched:O.boolean(),anchorRelated:O.boolean(),proximityPx:O.number().nullable().optional()}).optional()}).nullable(),candidates:O.array(O.object({name:O.string().nullable(),displayName:O.string().nullable(),debugSource:O.object({fileName:O.string().nullable(),lineNumber:O.number().int().nullable(),columnNumber:O.number().int().nullable()}).nullable(),componentStack:O.array(O.string()),selection:O.enum(["anchor","query","query+anchor","unknown"]),scoring:O.object({score:O.number(),nameMatched:O.boolean(),debugSourceMatched:O.boolean(),anchorRelated:O.boolean(),proximityPx:O.number().nullable().optional()}).optional(),domFootprintCount:O.number().int()})).describe("Ranked candidate matches (best-first)."),elements:O.array(O.object({tagName:O.string(),id:O.string().nullable(),className:O.string().nullable(),selectorHint:O.string().nullable(),textPreview:O.string().nullable(),boundingBox:O.object({x:O.number(),y:O.number(),width:O.number(),height:O.number()}).nullable(),isVisible:O.boolean(),isInViewport:O.boolean()})),notes:O.array(O.string())}}async handle(e,t){let n=t.anchorSelector,r=t.anchorX,i=t.anchorY,a=t.componentName,l=t.matchStrategy??Ua,u=t.fileNameHint,m=t.lineNumber,c=t.maxElements??Ha,p=t.onlyVisible??Wa,g=t.onlyInViewport??qa,f=t.textPreviewMaxLength??ja,y=t.maxMatches??$a,P=typeof n=="string"&&n.trim().length>0,T=typeof r=="number"&&typeof i=="number",W=typeof a=="string"&&a.trim().length>0||typeof u=="string"&&u.trim().length>0||typeof m=="number";if(!P&&!T&&!W)throw new Error("Provide at least one targeting method: anchorSelector, (anchorX+anchorY), or componentName/debugSource hints.");return await e.page.evaluate(M=>{let D=s((b,d)=>b[d],"g"),$=D(M,"anchorSelectorEval"),A=D(M,"anchorXEval"),_=D(M,"anchorYEval"),Q=D(M,"componentNameEval"),q=D(M,"matchStrategyEval"),z=D(M,"fileNameHintEval"),ee=D(M,"lineNumberEval"),B=D(M,"maxElementsEval"),V=D(M,"onlyVisibleEval"),Te=D(M,"onlyInViewportEval"),ae=D(M,"textPreviewMaxLengthEval"),ne=D(M,"maxMatchesEval"),oe=D(M,"maxRootsScan"),pe=D(M,"maxFibersVisited"),Ie=D(M,"stackLimit"),v=[];function le(b){return typeof Element<"u"&&b instanceof Element}s(le,"isElement");function X(b){if(typeof b!="string")return null;let d=b.trim();return d||null}s(X,"normalizeStr");function H(b){let d=b,x=Object.keys(d);for(let E of x)if(E.startsWith("__reactFiber$")){let R=d[E];if(R)return R}for(let E of x)if(E.startsWith("__reactInternalInstance$")){let R=d[E];if(R)return R}return null}s(H,"getFiberFromDomElement");function Y(){let d=globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__;return!d||typeof d.getFiberRoots!="function"?null:d}s(Y,"getDevtoolsHook");function Pe(b){let d=[],x=b.renderers;return!x||typeof x.forEach!="function"?d:(x.forEach((E,R)=>{try{let G=b.getFiberRoots(R);G&&typeof G.forEach=="function"&&G.forEach(se=>{se&&d.push(se)})}catch{}}),d.slice(0,oe))}s(Pe,"getAllRootsFromHook");function _e(b){let d=[],x=Array.from(document.querySelectorAll("*")),E=x.length>5e3?Math.ceil(x.length/5e3):1;for(let R=0;R<x.length;R+=E){let G=x[R],se=H(G);if(se&&(d.push(se),d.length>=b))break}return d}s(_e,"getSeedFibersFromDomScan");function me(b){if(typeof b!="function")return null;let d=b,x=X(d.displayName);if(x)return x;let E=X(d.name);return E||null}s(me,"getFunctionDisplayName");function fe(b){if(!b)return null;let d=b.type??b.elementType??null;if(!d)return null;if(typeof d=="function")return me(d);if(typeof d=="string")return d;let x=X(d.displayName);return x||X(d.name)}s(fe,"getFiberTypeName");function Me(b){if(!b)return null;let d=b.type??b.elementType??null;if(!d)return null;let x=X(d.displayName);return x||fe(b)}s(Me,"getDisplayName");function Ve(b){let d=new Set,x=[],E=s(R=>{R&&(d.has(R)||(d.add(R),x.push(R)))},"push");E(b),E(b?.alternate);for(let R=0;R<8;R++){let G=x[R];if(!G)break;E(G?._debugOwner),E(G?._debugOwner?.alternate)}for(let R of x){let G=R?._debugSource??R?._debugOwner?._debugSource??R?.type?._debugSource??R?.elementType?._debugSource??null;if(!G)continue;let se=X(G.fileName)??null,ye=typeof G.lineNumber=="number"?G.lineNumber:null,Ue=typeof G.columnNumber=="number"?G.columnNumber:null;if(se||ye!==null||Ue!==null)return{fileName:se,lineNumber:ye,columnNumber:Ue}}return null}s(Ve,"getDebugSource");function tt(b){let d=b?.stateNode;return le(d)}s(tt,"isHostFiber");function Rt(b,d){let x=[],E=b??null;for(let G=0;G<d&&E;G++){let se=Me(E),ye=tt(E);se&&!ye&&x.push(se),E=E.return??null}if(x.length===0){E=b??null;for(let G=0;G<d&&E;G++){let se=Me(E);se&&x.push(se),E=E.return??null}}let R=[];for(let G of x)(R.length===0||R[R.length-1]!==G)&&R.push(G);return R}s(Rt,"buildComponentStack");function yt(b){let d=b??null,x=new Set;for(;d;){let E=d.alternate??d;if(x.has(E))break;if(x.add(E),!tt(d))return d;d=d.return??null}return null}s(yt,"firstMeaningfulComponentAbove");function jt(b,d,x){if(!b)return!1;let E=b.trim(),R=d.trim();return!E||!R?!1:x==="exact"?E===R:E.toLowerCase().includes(R.toLowerCase())}s(jt,"matchesName");function mt(b,d,x){let E=Ve(b);if(!E)return!1;if(d){let R=d.trim();if(R){let G=(E.fileName??"").trim();if(!G)return!1;let se=G.toLowerCase(),ye=R.toLowerCase();if(!(se.endsWith(ye)||se.includes(ye)))return!1}}return!(typeof x=="number"&&(E.lineNumber===null||Math.abs(E.lineNumber-x)>3))}s(mt,"matchesDebugSource");function _t(b){if(!b)return null;let d=b.current;return d?d.child??d:b}s(_t,"toStartFiber");function $t(b,d,x){if(b&&b.trim()){let E=document.querySelector(b);return E||(v.push(`anchorSelector did not match any element: ${b}`),null)}if(typeof d=="number"&&typeof x=="number"){let E=document.elementFromPoint(d,x);return E||(v.push(`anchorPoint did not hit any element: (${d}, ${x})`),null)}return null}s($t,"pickAnchorElement");function mn(b){let d=X(b.getAttribute("data-testid"))??X(b.getAttribute("data-test-id"))??X(b.getAttribute("data-test"))??null;if(d)return`[data-testid='${d.replace(/'/g,"\\'")}']`;let x=X(b.getAttribute("data-selector"))??null;if(x)return`[data-selector='${x.replace(/'/g,"\\'")}']`;if(b.id)try{return`#${CSS.escape(b.id)}`}catch{return`#${b.id}`}return b.tagName.toLowerCase()}s(mn,"selectorHintFor");function pt(b,d){let x=X(b.getAttribute("aria-label"))??null;if(x)return x.slice(0,d);let E=String(b.innerText??b.textContent??"").trim();return E?E.slice(0,d):null}s(pt,"textPreviewFor");function zt(b){let d=b.getBoundingClientRect(),x=getComputedStyle(b),E=x.display!=="none"&&x.visibility!=="hidden"&&parseFloat(x.opacity||"1")>0&&d.width>0&&d.height>0,R=window.innerWidth,G=window.innerHeight,se=d.right>0&&d.bottom>0&&d.left<R&&d.top<G,ye=Number.isFinite(d.x)&&Number.isFinite(d.y)&&Number.isFinite(d.width)&&Number.isFinite(d.height)?{x:d.x,y:d.y,width:d.width,height:d.height}:null,Ue=d.left+d.width/2,Se=d.top+d.height/2;return{boundingBox:ye,isVisible:E,isInViewport:se,centerX:Ue,centerY:Se}}s(zt,"computeRuntime");function es(b,d,x,E,R){let G=[],se=new Set,ye=[];b&&ye.push(b);let Ue=new Set;for(;ye.length>0&&!(G.length>=d);){let Se=ye.pop();if(!Se)continue;let nt=Se.alternate??Se;if(Ue.has(nt))continue;if(Ue.add(nt),tt(Se)){let ge=Se.stateNode;if(!se.has(ge)){se.add(ge);let De=zt(ge);if(!(x&&!De.isVisible)){if(!(E&&!De.isInViewport)){let ot=ge.tagName.toLowerCase(),Ft=ge.id?String(ge.id):null,Ke=ge.className,rt=typeof Ke=="string"&&Ke.trim()?Ke.trim():null;G.push({tagName:ot,id:Ft,className:rt,selectorHint:mn(ge),textPreview:pt(ge,R),boundingBox:De.boundingBox,isVisible:De.isVisible,isInViewport:De.isInViewport})}}}}let wt=Se.child??null,Lt=Se.sibling??null;wt&&ye.push(wt),Lt&&ye.push(Lt)}return G}s(es,"collectDomElementsFromFiberSubtree");function Vt(b,d,x){let E=d.componentName?d.componentName.trim():void 0,R=!!E,G=d.fileNameHint?d.fileNameHint.trim():void 0,se=!!G,ye=typeof d.lineNumber=="number";if(!(R||se||ye))return[];let Se=[];for(let ge of b){let De=_t(ge);De&&Se.push(De)}let nt=new Set,wt=[],Lt=0;for(;Se.length>0&&!(wt.length>=x);){let ge=Se.pop();if(!ge)continue;let De=ge.alternate??ge;if(nt.has(De))continue;if(nt.add(De),Lt++,Lt>pe){v.push(`Fiber traversal safety cap reached (${pe}). Results may be incomplete.`);break}let ot=Me(ge),Ft=fe(ge),Ke=R?jt(ot,E,d.matchStrategy)||jt(Ft,E,d.matchStrategy):!0,rt=se||ye?mt(ge,G,d.lineNumber):!0;Ke&&rt&&wt.push(ge);let Ut=ge.child??null,Be=ge.sibling??null;Ut&&Se.push(Ut),Be&&Se.push(Be)}return wt}s(Vt,"findFibersByQuery");function ts(b,d,x,E,R,G,se,ye,Ue){let Se=R.componentName?R.componentName.trim():void 0,nt=!!Se,wt=Me(b),Lt=fe(b),ge=nt?jt(wt,Se,R.matchStrategy)||jt(Lt,Se,R.matchStrategy):!1,De=X(R.fileNameHint)||typeof R.lineNumber=="number"?mt(b,X(R.fileNameHint)??void 0,typeof R.lineNumber=="number"?R.lineNumber:void 0):!1,ot=es(b,G,se,ye,Ue),Ft=!1,Ke=null;if(d){let Ut=mn(d);if(Ft=ot.some(Be=>!Be.selectorHint||!Ut?!1:Be.selectorHint===Ut)||ot.some(Be=>{if(!Be.boundingBox)return!1;let qe=d.getBoundingClientRect(),Tt=Be.boundingBox;return qe.left<Tt.x+Tt.width&&qe.left+qe.width>Tt.x&&qe.top<Tt.y+Tt.height&&qe.top+qe.height>Tt.y}),typeof x=="number"&&typeof E=="number"&&ot.length>0){let Be=null;for(let qe of ot){if(!qe.boundingBox)continue;let Tt=qe.boundingBox.x+qe.boundingBox.width/2,js=qe.boundingBox.y+qe.boundingBox.height/2,$s=Tt-x,zs=js-E,os=Math.sqrt($s*$s+zs*zs);(Be===null||os<Be)&&(Be=os)}Ke=Be}}let rt=0;if(rt+=ge?3:0,rt+=De?3:0,rt+=Ft?2:0,rt+=Math.min(1.5,ot.length/25),typeof Ke=="number"&&Number.isFinite(Ke)){let Ut=Math.max(0,Math.min(1,1-Ke/1e3));rt+=1.5*Ut}return{score:rt,nameMatched:ge,debugSourceMatched:De,anchorRelated:Ft,proximityPx:Ke,dom:ot}}s(ts,"scoreCandidate");let Mt=Y(),Dt=!!Mt;Dt?v.push("React DevTools hook detected. Root discovery will use getFiberRoots() (more reliable)."):(v.push("React DevTools hook was not detected (__REACT_DEVTOOLS_GLOBAL_HOOK__)."),v.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 h=(()=>{let b=document.body;return b?!!(H(b)||_e(1).length>0):!1})();h?v.push("React Fiber pointers detected on DOM nodes. Anchor-based mapping may still work without the DevTools hook (best-effort)."):v.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 I=$t($,A,_),C=null;if(I){let b=H(I);if(b){let d=b,x=b.alternate??null,E=d;x&&(x.child||x.sibling)&&!(d.child||d.sibling)&&(E=x);let R=yt(E);R?C=R:v.push("Anchor fiber found but no meaningful component fiber was found above it.")}else v.push("Anchor element found but React fiber was not found on it.")}let k=[],L="none";if(Mt){let b=Pe(Mt);b.length>0&&(k=b,L="devtools-hook")}if(k.length===0&&h){let b=_e(10);b.length>0&&(k=b,L="dom-fiber-scan",v.push("Using DOM fiber scan as fallback root discovery (best-effort)."))}let F=!!X(Q)||!!X(z)||typeof ee=="number",Z={componentName:X(Q)??void 0,matchStrategy:q,fileNameHint:X(z)??void 0,lineNumber:typeof ee=="number"?ee:void 0},ie=[];F&&(k.length>0?ie=Vt(k,Z,Math.max(1,Math.floor(ne))):v.push("Query was provided but no roots could be discovered. Provide an anchorSelector/anchorX+anchorY so we can map via DOM fiber pointers."));let de=[];C&&de.push(C);for(let b of ie)de.push(b);let Ee=[],Ge=new Set;for(let b of de){let d=b?.alternate??b;b&&!Ge.has(d)&&(Ge.add(d),Ee.push(b))}if(Ee.length===0)return Dt||v.push("No candidates found. Without the DevTools hook, component search may be unreliable unless you provide a strong anchor."),{reactDetected:Dt,fiberDetected:h,rootDiscovery:L,component:null,candidates:[],elements:[],notes:[...v,"Failed to select a target component fiber. Provide a better anchor, or ensure React is present and render has happened."]};let Bt=[];for(let b of Ee){let d=ts(b,I,A,_,Z,B,V,Te,ae),x="unknown",E=C?(C.alternate??C)===(b.alternate??b):!1,R=ie.some(nt=>(nt.alternate??nt)===(b.alternate??b));E&&R?x="query+anchor":E?x="anchor":R?x="query":x="unknown";let G=fe(b),se=Me(b),ye=Ve(b),Ue=Rt(b,Ie),Se={name:G,displayName:se,debugSource:ye,componentStack:Ue,selection:x,scoring:{score:d.score,nameMatched:d.nameMatched,debugSourceMatched:d.debugSourceMatched,anchorRelated:d.anchorRelated,proximityPx:d.proximityPx}};Bt.push({fiber:b,meta:Se,dom:d.dom,domFootprintCount:d.dom.length})}Bt.sort((b,d)=>(d.meta.scoring?.score??0)-(b.meta.scoring?.score??0));let pn=Bt[0],At=Bt.slice(0,Math.max(1,Math.floor(ne))).map(b=>({...b.meta,domFootprintCount:b.domFootprintCount})),ns=pn.dom;return F&&(Z.fileNameHint||typeof Z.lineNumber=="number")&&(At.some(d=>!!(d.debugSource?.fileName||d.debugSource?.lineNumber!==null))||(v.push("debugSource hints were provided, but no _debugSource information was found on matched fibers. This is common in production builds and some dev toolchains."),v.push('React DevTools may still display "Rendered by <file>:<line>" using sourcemaps/stack traces even when fiber._debugSource is null.'))),ns.length>=B&&v.push(`Element list was truncated at maxElements=${B}. Increase maxElements if needed.`),ns.length===0&&v.push("No DOM elements were returned for the selected component. It may render no host elements, or filtering (onlyVisible/onlyInViewport) removed them."),!Dt&&h?v.push("React DevTools hook was not detected, but DOM fiber pointers were found. Using DOM-fiber scanning and anchor-based mapping (best-effort)."):!Dt&&!h&&v.push("React DevTools hook was not detected and no DOM fiber pointers were found. Component-to-DOM mapping is unavailable on this page."),{reactDetected:Dt,fiberDetected:h,rootDiscovery:L,component:pn.meta,candidates:At,elements:ns,notes:[...v,"Component metadata is best-effort. Wrappers (memo/forwardRef/HOCs), Suspense/Offscreen, and portals may make names/stacks noisy."]}},Object.fromEntries([["anchorSelectorEval",typeof n=="string"&&n.trim()?n.trim():void 0],["anchorXEval",typeof r=="number"&&Number.isFinite(r)?Math.floor(r):void 0],["anchorYEval",typeof i=="number"&&Number.isFinite(i)?Math.floor(i):void 0],["componentNameEval",typeof a=="string"&&a.trim()?a.trim():void 0],["matchStrategyEval",l],["fileNameHintEval",typeof u=="string"&&u.trim()?u.trim():void 0],["lineNumberEval",typeof m=="number"&&Number.isFinite(m)?Math.floor(m):void 0],["maxElementsEval",Math.max(1,Math.floor(c))],["onlyVisibleEval",!!p],["onlyInViewportEval",!!g],["textPreviewMaxLengthEval",Math.max(1,Math.floor(f))],["maxMatchesEval",Math.max(1,Math.floor(y))],["maxRootsScan",Ic],["maxFibersVisited",Cc],["stackLimit",vc]]))}};var za=[new sr,new ir];import{z as Va}from"zod";var ar=class{static{s(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:Va.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:Va.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(e,t){let n=`(async function() { ${t.script} })()`;return{result:await e.page.evaluate(n)}}};import Ec from"node:crypto";import Ga from"node:vm";import{z as _s}from"zod";var Ka=5e3,Oc=3e4;function Nc(o){if(o==null||typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;try{return JSON.parse(JSON.stringify(o))}catch{return String(o)}}s(Nc,"_toJsonSafe");var lr=class{static{s(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:_s.string().describe("JavaScript code (async allowed)."),timeoutMs:_s.number().int().min(0).max(Oc).optional().default(Ka).describe("Max VM CPU time for synchronous execution in milliseconds.")}}outputSchema(){return{result:_s.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(e,t){let n=[],r={log:s((...m)=>{n.push({level:"log",message:m.map(c=>String(c)).join(" ")})},"log"),warn:s((...m)=>{n.push({level:"warn",message:m.map(c=>String(c)).join(" ")})},"warn"),error:s((...m)=>{n.push({level:"error",message:m.map(c=>String(c)).join(" ")})},"error")},i=s(async m=>{let c=Math.max(0,Math.floor(m));await new Promise(p=>{setTimeout(()=>p(),c)})},"sleep"),a={page:e.page,console:r,sleep:i,Math,JSON,Number,String,Boolean,Array,Object,Date,RegExp,isFinite,isNaN,parseInt,parseFloat,URL,URLSearchParams,TextEncoder,TextDecoder,structuredClone,crypto:{randomUUID:Ec.randomUUID},AbortController,setTimeout,clearTimeout},l=Ga.createContext(a),u=`
715
- 'use strict';
716
- (async () => {
717
- ${String(t.code??"")}
718
- })()
719
- `.trim();try{let c=new Ga.Script(u,{filename:"mcp-sandbox.js"}).runInContext(l,{timeout:t.timeoutMs??Ka}),p=await Promise.resolve(c);return p===void 0&&n.length>0?{result:{logs:n}}:{result:Nc(p)}}catch(m){return{result:{error:m instanceof Error?m.stack??m.message:String(m),logs:n}}}}};var Xa=[new ar,new lr];import Pc from"picomatch";var Ya=new WeakMap;function ln(o){let e=Ya.get(o);if(e)return e;let t={stubs:[],installed:!1};return Ya.set(o,t),t}s(ln,"_ensureStore");function Ja(){let o=Date.now(),e=Math.floor(Math.random()*1e6);return`${o.toString(36)}-${e.toString(36)}`}s(Ja,"_nowId");async function kc(o){o<=0||await new Promise(e=>{setTimeout(()=>e(),o)})}s(kc,"_sleep");function Ms(o){return typeof o!="number"||!Number.isFinite(o)||o<=0?-1:Math.floor(o)}s(Ms,"_normalizeTimes");function Qa(o,e){return o===-1?!0:e<o}s(Qa,"_isTimesRemaining");function Za(o){if(typeof o=="number"&&Number.isFinite(o))return Math.max(0,Math.min(1,o))}s(Za,"_normalizeChance");function Rc(o){return o===void 0?!0:o<=0?!1:o>=1?!0:Math.random()<o}s(Rc,"_shouldApplyChance");function el(o){let e=o.trim();return e?Pc(e,{dot:!0,nocase:!1}):()=>!1}s(el,"_compileMatcher");function _c(o,e){for(let t of o)if(t.enabled&&Qa(t.times,t.usedCount)&&t.matcher(e)&&!(t.kind==="mock_http_response"&&!Rc(t.chance)))return t}s(_c,"_pickStub");async function Mc(o,e){let t=o.request();if(e.usedCount++,e.delayMs>0&&await kc(e.delayMs),e.kind==="mock_http_response"){if(e.action==="abort"){let a=e.abortErrorCode??"failed";await o.abort(a);return}let n=typeof e.status=="number"?e.status:200,r=e.headers??{},i=typeof e.body=="string"?e.body:"";await o.fulfill({status:n,headers:r,body:i});return}else if(e.kind==="intercept_http_request"){let r={headers:{...t.headers(),...e.modifications.headers??{}}};typeof e.modifications.method=="string"&&e.modifications.method.trim()&&(r.method=e.modifications.method.trim().toUpperCase()),typeof e.modifications.body=="string"&&(r.postData=e.modifications.body),await o.continue(r);return}await o.continue()}s(Mc,"_applyStub");async function ur(o){let e=ln(o);e.installed||(await o.route("**/*",async t=>{let n=t.request().url(),r=ln(o),i=_c(r.stubs,n);if(!i){await t.continue();return}try{await Mc(t,i)}finally{Qa(i.times,i.usedCount)||(r.stubs=r.stubs.filter(a=>a.id!==i.id))}}),e.installed=!0)}s(ur,"ensureRoutingInstalled");function tl(o,e){let t=ln(o),n={...e,kind:"mock_http_response",id:Ja(),usedCount:0,matcher:el(e.pattern),times:Ms(e.times),delayMs:Math.max(0,Math.floor(e.delayMs)),chance:Za(e.chance)};return t.stubs.push(n),n}s(tl,"addMockHttpResponseStub");function nl(o,e){let t=ln(o),n={...e,kind:"intercept_http_request",id:Ja(),usedCount:0,matcher:el(e.pattern),times:Ms(e.times),delayMs:Math.max(0,Math.floor(e.delayMs))};return t.stubs.push(n),n}s(nl,"addHttpInterceptRequestStub");function ol(o,e){let t=ln(o);if(!e){let r=t.stubs.length;return t.stubs=[],r}let n=t.stubs.length;return t.stubs=t.stubs.filter(r=>r.id!==e),n-t.stubs.length}s(ol,"clearStub");function rl(o){return[...ln(o).stubs]}s(rl,"listStubs");function cr(o){return typeof o!="number"||!Number.isFinite(o)||o<=0?0:Math.floor(o)}s(cr,"normalizeDelayMs");function mr(o){return Ms(o)}s(mr,"normalizeTimesPublic");function pr(o){if(!o)return;let e={};for(let[t,n]of Object.entries(o))e[String(t)]=String(n);return e}s(pr,"normalizeHeaders");function dr(o){if(typeof o=="string")return o;if(o&&typeof o=="object")return JSON.stringify(o)}s(dr,"normalizeBody");function sl(o){if(typeof o!="string")return;let e=o.trim();if(e)return e}s(sl,"normalizeAbortCode");function il(o){if(typeof o!="string")return;let e=o.trim();if(e)return e.toUpperCase()}s(il,"normalizeMethod");function al(o){return Za(o)}s(al,"normalizeChance");import{z as ll}from"zod";var br=class{static{s(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:ll.string().optional().describe("Stub id to remove. Omit to remove all stubs.")}}outputSchema(){return{clearedCount:ll.number().int().nonnegative().describe("Number of stubs removed.")}}async handle(e,t){return{clearedCount:ol(e.browserContext,t.stubId)}}};import{z as xe}from"zod";var gr=class{static{s(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:xe.string().describe("Glob pattern matched against the full request URL (picomatch)."),modifications:xe.object({headers:xe.record(xe.string(),xe.string()).optional().describe("Headers to merge into the outgoing request headers."),body:xe.union([xe.string(),xe.record(xe.string(),xe.any()),xe.array(xe.any())]).optional().describe("Override request body. If object/array, it will be JSON-stringified."),method:xe.string().optional().describe("Override HTTP method (e.g., POST, PUT).")}).optional().describe("Request modifications to apply."),delayMs:xe.number().int().nonnegative().optional().describe("Artificial delay in milliseconds before continuing the request."),times:xe.number().int().optional().describe("Apply only N times, then let through. Omit for infinite.")}}outputSchema(){return{stubId:xe.string().describe("Unique id of the installed stub."),kind:xe.literal("intercept_http_request").describe("Stub kind."),pattern:xe.string().describe("Glob pattern."),enabled:xe.boolean().describe("Whether the stub is enabled."),delayMs:xe.number().int().describe("Applied artificial delay in milliseconds."),times:xe.number().int().describe("Max applications (-1 means infinite).")}}async handle(e,t){await ur(e.browserContext);let n=cr(t.delayMs),r=mr(t.times),i=pr(t.modifications?.headers),a=dr(t.modifications?.body),l=il(t.modifications?.method),u=nl(e.browserContext,{enabled:!0,pattern:t.pattern,modifications:{headers:i,body:a,method:l},delayMs:n,times:r});return{stubId:u.id,kind:"intercept_http_request",pattern:u.pattern,enabled:u.enabled,delayMs:u.delayMs,times:u.times}}};import{z as Qe}from"zod";var hr=class{static{s(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:Qe.array(Qe.object({id:Qe.string().describe("Stub id."),kind:Qe.string().describe("Stub kind."),enabled:Qe.boolean().describe("Whether stub is enabled."),pattern:Qe.string().describe("Glob pattern (picomatch)."),delayMs:Qe.number().int().describe("Artificial delay in ms."),times:Qe.number().int().describe("Max applications (-1 means infinite)."),usedCount:Qe.number().int().describe("How many times it has been applied."),action:Qe.string().optional().describe("For mock_response: fulfill/abort."),status:Qe.number().int().optional().describe("For mock_response: HTTP status (if set).")}))}}async handle(e,t){return{stubs:rl(e.browserContext).map(r=>{let i={id:r.id,kind:r.kind,enabled:r.enabled,pattern:r.pattern,delayMs:r.delayMs,times:r.times,usedCount:r.usedCount};return r.kind==="mock_http_response"&&(i.action=r.action,typeof r.status=="number"&&(i.status=r.status)),i})}}};import{z as ce}from"zod";var fr=class{static{s(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:ce.string().describe("Glob pattern matched against the full request URL (picomatch)."),response:ce.object({action:ce.enum(["fulfill","abort"]).optional().default("fulfill").describe("Fulfill with a mocked response or abort the request."),status:ce.number().int().min(100).max(599).optional().describe("HTTP status code (used when action=fulfill)."),headers:ce.record(ce.string(),ce.string()).optional().describe("HTTP headers for the mocked response."),body:ce.union([ce.string(),ce.record(ce.string(),ce.any()),ce.array(ce.any())]).optional().describe("Response body. If object/array, it will be JSON-stringified."),abortErrorCode:ce.string().optional().describe('Playwright abort error code (used when action=abort), e.g. "timedout".')}).describe("Mock response configuration."),delayMs:ce.number().int().nonnegative().optional().describe("Artificial delay in milliseconds before applying the stub."),times:ce.number().int().optional().describe("Apply only N times, then let through. Omit for infinite."),chance:ce.number().min(0).max(1).optional().describe("Probability (0..1) to apply the stub per request (flaky testing).")}}outputSchema(){return{stubId:ce.string().describe("Unique id of the installed stub (use it to clear later)."),kind:ce.literal("mock_http_response").describe("Stub kind."),pattern:ce.string().describe("Glob pattern."),enabled:ce.boolean().describe("Whether the stub is enabled."),delayMs:ce.number().int().describe("Applied artificial delay in milliseconds."),times:ce.number().int().describe("Max applications (-1 means infinite)."),chance:ce.number().optional().describe("Apply probability (omit means always)."),action:ce.enum(["fulfill","abort"]).describe("Applied action."),status:ce.number().int().optional().describe("HTTP status (present when action=fulfill).")}}async handle(e,t){await ur(e.browserContext);let n=t.response.action??"fulfill",r=cr(t.delayMs),i=mr(t.times),a=al(t.chance),l=t.response.status,u=pr(t.response.headers),m=dr(t.response.body),c=sl(t.response.abortErrorCode),p=tl(e.browserContext,{enabled:!0,pattern:t.pattern,action:n,status:l,headers:u,body:m,abortErrorCode:c,delayMs:r,times:i,chance:a}),g={stubId:p.id,kind:"mock_http_response",pattern:p.pattern,enabled:p.enabled,delayMs:p.delayMs,times:p.times,action:p.action};return typeof p.chance=="number"&&(g.chance=p.chance),p.action==="fulfill"&&(g.status=typeof p.status=="number"?p.status:200),g}};var ul=[new br,new gr,new hr,new fr];import{z as Ze}from"zod";var cl=3e4,ml=500,pl=0,dl=50,yr=class{static{s(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:Ze.number().int().min(0).optional().default(cl).describe("Maximum time to wait before failing (milliseconds).."),idleTimeMs:Ze.number().int().min(0).optional().default(ml).describe("How long the network must stay idle continuously before resolving (milliseconds)."),maxConnections:Ze.number().int().min(0).optional().default(pl).describe("Idle threshold. Network is considered idle when in-flight requests <= maxConnections."),pollIntervalMs:Ze.number().int().min(10).optional().default(dl).describe("Polling interval used to sample the in-flight request count (milliseconds).")}}outputSchema(){return{waitedMs:Ze.number().int().nonnegative().describe("Total time waited until the network became idle or the tool timed out (milliseconds)."),idleTimeMs:Ze.number().int().nonnegative().describe("Idle duration required for success (milliseconds)."),timeoutMs:Ze.number().int().nonnegative().describe("Maximum allowed wait time (milliseconds)."),maxConnections:Ze.number().int().nonnegative().describe("Idle threshold used: in-flight requests must be <= this value."),pollIntervalMs:Ze.number().int().nonnegative().describe("Polling interval used to sample the in-flight request count (milliseconds)."),finalInFlightRequests:Ze.number().int().nonnegative().describe("The last observed number of in-flight requests at the moment the tool returned."),observedIdleMs:Ze.number().int().nonnegative().describe("How long the in-flight request count stayed <= maxConnections right before returning (milliseconds).")}}async handle(e,t){let n=t.timeoutMs??cl,r=t.idleTimeMs??ml,i=t.maxConnections??pl,a=t.pollIntervalMs??dl,l=Date.now(),u=l+n,m=l,c=0;for(;;){let p=Date.now();c=e.numOfInFlightRequests(),c>i&&(m=p);let g=p-m;if(g>=r)return{waitedMs:p-l,idleTimeMs:r,timeoutMs:n,maxConnections:i,pollIntervalMs:a,finalInFlightRequests:c,observedIdleMs:g};if(p>=u){let f=p-l;throw new Error(`Timed out after ${f}ms waiting for network idle (idleTimeMs=${r}, maxConnections=${i}, inFlight=${c}).`)}await this.sleep(a)}}async sleep(e){await new Promise(t=>{setTimeout(()=>t(),e)})}};var bl=[new yr];import Bc from"node:fs";import{chromium as hl,firefox as fl,webkit as yl}from"playwright";var Ac="chromium",gl=new Map,wr=new Map;function Lc(o){return JSON.stringify(o)}s(Lc,"_browserKey");function Fc(o){let e={headless:o.headless,executablePath:o.executablePath,handleSIGINT:!1,handleSIGTERM:!1};if(o.useInstalledOnSystem)if(o.browserType==="chromium")e.channel="chrome",e.args=["--disable-blink-features=AutomationControlled"],e.ignoreDefaultArgs=["--disable-extensions"];else throw new Error(`Browser type ${o.browserType} is not supported to be used from the one installed on the system`);return e}s(Fc,"_browserLaunchOptions");async function Uc(o){let e;switch(o.browserType){case"firefox":e=fl;break;case"webkit":e=yl;break;default:e=hl;break}return e.launch(Fc(o))}s(Uc,"_createBrowser");async function Hc(o){let e=Lc(o),t=gl.get(e);if(t&&!t.isConnected()){try{await t.close().catch(()=>{})}catch{}t=void 0}return t||(t=await Uc(o),gl.set(e,t)),t}s(Hc,"_getBrowser");function Wc(o){return o.persistent.userDataDir}s(Wc,"_persistentBrowserContextKey");function qc(o){let e=o.browserOptions,t={headless:e.headless,executablePath:e.executablePath,bypassCSP:!0,viewport:e.headless?void 0:null,locale:o.locale};if(e.useInstalledOnSystem)if(e.browserType==="chromium")t.channel="chrome",t.args=["--disable-blink-features=AutomationControlled"],t.ignoreDefaultArgs=["--disable-extensions"];else throw new Error(`Browser type ${e.browserType} is not supported to be used from the one installed on the system`);return t}s(qc,"_persistentBrowserContextLaunchOptions");async function jc(o){let e;switch(o.browserOptions.browserType){case"firefox":e=fl;break;case"webkit":e=yl;break;default:e=hl;break}let t=o.persistent.userDataDir;Bc.mkdirSync(t,{recursive:!0});let n=await e.launchPersistentContext(t,qc(o));for(let r of n.pages())try{await r.close()}catch{}return n}s(jc,"_createPersistentBrowserContext");async function $c(o){let e=Wc(o),t=wr.get(e);if(t&&!t.browser()?.isConnected()){try{await t.close().catch(()=>{})}catch{}t=void 0}if(!t)t=await jc(o),wr.set(e,t);else throw new Error(`There is already active persistent browser context in the user data directory: ${o.persistent?.userDataDir}`);return t}s($c,"_getPersistentBrowserContext");async function wl(o={browserOptions:{browserType:Ac,headless:Gt,executablePath:Pn,useInstalledOnSystem:Yt},persistent:Kt?{userDataDir:Xt}:void 0,locale:kn}){return o.persistent?{browserContext:await $c(o)}:{browserContext:await(await Hc(o.browserOptions)).newContext({viewport:o.browserOptions.headless?void 0:null,bypassCSP:!0,locale:o.locale})}}s(wl,"newBrowserContext");async function Tl(o,e={}){return await o.newPage()}s(Tl,"newPage");async function Sl(o){await o.close();let e=!1;for(let[t,n]of wr.entries())o===n&&(wr.delete(t),e=!0);return e}s(Sl,"closeBrowserContext");function zc(o){let e=o.trim();return e.startsWith("/")||(e="/"+e),e.endsWith("/")||(e=e+"/"),e}s(zc,"_normalizeBasePath");function Vc(o){let e=o.trim();return e&&(e.endsWith("/")?e.slice(0,-1):e)}s(Vc,"_normalizeUpstreamBaseUrl");function Gc(o,e){try{let n=new URL(o).pathname;if(!n.startsWith(e))return null;let r=n.slice(e.length);return r?r.startsWith("/")?r:"/"+r:null}catch{return null}}s(Gc,"_computeSuffixPath");function Kc(o,e,t){try{let r=new URL(t).search??"";return o+e+r}catch{return o+e}}s(Kc,"_appendSuffixToUpstream");var Tr=class{static{s(this,"OTELProxy")}config;queue;workers;isRunning;isInstalled;metrics;constructor(e){let t=e.maxQueueSize??200,n=e.concurrency??2,r=e.respondNoContent??!0,i=zc(e.localPath),a=Vc(e.upstreamUrl);this.config={...e,localPath:i,upstreamUrl:a,maxQueueSize:t,concurrency:n,respondNoContent:r},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(e){if(this.isInstalled)return;let t=this.config.localPath;if(!t.startsWith("/"))throw new Error('localPath must start with "/" (e.g. "/__mcp_otel/").');let n=`**${t}**`;await e.route(n,async r=>{await this._handleRoute(r)}),this.isInstalled=!0,this.isRunning||await this.start(),J(`[otel-proxy] installed route pattern: ${n} (basePath=${t}, upstreamBase=${this.config.upstreamUrl})`)}async uninstall(e){if(!this.isInstalled)return;let t=`**${this.config.localPath}**`;try{await e.unroute(t)}catch{}this.isInstalled=!1,await this.stop()}async start(){if(this.isRunning)return;this.isRunning=!0;let e=Math.max(1,this.config.concurrency);for(let t=0;t<e;t++){let n=this._workerLoop(t);this.workers.push(n)}J(`[otel-proxy] started with concurrency=${e}, 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}J("[otel-proxy] stopped")}}async _handleRoute(e){let t=e.request();if(this.metrics.routedRequests++,t.method().toUpperCase()==="OPTIONS"){await this._fulfillFast(e);return}if(this.config.shouldForward&&!this.config.shouldForward(t)){await this._fulfillFast(e);return}let n=t.url(),r=this.config.localPath,i=Gc(n,r);if(!i){await e.fallback();return}let a=Kc(this.config.upstreamUrl,i,n),u=await t.postDataBuffer()??Buffer.alloc(0),c=t.headers()["content-type"]??"application/x-protobuf",p=t.method(),g={"content-type":c};if(this.config.upstreamHeaders)for(let[y,P]of Object.entries(this.config.upstreamHeaders))g[y]=P;if(this.queue.length>=this.config.maxQueueSize){this.metrics.droppedBatches++,await this._fulfillFast(e),ss(`[otel-proxy] dropped batch (queue full: ${this.queue.length}/${this.config.maxQueueSize}) suffix=${i}`);return}let f={body:u,contentType:c,createdAtMs:Date.now(),upstreamUrl:a,method:p,headers:g};this.queue.push(f),this.metrics.acceptedBatches++,await this._fulfillFast(e)}async _fulfillFast(e){let t=this.config.respondNoContent?204:200;if(t===204){await e.fulfill({status:t});return}await e.fulfill({status:t,headers:{"content-type":"text/plain; charset=utf-8"},body:""})}async _workerLoop(e){for(;this.isRunning;){let t=this.queue.shift();if(!t){await this._sleep(25);continue}this.metrics.inFlight++;try{await this._forwardUpstream(t),this.metrics.forwardedBatches++}catch(n){this.metrics.failedBatches++;let r=n instanceof Error?n.message:String(n);this.metrics.lastError=r,ss(`[otel-proxy] worker=${e} forward failed: ${r}`)}finally{this.metrics.inFlight--}}}async _forwardUpstream(e){let t=await fetch(e.upstreamUrl,{method:e.method,headers:e.headers,body:new Uint8Array(e.body)});if(t.status<200||t.status>=300){let n=await this._safeReadText(t);throw new Error(`upstream returned ${t.status} for ${e.upstreamUrl}: ${n}`)}}async _safeReadText(e){try{return(await e.text()).slice(0,500)}catch{return""}}async _sleep(e){await new Promise(t=>{setTimeout(()=>t(),e)})}};import*as vr from"node:fs";import*as Ot from"node:path";import{fileURLToPath as Xc}from"node:url";var Yc=Xc(import.meta.url),Jc=Ot.dirname(Yc),Sr="/__mcp_otel/",Qc="otel-initializer.bundle.js";function Zc(){return rs?rs:Ot.join(Jc,"platform","browser","otel")}s(Zc,"_getOtelAssetsDir");function em(){if(gn==="otlp/http"||_n){if(!_n)throw new Error('OTEL exporter HTTP url must be set when OTEL exporter type is "otlp/http"');return{type:"otlp/http",url:Sr,upstreamURL:_n,headers:Js}}else{if(gn==="console")return{type:"console"};if(gn==="none")return{type:"none"};throw new Error(`Invalid OTEL exporter type ${gn}`)}}s(em,"_getOTELExporterConfig");function tm(){return{userInteractionEvents:Ys}}s(tm,"_getOTELInstrumentationConfig");function nm(){return{serviceName:Ks,serviceVersion:Xs,exporter:em(),instrumentation:tm(),debug:!1}}s(nm,"_getOTELConfig");function om(o,e){let t=Ot.isAbsolute(o)?o:Ot.join(process.cwd(),o),n=Ot.join(t,e);if(!vr.existsSync(n))throw new Error(`OTEL bundle not found at: ${n}`);return vr.readFileSync(n,"utf-8")}s(om,"_readBundleContent");async function rm(o,e){let t=Object.fromEntries([["traceId",e.traceId],["serviceName",e.serviceName],["serviceVersion",e.serviceVersion],["exporter",e.exporter],["instrumentation",e.instrumentation],["debug",e.debug]]);await o.evaluate(n=>{let r=globalThis;r.__MCP_DEVTOOLS__||(r.__MCP_DEVTOOLS__={});let i=s((a,l)=>a[l],"getK");r.__MCP_TRACE_ID__=i(n,"traceId"),r.__mcpOtel&&typeof r.__mcpOtel.init=="function"?r.__mcpOtel.init(n):(r.__MCP_DEVTOOLS__.otelInitialized=!1,r.__MCP_DEVTOOLS__.otelInitError="__mcpOtel.init is not available while applying config")},t).catch(n=>{let r=n instanceof Error?n.message:String(n);J(`[otel-controller] applyConfigToPage failed (ignored): ${r}`)})}s(rm,"_applyConfigToPage");function sm(o,e){let t=new WeakMap,n=s(a=>{if(t.has(a))return;let l=s(async u=>{u===a.mainFrame()&&await rm(a,e())},"onFrameNavigated");t.set(a,l),a.on("framenavigated",l)},"attachToPage");for(let a of o.pages())n(a);let r=s(a=>{n(a)},"onNewPage");o.on("page",r);let i=s(()=>{try{o.off("page",r)}catch{}for(let a of o.pages()){let l=t.get(a);if(l)try{a.off("framenavigated",l)}catch{}}},"detach");return J("[otel-controller] auto-sync installed (page+framenavigated)"),{detach:i}}s(sm,"_installAutoSync");var xr=class{static{s(this,"OTELController")}browserContext;config;proxy;initialized=!1;autoSyncDetach;constructor(e){this.browserContext=e,this.config=nm()}async init(e){if(this.initialized){J("[otel-controller] init skipped: BrowserContext already initialized");return}if(!e.traceId||!e.traceId.trim())throw new Error("[otel-controller] init requires a non-empty traceId");this.config.traceId=e.traceId;let t=Zc();this.config.exporter.type==="otlp/http"&&(this.proxy=new Tr({localPath:Sr,upstreamUrl:this.config.exporter.upstreamURL,upstreamHeaders:{...this.config.exporter.headers??{}}}),await this.proxy.install(this.browserContext)),J(`[otel-controller] exporter=${this.config.exporter.type} localBase=${Sr}`+(this.config.exporter.type==="otlp/http"?` upstreamBase=${this.config.exporter.upstreamURL}`:""));let n=om(t,Qc),r=sm(this.browserContext,()=>this.config);this.autoSyncDetach=r.detach,await this.browserContext.addInitScript({content:n});let i=Object.fromEntries([["traceId",this.config.traceId],["serviceName",this.config.serviceName],["serviceVersion",this.config.serviceVersion],["exporter",this.config.exporter],["instrumentation",this.config.instrumentation],["debug",this.config.debug]]);await this.browserContext.addInitScript(a=>{let l=globalThis;l.__MCP_DEVTOOLS__||(l.__MCP_DEVTOOLS__={});let u=s((m,c)=>m[c],"getK");l.__MCP_TRACE_ID__=u(a,"traceId"),l.__mcpOtel&&typeof l.__mcpOtel.init=="function"?l.__mcpOtel.init(a):(l.__MCP_DEVTOOLS__.otelInitialized=!1,l.__MCP_DEVTOOLS__.otelInitError="__mcpOtel.init is not available (initializer bundle did not install)")},i),this.initialized=!0,J("[otel-controller] init installed: bundle + config init scripts + auto-sync")}isOTELRequest(e){return new URL(e.url()).pathname.startsWith(Sr)}async isInitialized(e){return await e.evaluate(()=>globalThis.__MCP_DEVTOOLS__?.otelInitialized===!0)}async getInitError(e){return await e.evaluate(()=>{let n=globalThis.__MCP_DEVTOOLS__?.otelInitError;if(typeof n=="string"&&n.trim())return n})}async getTraceId(e){return await e.evaluate(()=>{let t=globalThis;if(t.__mcpOtel&&typeof t.__mcpOtel.getTraceId=="function"){let r=t.__mcpOtel.getTraceId();if(typeof r=="string"&&r.trim())return r}let n=t.__MCP_TRACE_ID__;if(typeof n=="string"&&n.trim())return n})}async setTraceId(e,t){this.config.traceId=t,await e.evaluate(n=>{let r=globalThis;r.__mcpOtel&&typeof r.__mcpOtel.setTraceId=="function"?r.__mcpOtel.setTraceId(n):r.__MCP_TRACE_ID__=n},t)}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 Ir=class{static{s(this,"BrowserToolSessionContext")}_sessionId;options;otelController;consoleMessages=[];httpRequests=[];initialized=!1;closed=!1;traceId;_numOfInFlightRequests=0;_lastNetworkActivityTimestamp=0;browserContext;page;constructor(e,t,n,r){this._sessionId=e,this.browserContext=t,this.page=n,this.options=r,this.otelController=new xr(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 e=this,t=0;this.page.on("console",r=>{e.consoleMessages.push(e._toConsoleMessage(r,++t)),e.consoleMessages.length>dn&&e.consoleMessages.splice(0,e.consoleMessages.length-dn)}),this.page.on("pageerror",r=>{e.consoleMessages.push(e._errorToConsoleMessage(r,++t)),e.consoleMessages.length>dn&&e.consoleMessages.splice(0,e.consoleMessages.length-dn)});let n=0;this.page.on("request",async r=>{e.otelController.isOTELRequest(r)||(e._numOfInFlightRequests++,e._lastNetworkActivityTimestamp=Date.now())}),this.page.on("requestfinished",async r=>{e.otelController.isOTELRequest(r)||(e._numOfInFlightRequests--,e._lastNetworkActivityTimestamp=Date.now(),e.httpRequests.push(await e._toHttpRequest(r,++n)),e.httpRequests.length>bn&&e.httpRequests.splice(0,e.httpRequests.length-bn))}),this.page.on("requestfailed",async r=>{e.otelController.isOTELRequest(r)||(e._numOfInFlightRequests--,e._lastNetworkActivityTimestamp=Date.now(),e.httpRequests.push(await e._toHttpRequest(r,++n)),e.httpRequests.length>bn&&e.httpRequests.splice(0,e.httpRequests.length-bn))}),this.options.otelEnable&&(this.traceId=nr(),await this.otelController.init({traceId:this.traceId})),this.initialized=!0}_toConsoleMessageLevelName(e){switch(e){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(e,t){let n=Date.now(),r=this._toConsoleMessageLevelName(e.type()),i=Qt[r].code;return{type:e.type(),text:e.text(),level:{name:r,code:i},location:{url:e.location().url,lineNumber:e.location().lineNumber,columnNumber:e.location().columnNumber},timestamp:n,sequenceNumber:t}}_errorToConsoleMessage(e,t){let n=Date.now();return e instanceof Error?{type:"error",text:e.message,level:{name:"error",code:3},timestamp:n,sequenceNumber:t}:{type:"error",text:String(e),level:{name:"error",code:3},timestamp:n,sequenceNumber:t}}_isBodyLikelyPresent(e,t){return!(t==="HEAD"||t==="OPTIONS"||e===204||e===304||e>=300&&e<400)}async _safeReadResponseBody(e){try{let n=e.request().method(),r=e.status();return this._isBodyLikelyPresent(r,n)?(await e.body()).toString("utf-8"):void 0}catch{return}}async _toHttpRequest(e,t){let n=await e.response();return{url:e.url(),method:e.method(),headers:e.headers(),body:e.postData()||void 0,resourceType:e.resourceType(),failure:e.failure()?.errorText,duration:e.timing().responseEnd,response:n?{status:n.status(),statusText:n.statusText(),headers:n.headers(),body:await this._safeReadResponseBody(n)}:void 0,ok:n?n.ok():!1,timestamp:Math.floor(e.timing().startTime),sequenceNumber:t}}numOfInFlightRequests(){return this._numOfInFlightRequests}lastNetworkActivityTimestamp(){return this._lastNetworkActivityTimestamp}sessionId(){return this._sessionId}async getTraceId(){return this.traceId}async setTraceId(e){if(!this.options.otelEnable)throw new Error("OTEL is not enabled");this.traceId=e,await this.otelController.setTraceId(this.page,e)}getConsoleMessages(){return this.consoleMessages}getHttpRequests(){return this.httpRequests}async close(){if(this.closed)return!1;J(`Closing OTEL controller of the session with id ${this._sessionId} ...`),await this.otelController.close();try{J(`Closing browser context of the session with id ${this._sessionId} ...`),await Sl(this.browserContext)}catch(e){J(`Error occurred while closing browser context of the session with id ${this._sessionId} ...`,e)}return this.consoleMessages.length=0,this.httpRequests.length=0,this.closed=!0,!0}};var Cr=class{static{s(this,"BrowserToolExecutor")}sessionIdProvider;sessionContext;constructor(e){this.sessionIdProvider=e}async _createSessionContext(){let e=await wl(),t=await Tl(e.browserContext),n=this.sessionIdProvider(),r=new Ir(n,e.browserContext,t,{otelEnable:Gs});return await r.init(),r}async _sessionContext(){return this.sessionContext||(this.sessionContext=await this._createSessionContext(),J(`Created session context on the first tool call for the session with id ${this.sessionContext.sessionId()}`)),this.sessionContext}async executeTool(e,t){J(`Executing tool ${e.name()} with input: ${hn(t)}`);try{let n=await this._sessionContext(),r=await e.handle(n,t);return J(`Executed tool ${e.name()} and got output: ${hn(r)}`),r}catch(n){throw J(`Error occurred while executing ${e.name()}: ${n}`),n}}};var Er=[...Ni,...Di,...ia,...Ca,..._a,...Ma,...Ba,...za,...Xa,...ul,...bl];function xl(o){return new Cr(o)}s(xl,"createToolExecutor");import{Option as qt}from"commander";var Ds=class{static{s(this,"BrowserCliProvider")}platform="browser";cliName="browser-devtools-cli";tools=Er;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(e){let t={...process.env};return e.headless!==void 0&&(t.BROWSER_HEADLESS_ENABLE=String(e.headless)),e.persistent!==void 0&&(t.BROWSER_PERSISTENT_ENABLE=String(e.persistent)),e.userDataDir!==void 0&&(t.BROWSER_PERSISTENT_USER_DATA_DIR=e.userDataDir),e.useSystemBrowser!==void 0&&(t.BROWSER_USE_INSTALLED_ON_SYSTEM=String(e.useSystemBrowser)),e.browserPath!==void 0&&(t.BROWSER_EXECUTABLE_PATH=e.browserPath),t}addOptions(e){return e.addOption(new qt("--headless","Run browser in headless mode (no visible window)").default(Gt)).addOption(new qt("--no-headless","Run browser in headful mode (visible window)")).addOption(new qt("--persistent","Use persistent browser context (preserves cookies, localStorage)").default(Kt)).addOption(new qt("--no-persistent","Use ephemeral browser context (cleared on session end)")).addOption(new qt("--user-data-dir <path>","Directory for persistent browser context user data").default(Xt)).addOption(new qt("--use-system-browser","Use system-installed Chrome instead of bundled browser").default(Yt)).addOption(new qt("--browser-path <path>","Custom browser executable path"))}getConfig(){return{headless:Gt,persistent:Kt,userDataDir:Xt,useSystemBrowser:Yt,executablePath:Pn,locale:kn}}formatConfig(e){let t=[" Browser:",` Headless: ${e.headless}`,` Persistent: ${e.persistent}`,` User Data Dir: ${e.userDataDir||"(default)"}`,` Use System Browser: ${e.useSystemBrowser}`,` Executable Path: ${e.executablePath||"(bundled)"}`];return e.locale&&t.push(` Locale: ${e.locale}`),t.join(`
777
- `)}formatConfigForRepl(e){return[` headless = ${e.headless??Gt}`,` persistent = ${e.persistent??Kt}`,` user-data-dir = ${e.userDataDir||Xt||"(default)"}`,` use-system-browser = ${e.useSystemBrowser??Yt}`,` browser-path = ${e.browserPath||"(auto)"}`].join(`
778
- `)}},Il=new Ds;var Cl=`
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
- `,El=`
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 Ol={serverInfo:{instructions:Cl,policies:[El]},toolsInfo:{tools:Er,createToolExecutor:xl},cliInfo:{cliProvider:Il}};import{z as Re}from"zod";var Or=class{static{s(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:Re.number().int().positive().describe("Process ID to connect to").optional(),processName:Re.string().describe('Process name pattern to search for (e.g., "server.js", "api")').optional(),containerId:Re.string().describe("Docker container ID - process runs inside this container").optional(),containerName:Re.string().describe("Docker container name or pattern (e.g., my-node-app) - resolved via docker ps -f name=").optional(),host:Re.string().describe("Inspector host (default: 127.0.0.1); for containerized MCP use host.docker.internal or container name").optional(),port:Re.number().int().positive().describe("Inspector port (default: 9229); for Docker use host-mapped port").optional(),wsUrl:Re.string().describe("Direct WebSocket URL (e.g., ws://127.0.0.1:9229/abc-123)").optional()}}outputSchema(){return{connected:Re.boolean().describe("Whether connection was successful"),pid:Re.number().describe("Process ID"),command:Re.string().optional().describe("Process command line"),containerId:Re.string().optional().describe("Docker container ID when connected via container"),inspectorHost:Re.string().optional().describe("Inspector host"),inspectorPort:Re.number().optional().describe("Inspector port"),webSocketUrl:Re.string().optional().describe("WebSocket URL"),title:Re.string().describe("Target title")}}async handle(e,t){let n=await e.connect({pid:t.pid,processName:t.processName,containerId:t.containerId,containerName:t.containerName,host:t.host,port:t.port,wsUrl:t.wsUrl,activateIfNeeded:!0});return{connected:!0,pid:n.processInfo.pid,command:n.processInfo.command,containerId:n.processInfo.containerId,inspectorHost:n.processInfo.inspectorHost,inspectorPort:n.processInfo.inspectorPort,webSocketUrl:n.processInfo.webSocketUrl,title:n.target.title}}};import{z as im}from"zod";var Nr=class{static{s(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:im.boolean().describe("Whether disconnection was successful")}}async handle(e,t){return await e.disconnect(),{disconnected:!0}}};import{z as we}from"zod";function Nl(o,e,t,n,r){let i;if(e)i=mi(o,e);else if(r){let a=bt(o),l=new Set(a.filter(m=>m.kind===r).map(m=>m.id)),u=Ln(o);r==="tracepoint"?i=u.filter(m=>l.has(m.probeId)||m.probeId==="__exception__"):i=u.filter(m=>l.has(m.probeId))}else i=Ln(o);return t!==void 0&&(i=i.filter(a=>a.sequenceNumber>t)),n!==void 0&&(i=i.slice(-n)),i}s(Nl,"_filterSnapshots");var Pr=class{static{s(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:we.string().describe("Filter by specific tracepoint ID").optional(),fromSequence:we.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:we.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:we.array(we.any()).describe("Captured snapshots"),count:we.number().describe("Number of snapshots returned")}}async handle(e,t){let n=Nl(e.storeKey,t.probeId,t.fromSequence,t.limit,"tracepoint");return{snapshots:n,count:n.length}}},kr=class{static{s(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:we.string().describe("Filter by specific logpoint ID").optional(),fromSequence:we.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence").optional(),limit:we.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:we.array(we.any()).describe("Captured snapshots"),count:we.number().describe("Number of snapshots returned")}}async handle(e,t){let n=Nl(e.storeKey,t.probeId,t.fromSequence,t.limit,"logpoint");return{snapshots:n,count:n.length}}},Rr=class{static{s(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:we.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence").optional(),limit:we.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:we.array(we.any()).describe("Captured snapshots"),count:we.number().describe("Number of snapshots returned")}}async handle(e,t){let r=Ln(e.storeKey).filter(i=>i.probeId==="__exception__");return t.fromSequence!==void 0&&(r=r.filter(i=>i.sequenceNumber>t.fromSequence)),t.limit!==void 0&&(r=r.slice(-t.limit)),{snapshots:r,count:r.length}}},_r=class{static{s(this,"ClearTracepointSnapshots")}name(){return"debug_clear-tracepoint-snapshots"}description(){return"Clears tracepoint snapshots. Optionally filter by specific tracepoint ID."}inputSchema(){return{probeId:we.string().describe("Clear only snapshots for this tracepoint ID").optional()}}outputSchema(){return{cleared:we.number().describe("Number of snapshots cleared")}}async handle(e,t){let{clearSnapshots:n,clearSnapshotsByProbe:r}=await import("./core-B3VLZZCP.js");return{cleared:t.probeId?r(e.storeKey,t.probeId):n(e.storeKey)}}},Mr=class{static{s(this,"ClearLogpointSnapshots")}name(){return"debug_clear-logpoint-snapshots"}description(){return"Clears logpoint snapshots. Optionally filter by specific logpoint ID."}inputSchema(){return{probeId:we.string().describe("Clear only snapshots for this logpoint ID").optional()}}outputSchema(){return{cleared:we.number().describe("Number of snapshots cleared")}}async handle(e,t){let{clearSnapshotsByProbe:n,clearSnapshots:r}=await import("./core-B3VLZZCP.js");return{cleared:t.probeId?n(e.storeKey,t.probeId):r(e.storeKey)}}},Dr=class{static{s(this,"ClearExceptionpointSnapshots")}name(){return"debug_clear-exceptionpoint-snapshots"}description(){return"Clears all exception snapshots."}inputSchema(){return{}}outputSchema(){return{cleared:we.number().describe("Number of snapshots cleared")}}async handle(e,t){let{clearSnapshotsByProbe:n}=await import("./core-B3VLZZCP.js");return{cleared:n(e.storeKey,"__exception__")}}};import{z as Ne}from"zod";var Ar=class{static{s(this,"GetLogs")}name(){return"debug_get-logs"}description(){return"Retrieves console messages/logs from the Node.js process with filtering options."}inputSchema(){return{type:Ne.enum(ve(dt)).transform(st(dt)).describe(`Type of console messages to retrieve. When specified, messages with equal or higher levels are retrieved. Valid values: ${ve(dt).join(", ")}.`).optional(),search:Ne.string().describe("Text to search for in console messages.").optional(),timestamp:Ne.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:Ne.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:Ne.object({count:Ne.number().int().nonnegative().default(0).describe("Max number of messages. 0 = no limit."),from:Ne.enum(["start","end"]).default("end").describe("Which side to keep when truncated.")}).describe("Maximum number of console messages to return.").optional()}}outputSchema(){return{messages:Ne.array(Ne.object({type:Ne.string().describe("Type of the console message."),text:Ne.string().describe("Text of the console message."),location:Ne.object({url:Ne.string().describe("URL of the resource."),lineNumber:Ne.number().nonnegative().describe("0-based line number."),columnNumber:Ne.number().nonnegative().describe("0-based column number.")}).describe("Location of the console message.").optional(),timestamp:Ne.number().int().nonnegative().describe("Unix epoch timestamp (ms)."),sequenceNumber:Ne.number().int().nonnegative().describe("Monotonic sequence number.")})).describe("Retrieved console messages.")}}async handle(e,t){let n=t.type?Qt[t.type]?.code:void 0,r=di(e.storeKey).filter(l=>!(n!==void 0&&l.level.code<n||t.timestamp&&l.timestamp<t.timestamp||t.sequenceNumber&&l.sequenceNumber<=t.sequenceNumber||t.search&&!l.text.includes(t.search)));return{messages:(t.limit?.count?t.limit.from==="start"?r.slice(0,t.limit.count):r.slice(-t.limit.count):r).map(l=>({type:l.type,text:l.text,location:l.location?{url:l.location.url,lineNumber:l.location.lineNumber,columnNumber:l.location.columnNumber}:void 0,timestamp:l.timestamp,sequenceNumber:l.sequenceNumber}))}}};import{z as ct}from"zod";var Lr=class{static{s(this,"RemoveTracepoint")}name(){return"debug_remove-tracepoint"}description(){return"Removes a tracepoint by its ID."}inputSchema(){return{id:ct.string().describe("Tracepoint ID to remove")}}outputSchema(){return{removed:ct.boolean().describe("Whether the tracepoint was removed")}}async handle(e,t){return{removed:await fn(e.storeKey,t.id)}}},Fr=class{static{s(this,"ListTracepoints")}name(){return"debug_list-tracepoints"}description(){return"Lists all active tracepoints on the Node.js process."}inputSchema(){return{}}outputSchema(){return{tracepoints:ct.array(ct.any()).describe("Active tracepoints")}}async handle(e,t){return{tracepoints:bt(e.storeKey).filter(r=>r.kind==="tracepoint").map(r=>({id:r.id,urlPattern:r.urlPattern,lineNumber:r.lineNumber,columnNumber:r.columnNumber,condition:r.condition,hitCondition:r.hitCondition,hitCount:r.hitCount,resolvedLocations:r.resolvedLocations,enabled:r.enabled}))}}},Ur=class{static{s(this,"ClearTracepoints")}name(){return"debug_clear-tracepoints"}description(){return"Removes all tracepoints from the Node.js process."}inputSchema(){return{}}outputSchema(){return{cleared:ct.number().describe("Number of tracepoints cleared")}}async handle(e,t){let n=bt(e.storeKey).filter(i=>i.kind==="tracepoint"),r=0;for(let i of n)await fn(e.storeKey,i.id)&&r++;return{cleared:r}}},Hr=class{static{s(this,"RemoveLogpoint")}name(){return"debug_remove-logpoint"}description(){return"Removes a logpoint by its ID."}inputSchema(){return{id:ct.string().describe("Logpoint ID to remove")}}outputSchema(){return{removed:ct.boolean().describe("Whether the logpoint was removed")}}async handle(e,t){return{removed:await fn(e.storeKey,t.id)}}},Wr=class{static{s(this,"ListLogpoints")}name(){return"debug_list-logpoints"}description(){return"Lists all active logpoints on the Node.js process."}inputSchema(){return{}}outputSchema(){return{logpoints:ct.array(ct.any()).describe("Active logpoints")}}async handle(e,t){return{logpoints:bt(e.storeKey).filter(r=>r.kind==="logpoint").map(r=>({id:r.id,urlPattern:r.urlPattern,lineNumber:r.lineNumber,logExpression:r.logExpression,condition:r.condition,hitCondition:r.hitCondition,hitCount:r.hitCount,resolvedLocations:r.resolvedLocations,enabled:r.enabled}))}}},qr=class{static{s(this,"ClearLogpoints")}name(){return"debug_clear-logpoints"}description(){return"Removes all logpoints from the Node.js process."}inputSchema(){return{}}outputSchema(){return{cleared:ct.number().describe("Number of logpoints cleared")}}async handle(e,t){let n=bt(e.storeKey).filter(i=>i.kind==="logpoint"),r=0;for(let i of n)await fn(e.storeKey,i.id)&&r++;return{cleared:r}}};import{z as Bs}from"zod";var jr=class{static{s(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:Bs.enum(["none","uncaught","all"]).describe("Exception tracepoint state")}}outputSchema(){return{state:Bs.string().describe("New exception tracepoint state"),previousState:Bs.string().describe("Previous state")}}async handle(e,t){let n=Bn(e.storeKey);return await ci(e.storeKey,t.state),{state:t.state,previousState:n}}};import{z as et}from"zod";var $r=class{static{s(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:et.string().describe('Script file path pattern (e.g., "server.js"). Auto-escaped.'),lineNumber:et.number().int().positive().describe("Line number (1-based)"),columnNumber:et.number().int().nonnegative().describe("Column number (1-based). Optional.").optional(),logExpression:et.string().describe("Expression to evaluate and log when hit"),condition:et.string().describe("Conditional expression - logpoint only hits if this evaluates to true").optional(),hitCondition:et.string().describe("Hit count condition").optional()}}outputSchema(){return{id:et.string().describe("Logpoint ID"),urlPattern:et.string().describe("URL pattern"),lineNumber:et.number().describe("Line number"),logExpression:et.string().describe("Log expression"),resolvedLocations:et.number().describe("Number of locations resolved")}}async handle(e,t){let n=await An(e.storeKey,{kind:"logpoint",urlPattern:t.urlPattern,lineNumber:t.lineNumber,columnNumber:t.columnNumber,logExpression:t.logExpression,condition:t.condition,hitCondition:t.hitCondition});return{id:n.id,urlPattern:n.urlPattern,lineNumber:n.lineNumber,logExpression:n.logExpression||"",resolvedLocations:n.resolvedLocations}}};import{z as ze}from"zod";var zr=class{static{s(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:ze.string().describe('Script file path pattern (e.g., "server.js"). Auto-escaped.'),lineNumber:ze.number().int().positive().describe("Line number (1-based)"),columnNumber:ze.number().int().nonnegative().describe("Column number (1-based). Optional.").optional(),condition:ze.string().describe("Conditional expression - only triggers if this evaluates to true").optional(),hitCondition:ze.string().describe('Hit count condition, e.g., "== 5", ">= 10", "% 10 == 0"').optional()}}outputSchema(){return{id:ze.string().describe("Tracepoint ID"),urlPattern:ze.string().describe("URL pattern"),lineNumber:ze.number().describe("Line number"),columnNumber:ze.number().optional().describe("Column number"),condition:ze.string().optional().describe("Condition expression"),hitCondition:ze.string().optional().describe("Hit count condition"),resolvedLocations:ze.number().describe("Number of locations where tracepoint was resolved")}}async handle(e,t){let n=await An(e.storeKey,{kind:"tracepoint",urlPattern:t.urlPattern,lineNumber:t.lineNumber,columnNumber:t.columnNumber,condition:t.condition,hitCondition:t.hitCondition});return{id:n.id,urlPattern:n.urlPattern,lineNumber:n.lineNumber,columnNumber:n.columnNumber,condition:n.condition,hitCondition:n.hitCondition,resolvedLocations:n.resolvedLocations}}};import{z as Nt}from"zod";var Vr=class{static{s(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:Nt.string().describe("Generated script URL (e.g. file:///path/to/dist/app.js)"),line:Nt.number().int().positive().describe("Line number in generated code (1-based)"),column:Nt.number().int().nonnegative().describe("Column number in generated code (1-based, default 1)").optional()}}outputSchema(){return{resolved:Nt.boolean().describe("Whether the location was resolved to original source"),source:Nt.string().optional().describe("Original source file path"),line:Nt.number().optional().describe("Line number in original source (1-based)"),column:Nt.number().optional().describe("Column number in original source (1-based)"),name:Nt.string().optional().describe("Original identifier name if available")}}async handle(e,t){let n=await ui(e.storeKey,t.url,t.line,t.column??1);return n?{resolved:!0,source:n.source,line:n.line,column:n.column,name:n.name}:{resolved:!1}}};import{z as ft}from"zod";var Gr=class{static{s(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:ft.boolean().describe("Whether connected to a Node.js process"),enabled:ft.boolean().describe("Whether debugging is enabled"),pid:ft.number().optional().describe("Connected process PID"),hasSourceMaps:ft.boolean().describe("Whether source maps are loaded"),exceptionBreakpoint:ft.string().describe("Exceptionpoint state"),tracepointCount:ft.number().describe("Number of tracepoints"),logpointCount:ft.number().describe("Number of logpoints"),watchExpressionCount:ft.number().describe("Number of watch expressions"),snapshotStats:ft.any().nullable().describe("Snapshot statistics")}}async handle(e,t){if(!e.isConnected)return{connected:!1,enabled:!1,hasSourceMaps:!1,exceptionBreakpoint:"none",tracepointCount:0,logpointCount:0,watchExpressionCount:0,snapshotStats:null};let n=e.storeKey,r=li(n),i=bt(n);return{connected:!0,enabled:r,pid:e.processInfo?.pid,hasSourceMaps:fi(n),exceptionBreakpoint:Bn(n),tracepointCount:i.filter(a=>a.kind==="tracepoint").length,logpointCount:i.filter(a=>a.kind==="logpoint").length,watchExpressionCount:Fn(n).length,snapshotStats:r?pi(n):null}}};import{z as Pt}from"zod";var Kr=class{static{s(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:Pt.string().describe("JavaScript expression to watch")}}outputSchema(){return{id:Pt.string().describe("Watch expression ID"),expression:Pt.string().describe("The expression")}}async handle(e,t){let n=bi(e.storeKey,t.expression);return{id:n.id,expression:n.expression}}},Xr=class{static{s(this,"RemoveWatch")}name(){return"debug_remove-watch"}description(){return"Removes a watch expression by its ID."}inputSchema(){return{id:Pt.string().describe("Watch expression ID to remove")}}outputSchema(){return{removed:Pt.boolean().describe("Whether the watch was removed")}}async handle(e,t){return{removed:gi(e.storeKey,t.id)}}},Yr=class{static{s(this,"ListWatches")}name(){return"debug_list-watches"}description(){return"Lists all active watch expressions."}inputSchema(){return{}}outputSchema(){return{watches:Pt.array(Pt.any()).describe("Active watch expressions")}}async handle(e,t){return{watches:Fn(e.storeKey)}}},Jr=class{static{s(this,"ClearWatches")}name(){return"debug_clear-watches"}description(){return"Removes all watch expressions."}inputSchema(){return{}}outputSchema(){return{cleared:Pt.number().describe("Number of watches cleared")}}async handle(e,t){return{cleared:hi(e.storeKey)}}};var Pl=[new Or,new Nr,new Gr,new zr,new Lr,new Fr,new Ur,new $r,new Hr,new Wr,new qr,new jr,new Pr,new _r,new kr,new Mr,new Rr,new Dr,new Ar,new Vr,new Kr,new Xr,new Yr,new Jr];import{z as As}from"zod";var Qr=class{static{s(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:As.string().describe("JavaScript code to execute in the Node process."),timeoutMs:As.number().int().min(100).max(3e4).describe("Max evaluation time in milliseconds (default: 5000, max: 30000).").optional()}}outputSchema(){return{result:As.any().describe("The result of the evaluation. Can be primitives, arrays, or objects. Must be serializable (JSON-compatible).")}}async handle(e,t){return{result:await yi(e.storeKey,t.script,t.timeoutMs??5e3)}}};var kl=[new Qr];import{EventEmitter as am}from"node:events";import{WebSocket as lm}from"ws";var Ls=class extends am{static{s(this,"NodeCDPSession")}ws=null;reqId=0;pending=new Map;connected=!1;wsUrl;constructor(e){super(),this.wsUrl=e}async connect(){if(!this.connected)return new Promise((e,t)=>{this.ws=new lm(this.wsUrl);let n=setTimeout(()=>{t(new Error(`Connection timeout to ${this.wsUrl}`)),this.ws?.close()},1e4);this.ws.on("open",()=>{clearTimeout(n),this.connected=!0,e()}),this.ws.on("error",r=>{clearTimeout(n),this.connected||t(r)}),this.ws.on("close",()=>{this.connected=!1;for(let[r,i]of this.pending)i.reject(new Error("CDP session closed"));this.pending.clear()}),this.ws.on("message",r=>{try{let i=JSON.parse(r.toString());this._handleMessage(i)}catch{}})})}async send(e,t){if(!this.ws||!this.connected)throw new Error("CDP session is not connected");let n=++this.reqId;return new Promise((r,i)=>{this.pending.set(n,{resolve:r,reject:i});let a=JSON.stringify({id:n,method:e,params:t||{}});this.ws.send(a,l=>{l&&(this.pending.delete(n),i(l))}),setTimeout(()=>{this.pending.has(n)&&(this.pending.delete(n),i(new Error(`CDP command timeout: ${e}`)))},3e4)})}async detach(){if(this.ws){this.connected=!1,this.ws.close(),this.ws=null;for(let[,e]of this.pending)e.reject(new Error("CDP session detached"));this.pending.clear()}}isConnected(){return this.connected}_handleMessage(e){if(e.id!==void 0){let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.error?t.reject(new Error(`CDP error: ${e.error.message||JSON.stringify(e.error)}`)):t.resolve(e.result||{}))}else e.method&&this.emit(e.method,e.params)}};async function In(o){let e=new Ls(o);return await e.connect(),e}s(In,"createNodeCDPSession");import{execSync as Cn}from"node:child_process";import*as Rl from"node:http";var kt="127.0.0.1",cn=9229,Fs=1e4,_l=200,um=20;async function Zr(o=kt,e=cn,t=5e3){return new Promise((n,r)=>{let i=setTimeout(()=>{r(new Error(`Inspector discovery timeout on ${o}:${e}`))},t),a=Rl.get(`http://${o}:${e}/json/list`,l=>{let u="";l.on("data",m=>{u+=m}),l.on("end",()=>{clearTimeout(i);try{let m=JSON.parse(u);n(m)}catch{r(new Error(`Invalid response from inspector at ${o}:${e}`))}})});a.on("error",l=>{clearTimeout(i),r(new Error(`Cannot reach inspector at ${o}:${e}: ${l.message}`))}),a.end()})}s(Zr,"discoverInspectorTargets");async function cm(o=kt,e=cn,t=um){for(let n=e;n<e+t;n++)try{let r=await Zr(o,n,1e3);if(r.length>0)return{port:n,targets:r}}catch{}return null}s(cm,"scanForInspector");function mm(o){try{let e=process.platform,t;e==="win32"?t=Cn(`wmic process where "name like '%node%'" get ProcessId,CommandLine /format:csv`,{encoding:"utf-8",timeout:5e3}):t=Cn('ps aux | grep -E "[n]ode|[t]s-node|[n]px"',{encoding:"utf-8",timeout:5e3});let n=[];for(let r of t.split(`
1094
- `)){let i=r.trim();if(i)if(e==="win32"){let a=i.split(",");if(a.length>=3){let l=parseInt(a[a.length-1],10),u=a.slice(1,-1).join(",");!isNaN(l)&&l>0&&n.push({pid:l,command:u})}}else{let a=i.split(/\s+/);if(a.length>=11){let l=parseInt(a[1],10),u=a.slice(10).join(" ");!isNaN(l)&&l>0&&n.push({pid:l,command:u})}}}if(o){let r=new RegExp(o,"i");return n.filter(i=>r.test(i.command))}return n}catch{return[]}}s(mm,"findNodeProcesses");async function pm(o,e=kt,t=Fs){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(o,0)}catch{throw new Error(`Process ${o} does not exist or is not accessible`)}J(`Sending SIGUSR1 to process ${o} to activate V8 Inspector...`),process.kill(o,"SIGUSR1");let n=Date.now();for(;Date.now()-n<t;){let r=await cm(e,cn,10);if(r)return J(`Inspector activated on port ${r.port} for process ${o}`),r;await new Promise(i=>setTimeout(i,_l))}throw new Error(`Timeout waiting for inspector to activate on process ${o}`)}s(pm,"activateInspector");function dm(o){try{let t=Cn(`docker ps -q -f name=${o}`,{encoding:"utf-8",timeout:5e3}).trim().split(`
1095
- `).filter(Boolean);return t.length===0?null:(t.length>1&&J(`Multiple containers match "${o}", using first: ${t[0]}`),t[0])}catch(e){if(/Cannot connect to the Docker daemon|docker: command not found/i.test(e.message??""))throw new Error(`${e.message} When MCP runs in a container, mount /var/run/docker.sock and ensure the docker CLI is available.`);return null}}s(dm,"resolveContainerId");async function bm(o,e=kt,t=cn,n=Fs){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 r;try{let a=Cn(`docker exec ${o} sh -c "ps aux 2>/dev/null | grep '[n]ode' | head -1"`,{encoding:"utf-8",timeout:5e3}).trim();if(!a)throw new Error(`No Node.js process found inside container ${o}`);if(r=a.split(/\s+/).filter(Boolean)[1]||"",!r||!/^\d+$/.test(r))throw new Error(`Could not parse Node PID from container ${o}`)}catch(a){if(a.message?.includes("No Node.js process"))throw a;let l=/Cannot connect to the Docker daemon|docker: command not found/i.test(a.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 ${o}: ${a.message}. Ensure Docker is running and the container has a Node.js process.${l}`)}J(`Sending SIGUSR1 to Node process ${r} inside container ${o}...`);try{Cn(`docker exec ${o} kill -USR1 ${r}`,{encoding:"utf-8",timeout:5e3})}catch(a){let l=/Cannot connect to the Docker daemon|docker: command not found/i.test(a.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 ${o}: ${a.message}${l}`)}let i=Date.now();for(;Date.now()-i<n;){try{let a=await Zr(e,t,2e3);if(a.length>0)return J(`Inspector active at ${e}:${t} for container ${o}`),{port:t,targets:a}}catch{}await new Promise(a=>setTimeout(a,_l))}throw new Error(`Timeout waiting for inspector from container ${o}. 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.`)}s(bm,"activateInspectorInContainer");async function Ml(o){let e=o.host||kt,t=o.timeoutMs||Fs,n=o.activateIfNeeded!==!1;if(o.wsUrl)return J(`Connecting to Node.js inspector via WebSocket: ${o.wsUrl}`),{session:await In(o.wsUrl),processInfo:{pid:0,inspectorActive:!0,webSocketUrl:o.wsUrl},target:{id:"direct",type:"node",title:"Direct WebSocket connection",url:"",webSocketDebuggerUrl:o.wsUrl}};let r=o.containerId??null;if(!r&&o.containerName&&(r=dm(o.containerName),!r))throw new Error(`No running container found matching name: ${o.containerName}`);if(r){let m=o.port||cn,c=[];try{c=await Zr(e,m,3e3)}catch{}if(c.length===0&&n&&(J(`Inspector not active. Activating via SIGUSR1 in container ${r}...`),c=(await bm(r,e,m,t)).targets),c.length===0)throw new Error(`Cannot connect to Node.js in container ${r}. Inspector not active. Ensure port 9229 is exposed (e.g. -p 9229:9229) and use activateIfNeeded or start Node with --inspect.`);let p=c[0],g=p.webSocketDebuggerUrl;return e!==kt&&(g=g.replace(/ws:\/\/[^:]+:/,`ws://${e}:`)),{session:await In(g),processInfo:{pid:0,inspectorActive:!0,inspectorHost:e,inspectorPort:m,webSocketUrl:g,containerId:r},target:p}}let i=o.pid,a;if(!i&&o.processName){let m=mm(o.processName);if(m.length===0)throw new Error(`No Node.js process found matching: ${o.processName}`);if(m.length>1){let c=m.map(p=>` PID ${p.pid}: ${p.command}`).join(`
1096
- `);throw new Error(`Multiple Node.js processes match "${o.processName}":
1097
- ${c}
1098
- Please specify a PID directly.`)}i=m[0].pid,a=m[0].command,J(`Found Node.js process: PID ${i} - ${a}`)}let l=o.port||cn,u=[];try{u=await Zr(e,l,3e3)}catch{}if(u.length>0){let m=u[0];J(`Inspector already active at ${e}:${l}, connecting...`);let c=m.webSocketDebuggerUrl;return e!==kt&&(c=c.replace(/ws:\/\/[^:]+:/,`ws://${e}:`)),{session:await In(c),processInfo:{pid:i||0,command:a,inspectorActive:!0,inspectorHost:e,inspectorPort:l,webSocketUrl:c},target:m}}if(i&&n){J(`Inspector not active on ${e}:${l}. Activating via SIGUSR1 on PID ${i}...`);let{port:m,targets:c}=await pm(i,e,t);if(c.length===0)throw new Error(`Inspector activated on port ${m} but no targets found`);let p=c[0],g=p.webSocketDebuggerUrl;return e!==kt&&(g=g.replace(/ws:\/\/[^:]+:/,`ws://${e}:`)),{session:await In(g),processInfo:{pid:i,command:a,inspectorActive:!0,inspectorHost:e,inspectorPort:m,webSocketUrl:g},target:p}}throw i?new Error(`Cannot connect to process ${i}. 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.")}s(Ml,"connectToNodeProcess");var En=class{static{s(this,"NodeToolSessionContext")}_sessionId;_connection=null;_storeKey=null;closed=!1;constructor(e){this._sessionId=e}sessionId(){return this._sessionId}async connect(e){if(this._connection)throw new Error("Already connected to a Node.js process. Disconnect first.");J(`Connecting to Node.js process with options: ${JSON.stringify(e)}`);let t=await Ml(e);return this._connection=t,this._storeKey=si(t.processInfo.pid,t.processInfo.webSocketUrl),await ii(this._storeKey,t.session,{pid:t.processInfo.pid,command:t.processInfo.command}),J(`Connected to Node.js process: PID=${t.processInfo.pid}, store=${this._storeKey}`),{processInfo:t.processInfo,target:t.target}}async disconnect(){!this._connection||!this._storeKey||(J(`Disconnecting from Node.js process: ${this._storeKey}`),await ai(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 On=class{static{s(this,"NodeToolExecutor")}sessionIdProvider;sessionContext;constructor(e){this.sessionIdProvider=e}_sessionContext(){if(!this.sessionContext){let e=this.sessionIdProvider();this.sessionContext=new En(e),J(`Created Node.js session context for session ${e}`)}return this.sessionContext}async executeTool(e,t){J(`Executing Node.js tool ${e.name()} with input: ${hn(t)}`);try{let n=this._sessionContext(),r=await e.handle(n,t);return J(`Executed Node.js tool ${e.name()} successfully`),r}catch(n){throw J(`Error executing Node.js tool ${e.name()}: ${n}`),n}}};var Nn=[...Pl,...kl];function Us(o){return new On(o)}s(Us,"createToolExecutor");var Hs=class{static{s(this,"NodeCliProvider")}platform="node";cliName="node-devtools-cli";tools=Nn;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(e){return{...process.env}}addOptions(e){return e}getConfig(){return{consoleMessagesBufferSize:Rn}}formatConfig(e){return[" Node.js:",` Console Messages Buffer: ${e.consoleMessagesBufferSize??Rn}`].join(`
1099
- `)}formatConfigForRepl(e){return` console-messages-buffer = ${Rn}`}},Dl=new Hs;var Ws=`
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
- `,qs=`
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 Bl={serverInfo:{instructions:Ws,policies:[qs]},toolsInfo:{tools:Nn,createToolExecutor:Us},cliInfo:{cliProvider:Dl}};function gm(){return Vs==="node"?Bl:Ol}s(gm,"_resolvePlatformInfo");var lx=gm();export{lx as a};