Skip to content

Commit 3f12cad

Browse files
committed
Fix : Add image compression utility for base64 screenshots
1 parent 79f612c commit 3f12cad

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/lib/utils.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import sharp from "sharp";
2+
13
export function sanitizeUrlParam(param: string): string {
24
// Remove any characters that could be used for command injection
35
return param.replace(/[;&|`$(){}[\]<>]/g, "");
@@ -24,3 +26,24 @@ export interface HarEntry {
2426
serverIPAddress?: string;
2527
time?: number;
2628
}
29+
30+
/**
31+
* Compresses a base64 image intelligently to keep it under 1 MB if needed.
32+
*/
33+
export async function maybeCompressBase64(base64: string): Promise<string> {
34+
const buffer = Buffer.from(base64, "base64");
35+
36+
if (buffer.length <= 1048576) {
37+
return base64;
38+
}
39+
40+
const sizeRatio = 1048576 / buffer.length;
41+
const estimatedQuality = Math.floor(sizeRatio * 100);
42+
const quality = Math.min(95, Math.max(30, estimatedQuality));
43+
44+
const compressedBuffer = await sharp(buffer)
45+
.png({ quality })
46+
.toBuffer();
47+
48+
return compressedBuffer.toString("base64");
49+
}

src/tools/appautomate.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
44
import logger from "../logger";
55
import config from "../config";
66
import { trackMCP } from "../lib/instrumentation";
7+
import { maybeCompressBase64 } from "../lib/utils";
78

89
import {
910
getDevicesAndBrowsers,
@@ -122,13 +123,15 @@ async function takeAppScreenshot(args: {
122123
});
123124

124125
const screenshotBase64 = await driver.takeScreenshot();
126+
const compressed = await maybeCompressBase64(screenshotBase64);
125127

126128
return {
127129
content: [
128130
{
129131
type: "image",
130-
data: screenshotBase64,
132+
data: compressed,
131133
mimeType: "image/png",
134+
name: `screenshot-${selectedDevice.device}-${Date.now()}`,
132135
},
133136
],
134137
};

0 commit comments

Comments
 (0)