-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp-performance.go
More file actions
184 lines (162 loc) · 5.33 KB
/
mcp-performance.go
File metadata and controls
184 lines (162 loc) · 5.33 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
package devbrowser
import (
"fmt"
"strings"
"github.com/tinywasm/context"
"github.com/tinywasm/devbrowser/chromedp"
"github.com/tinywasm/mcp"
)
// GetPerformanceJS extracts page performance metrics optimized for LLM consumption.
const GetPerformanceJS = `
(() => {
const m = {};
// 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
b.WriteString(fmt.Sprintf("Performance: %s\n", pageURL))
// Memory
if heapUsed, ok := metrics["heapUsed"].(float64); ok {
heapTotal, _ := metrics["heapTotal"].(float64)
heapLimit, _ := metrics["heapLimit"].(float64)
b.WriteString(fmt.Sprintf("Memory: JS Heap %.1f/%.1f MB (limit %d MB)\n",
heapUsed/1048576, heapTotal/1048576, int(heapLimit/1048576)))
}
// 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 {
b.WriteString(fmt.Sprintf("Interactive %dms", int(domInteractive)))
sep = " | "
}
if hasLoaded {
b.WriteString(fmt.Sprintf("%sDOM Loaded %dms", sep, int(domLoaded)))
sep = " | "
}
if hasFullLoad {
b.WriteString(fmt.Sprintf("%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 {
b.WriteString(fmt.Sprintf("FP %dms", int(fp)))
sep = " | "
}
if hasFCP {
b.WriteString(fmt.Sprintf("%sFCP %dms", sep, int(fcp)))
}
b.WriteString("\n")
}
// DOM
if nodes, ok := metrics["domNodes"].(float64); ok {
depth, _ := metrics["domDepth"].(float64)
b.WriteString(fmt.Sprintf("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)
b.WriteString(fmt.Sprintf("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)
b.WriteString(fmt.Sprintf("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: EncodeSchema(new(GetPerformanceArgs)),
Resource: "browser",
Action: 'r',
Execute: func(Ctx *context.Context, req mcp.Request) (*mcp.Result, error) {
if !b.IsOpenFlag {
return nil, fmt.Errorf("Browser is not open")
}
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.Ctx,
chromedp.Location(&pageURL),
chromedp.Evaluate(GetPerformanceJS, &metrics),
)
if err != nil {
return nil, fmt.Errorf("Failed to get performance metrics: %v", err)
}
report := FormatPerformanceReport(pageURL, metrics)
return mcp.Text(report), nil
},
},
}
}