Repository navigation
Expand file tree
/
Copy pathmcp-performance.go
More file actions
277 lines (249 loc) · 7.99 KB
/
Copy pathmcp-performance.go
File metadata and controls
277 lines (249 loc) · 7.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package devbrowser
import (
"fmt"
"strings"
"webtyp.com/context"
"webtyp.com/devbrowser/chromedp"
"webtyp.com/mcp"
)
// GetPerformanceJS extracts page performance metrics optimized for LLM consumption.
const GetPerformanceJS = `
(() => {
const m = {};
// Go WASM Heap & Allocations (dev builds via webtyp/devtools)
if (typeof window.__webtypMemStats === 'function') {
try { m.wasmMem = window.__webtypMemStats(); } catch (e) {}
}
// JS Heap (Chrome only)
if (performance.memory) {
m.heapUsed = performance.memory.usedJSHeapSize;
m.heapTotal = performance.memory.totalJSHeapSize;
m.heapLimit = performance.memory.jsHeapSizeLimit;
}
// Navigation timing
const nav = performance.getEntriesByType('navigation')[0];
if (nav) {
m.domInteractive = Math.round(nav.domInteractive - nav.startTime);
m.domLoaded = Math.round(nav.domContentLoadedEventEnd - nav.startTime);
m.fullLoad = Math.round(nav.loadEventEnd - nav.startTime);
}
// Paint timing
const paints = performance.getEntriesByType('paint');
for (let i = 0; i < paints.length; i++) {
if (paints[i].name === 'first-paint') m.fp = Math.round(paints[i].startTime);
if (paints[i].name === 'first-contentful-paint') m.fcp = Math.round(paints[i].startTime);
}
// DOM stats
m.domNodes = document.querySelectorAll('*').length;
let maxDepth = 0;
const walk = (el, d) => {
if (d > maxDepth) maxDepth = d;
const children = el.children;
for (let i = 0; i < children.length; i++) walk(children[i], d + 1);
};
if (document.body) walk(document.body, 0);
m.domDepth = maxDepth;
// Resources summary
const resources = performance.getEntriesByType('resource');
m.resourceCount = resources.length;
let totalTransfer = 0;
const wasmFiles = [];
for (let i = 0; i < resources.length; i++) {
const r = resources[i];
totalTransfer += r.transferSize || 0;
if (r.name.endsWith('.wasm')) {
wasmFiles.push({
name: r.name.split('/').pop(),
size: Math.round(r.transferSize / 1024),
duration: Math.round(r.duration)
});
}
}
m.totalTransferKB = Math.round(totalTransfer / 1024);
m.wasmFiles = wasmFiles;
return m;
})()
`
// FormatPerformanceReport builds a compact text report from raw JS metrics.
func FormatPerformanceReport(pageURL string, metrics map[string]any) string {
var b strings.Builder
fmt.Fprintf(&b, "Performance: %s\n", pageURL)
// Memory
if heapUsed, ok := metrics["heapUsed"].(float64); ok {
heapTotal, _ := metrics["heapTotal"].(float64)
heapLimit, _ := metrics["heapLimit"].(float64)
fmt.Fprintf(&b, "Memory: JS Heap %.1f/%.1f MB (limit %d MB)\n",
heapUsed/1048576, heapTotal/1048576, int(heapLimit/1048576))
}
// Go WASM memory (dev builds via webtyp/devtools)
if wm, ok := metrics["wasmMem"].(map[string]any); ok {
heapAlloc, _ := wm["heapAlloc"].(float64)
totalAlloc, _ := wm["totalAlloc"].(float64)
mallocs, _ := wm["mallocs"].(float64)
numGC, _ := wm["numGC"].(float64)
fmt.Fprintf(&b, "WASM Mem: Heap %.1f KB | TotalAlloc %.1f KB (%.0f allocs) | GC %.0f\n",
heapAlloc/1024, totalAlloc/1024, mallocs, numGC)
}
// Delta since previous browser_get_performance call
if d, ok := metrics["delta"].(map[string]any); ok {
var parts []string
if da, ok := d["wasmAlloc"].(float64); ok {
dm, _ := d["wasmMallocs"].(float64)
dgc, _ := d["wasmGC"].(float64)
parts = append(parts, fmt.Sprintf("WASM %+.1f KB (%+.0f allocs, %+.0f GC)", da/1024, dm, dgc))
}
if dh, ok := d["jsHeap"].(float64); ok {
parts = append(parts, fmt.Sprintf("JS Heap %+.1f KB", dh/1024))
}
if dn, ok := d["domNodes"].(float64); ok {
parts = append(parts, fmt.Sprintf("DOM %+.0f nodes", dn))
}
if len(parts) > 0 {
fmt.Fprintf(&b, "Delta: %s\n", strings.Join(parts, " | "))
}
}
// Timing
domInteractive, hasInteractive := metrics["domInteractive"].(float64)
domLoaded, hasLoaded := metrics["domLoaded"].(float64)
fullLoad, hasFullLoad := metrics["fullLoad"].(float64)
if hasInteractive || hasLoaded || hasFullLoad {
b.WriteString("Timing: ")
sep := ""
if hasInteractive {
fmt.Fprintf(&b, "Interactive %dms", int(domInteractive))
sep = " | "
}
if hasLoaded {
fmt.Fprintf(&b, "%sDOM Loaded %dms", sep, int(domLoaded))
sep = " | "
}
if hasFullLoad {
fmt.Fprintf(&b, "%sFull Load %dms", sep, int(fullLoad))
}
b.WriteString("\n")
}
// Paint
fp, hasFP := metrics["fp"].(float64)
fcp, hasFCP := metrics["fcp"].(float64)
if hasFP || hasFCP {
b.WriteString("Paint: ")
sep := ""
if hasFP {
fmt.Fprintf(&b, "FP %dms", int(fp))
sep = " | "
}
if hasFCP {
fmt.Fprintf(&b, "%sFCP %dms", sep, int(fcp))
}
b.WriteString("\n")
}
// DOM
if nodes, ok := metrics["domNodes"].(float64); ok {
depth, _ := metrics["domDepth"].(float64)
fmt.Fprintf(&b, "DOM: %d nodes | max depth %d\n", int(nodes), int(depth))
}
// WASM files
if wasmFiles, ok := metrics["wasmFiles"].([]any); ok && len(wasmFiles) > 0 {
for _, wf := range wasmFiles {
if entry, ok := wf.(map[string]any); ok {
name, _ := entry["name"].(string)
size, _ := entry["size"].(float64)
duration, _ := entry["duration"].(float64)
fmt.Fprintf(&b, "WASM: %s %d KB (loaded in %dms)\n", name, int(size), int(duration))
}
}
}
// Resources total
if count, ok := metrics["resourceCount"].(float64); ok {
totalKB, _ := metrics["totalTransferKB"].(float64)
fmt.Fprintf(&b, "Resources: %d total | %d KB transferred\n", int(count), int(totalKB))
}
return b.String()
}
func (b *DevBrowser) GetPerformanceTools() []mcp.Tool {
return []mcp.Tool{
{
Name: "browser_get_performance",
Description: "Get page performance metrics (memory, timing, DOM stats, WASM resources) to diagnose excessive RAM usage, slow loads, or rendering issues. Returns a compact text report optimized for minimal token usage.",
InputSchema: mcp.SchemaOf(new(GetPerformanceArgs)),
Resource: "browser",
Action: 'r',
Execute: func(Ctx *context.Context, req mcp.Request) (*mcp.Result, error) {
if !b.IsOpenFlag {
return nil, ErrBrowserNotOpen
}
var args GetPerformanceArgs
if err := req.Bind(&args); err != nil {
return nil, err
}
var pageURL string
var metrics map[string]any
err := chromedp.Run(b.toolCtx(),
chromedp.Location(&pageURL),
chromedp.Evaluate(GetPerformanceJS, &metrics),
)
if err != nil {
return nil, fmt.Errorf("Failed to get performance metrics: %v", err)
}
b.recordPerfDelta(metrics)
report := FormatPerformanceReport(pageURL, metrics)
return mcp.Text(report), nil
},
},
}
}
type perfSnapshot struct {
hasJSHeap bool
jsHeapUsed float64
hasDOMNodes bool
domNodes float64
hasWasm bool
wasmAlloc float64
wasmMallocs float64
wasmGC float64
}
func snapshotFromMetrics(metrics map[string]any) perfSnapshot {
var snap perfSnapshot
if v, ok := metrics["heapUsed"].(float64); ok {
snap.hasJSHeap = true
snap.jsHeapUsed = v
}
if v, ok := metrics["domNodes"].(float64); ok {
snap.hasDOMNodes = true
snap.domNodes = v
}
if wm, ok := metrics["wasmMem"].(map[string]any); ok {
snap.hasWasm = true
snap.wasmAlloc, _ = wm["totalAlloc"].(float64)
snap.wasmMallocs, _ = wm["mallocs"].(float64)
snap.wasmGC, _ = wm["numGC"].(float64)
}
return snap
}
// recordPerfDelta compares metrics against the previous browser_get_performance
// call (if any), attaches metrics["delta"], and stores the new snapshot.
func (b *DevBrowser) recordPerfDelta(metrics map[string]any) {
cur := snapshotFromMetrics(metrics)
b.Mu.Lock()
prev := b.prevPerf
b.prevPerf = &cur
b.Mu.Unlock()
if prev == nil {
return
}
delta := map[string]any{}
if cur.hasWasm && prev.hasWasm && cur.wasmAlloc >= prev.wasmAlloc {
delta["wasmAlloc"] = cur.wasmAlloc - prev.wasmAlloc
delta["wasmMallocs"] = cur.wasmMallocs - prev.wasmMallocs
delta["wasmGC"] = cur.wasmGC - prev.wasmGC
}
if cur.hasJSHeap && prev.hasJSHeap {
delta["jsHeap"] = cur.jsHeapUsed - prev.jsHeapUsed
}
if cur.hasDOMNodes && prev.hasDOMNodes {
delta["domNodes"] = cur.domNodes - prev.domNodes
}
if len(delta) > 0 {
metrics["delta"] = delta
}
}