@mcp.tool()
def screenshot_screen(save_path: str = "", region: List[int] = None) -> Dict[str, Any]:
"""
Take a screenshot of the entire screen or a region.
Args:
save_path: Optional path to save the screenshot (PNG). If empty, returns base64.
region: Optional [x, y, width, height] to capture specific region.
Returns:
Screenshot info with base64 data or saved file path.
"""
if not SCREENSHOT_AVAILABLE:
return {"error": "Screenshot support not available. Install: pip install pywin32 pillow"}
try:
# Get screen dimensions
if region:
x, y, width, height = region
else:
x, y = 0, 0
width = ctypes.windll.user32.GetSystemMetrics(0)
height = ctypes.windll.user32.GetSystemMetrics(1)
# Capture screen
hwnd = win32gui.GetDesktopWindow()
hwnd_dc = win32gui.GetWindowDC(hwnd)
mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)
save_dc = mfc_dc.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(mfc_dc, width, height)
save_dc.SelectObject(bitmap)
save_dc.BitBlt((0, 0), (width, height), mfc_dc, (x, y), win32con.SRCCOPY)
# Convert to PIL Image
bmp_info = bitmap.GetInfo()
bmp_str = bitmap.GetBitmapBits(True)
img = Image.frombuffer(
'RGB',
(bmp_info['bmWidth'], bmp_info['bmHeight']),
bmp_str, 'raw', 'BGRX', 0, 1
)
# Cleanup
win32gui.DeleteObject(bitmap.GetHandle())
save_dc.DeleteDC()
mfc_dc.DeleteDC()
win32gui.ReleaseDC(hwnd, hwnd_dc)
# Save or return base64
if save_path:
img.save(save_path, 'PNG')
return {
"success": True,
"path": save_path,
"width": width,
"height": height
}
else:
buffer = io.BytesIO()
img.save(buffer, format='PNG')
img_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
return {
"success": True,
"width": width,
"height": height,
"image_base64": img_base64,
"format": "png"
}
except Exception as e:
return {"error": f"Screenshot failed: {str(e)}"}