universal-screenshot-mcp 1.1.1 → 1.2.0

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.
package/README.md CHANGED
@@ -42,6 +42,14 @@ sudo pacman -S maim xdotool
42
42
  sudo apt install grim
43
43
  ```
44
44
 
45
+ After installing, you can verify your setup with:
46
+
47
+ ```bash
48
+ npx universal-screenshot-mcp --doctor
49
+ ```
50
+
51
+ This probes the host and prints copy-pasteable install commands for any missing tools, tailored to your detected distro.
52
+
45
53
  ## Quick Start
46
54
 
47
55
  ### Install from npm
@@ -93,6 +101,24 @@ Or if installed from source:
93
101
  }
94
102
  ```
95
103
 
104
+ For **Claude Code**, register the server with the `claude mcp add` command:
105
+
106
+ ```bash
107
+ # Project scope (current directory only)
108
+ claude mcp add screenshot-server -- npx -y universal-screenshot-mcp
109
+
110
+ # User scope (available across all projects)
111
+ claude mcp add --scope user screenshot-server -- npx -y universal-screenshot-mcp
112
+ ```
113
+
114
+ Or if installed from source:
115
+
116
+ ```bash
117
+ claude mcp add screenshot-server -- node /absolute/path/to/mcp-screenshot-server/build/index.js
118
+ ```
119
+
120
+ Verify the server registered with `claude mcp list`, or check live status from inside a session with `/mcp`.
121
+
96
122
  For **Cursor** or other MCP clients, consult their documentation for the equivalent configuration.
97
123
 
98
124
  ## Tools
@@ -2,6 +2,7 @@
2
2
  // Configuration Constants
3
3
  // ============================================================================
4
4
  import { join } from 'path';
5
+ import { homedir, tmpdir } from 'os';
5
6
  /**
6
7
  * Maximum number of concurrent Puppeteer browser instances.
7
8
  * Each instance spawns a Chromium process consuming 100-500MB of memory.
@@ -17,9 +18,9 @@ export const ALLOW_LOCAL = process.env.ALLOW_LOCAL === 'true';
17
18
  /**
18
19
  * Resolved allowed output directories for screenshots.
19
20
  * Only these directories (and their subdirectories) are permitted for file output.
20
- * Uses process.env.HOME at module load time (pure computation, no I/O side effects).
21
+ * os.homedir() works cross-platform (USERPROFILE on Windows, HOME on Unix).
21
22
  */
22
- export const homeDir = process.env.HOME || '/tmp';
23
+ export const homeDir = process.env.HOME || homedir();
23
24
  /**
24
25
  * Resolved default output directory for screenshots.
25
26
  * Priority: 1) SCREENSHOT_OUTPUT_DIR env var 2) ~/Documents/screenshots 3) ~/Desktop/Screenshots
@@ -30,7 +31,7 @@ export const configuredOutDir = process.env.SCREENSHOT_OUTPUT_DIR
30
31
  export const ALLOWED_OUTPUT_DIRS = [
31
32
  join(homeDir, 'Desktop', 'Screenshots'), // ~/Desktop/Screenshots (original default)
32
33
  configuredOutDir, // Configured default output directory
33
- '/tmp', // System temp directory
34
+ tmpdir(), // System temp directory (cross-platform)
34
35
  join(homeDir, 'Downloads'), // ~/Downloads
35
36
  join(homeDir, 'Documents'), // ~/Documents
36
37
  ];
package/build/index.js CHANGED
@@ -1,11 +1,33 @@
1
1
  #!/usr/bin/env node
2
2
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
3
  import { createServer } from './server.js';
4
- const server = createServer();
5
- const transport = new StdioServerTransport();
6
- server.connect(transport)
7
- .then(() => console.error('Screenshot MCP server running'))
8
- .catch((error) => {
9
- console.error('Failed to connect server:', error);
4
+ import { runDoctor, formatDoctorReport } from './utils/doctor.js';
5
+ import { commandExists } from './utils/screenshot-provider.js';
6
+ const LINUX_BACKENDS = ['maim', 'scrot', 'gnome-screenshot', 'spectacle', 'grim', 'import'];
7
+ async function main() {
8
+ if (process.argv.slice(2).includes('--doctor')) {
9
+ const report = await runDoctor();
10
+ console.log(formatDoctorReport(report));
11
+ process.exit(report.hasFailures ? 1 : 0);
12
+ }
13
+ const server = createServer();
14
+ const transport = new StdioServerTransport();
15
+ await server.connect(transport);
16
+ console.error('Screenshot MCP server running');
17
+ if (process.platform === 'linux') {
18
+ void warnIfMissingLinuxBackend();
19
+ }
20
+ }
21
+ async function warnIfMissingLinuxBackend() {
22
+ for (const cmd of LINUX_BACKENDS) {
23
+ if (await commandExists(cmd))
24
+ return;
25
+ }
26
+ console.error('Warning: no screenshot tool detected on this Linux system. ' +
27
+ 'take_system_screenshot will fail until one is installed. ' +
28
+ 'Run `npx universal-screenshot-mcp --doctor` for distro-specific install commands.');
29
+ }
30
+ main().catch((error) => {
31
+ console.error('Failed to start server:', error);
10
32
  process.exit(1);
11
33
  });
@@ -8,7 +8,7 @@ import { ok, err, timestamp, ensureDir } from '../utils/helpers.js';
8
8
  // Semaphore protects expensive Puppeteer operations
9
9
  export function registerTakeScreenshot(server) {
10
10
  server.registerTool('take_screenshot', {
11
- description: 'Capture web page or element via headless browser. Saves to ~/Desktop/Screenshots by default.',
11
+ description: 'Capture web page or element via headless browser. Saves to ~/Documents/screenshots by default (configurable via SCREENSHOT_OUTPUT_DIR env var).',
12
12
  inputSchema: {
13
13
  url: z.string().describe('URL to capture'),
14
14
  width: z.number().min(1).max(3840).optional().describe('Viewport width'),
@@ -8,7 +8,7 @@ import { getScreenshotProvider } from '../utils/screenshot-provider.js';
8
8
  // No semaphore — system screenshot tools are lightweight (< 100ms, < 10MB)
9
9
  export function registerTakeSystemScreenshot(server) {
10
10
  server.registerTool('take_system_screenshot', {
11
- description: 'Capture desktop, window, or region screenshot. Cross-platform: macOS (screencapture), Linux (maim/scrot/gnome-screenshot/etc.), Windows (PowerShell+.NET). Saves to ~/Desktop/Screenshots by default. For window mode, provide windowName (app name like "Safari") or windowId.',
11
+ description: 'Capture desktop, window, or region screenshot. Cross-platform: macOS (screencapture), Linux (maim/scrot/gnome-screenshot/etc.), Windows (PowerShell+.NET). Saves to ~/Documents/screenshots by default (configurable via SCREENSHOT_OUTPUT_DIR env var). For window mode, provide windowName (app name like "Safari") or windowId.',
12
12
  inputSchema: {
13
13
  mode: z
14
14
  .enum(['fullscreen', 'window', 'region'])
@@ -27,7 +27,7 @@ export function registerTakeSystemScreenshot(server) {
27
27
  })
28
28
  .optional()
29
29
  .describe('Region {x,y,width,height}'),
30
- display: z.number().min(1).optional().describe('Display number'),
30
+ display: z.number().int().min(1).optional().describe('Display number'),
31
31
  includeCursor: z.boolean().optional().describe('Include cursor'),
32
32
  format: z.enum(['png', 'jpg']).optional().describe('Image format (png or jpg)'),
33
33
  delay: z.number().min(0).max(10).optional().describe('Delay seconds'),
@@ -0,0 +1,144 @@
1
+ // ============================================================================
2
+ // Diagnostic runner for `universal-screenshot-mcp --doctor`
3
+ //
4
+ // Probes the host system and reports whether the screenshot tools needed by
5
+ // take_system_screenshot are present, with copy-pasteable install commands
6
+ // for any that are missing.
7
+ // ============================================================================
8
+ import { commandExists } from './screenshot-provider.js';
9
+ import { detectLinuxDistro, getInstallCommand, RECOMMENDED_X11_PACKAGES } from './linux-deps.js';
10
+ const LINUX_BACKENDS = [
11
+ 'maim', 'scrot', 'gnome-screenshot', 'spectacle', 'grim', 'import',
12
+ ];
13
+ export async function runDoctor(platform = process.platform) {
14
+ const checks = [];
15
+ if (platform === 'darwin') {
16
+ checks.push(await checkMacOS());
17
+ }
18
+ else if (platform === 'linux') {
19
+ checks.push(...(await checkLinux()));
20
+ }
21
+ else if (platform === 'win32') {
22
+ checks.push(await checkWindows());
23
+ }
24
+ else {
25
+ checks.push({
26
+ name: 'Platform support',
27
+ status: 'fail',
28
+ detail: `Unsupported platform: ${platform}. Supported: darwin, linux, win32.`,
29
+ });
30
+ }
31
+ return {
32
+ platform,
33
+ nodeVersion: process.version,
34
+ checks,
35
+ hasFailures: checks.some(c => c.status === 'fail'),
36
+ hasWarnings: checks.some(c => c.status === 'warn'),
37
+ };
38
+ }
39
+ async function checkMacOS() {
40
+ if (await commandExists('screencapture')) {
41
+ return {
42
+ name: 'macOS screencapture',
43
+ status: 'ok',
44
+ detail: 'screencapture is available (built-in on macOS).',
45
+ };
46
+ }
47
+ return {
48
+ name: 'macOS screencapture',
49
+ status: 'fail',
50
+ detail: 'screencapture is missing — this is unexpected on macOS.',
51
+ };
52
+ }
53
+ async function checkWindows() {
54
+ if (await commandExists('powershell')) {
55
+ return {
56
+ name: 'Windows PowerShell',
57
+ status: 'ok',
58
+ detail: 'powershell is available (built-in on Windows).',
59
+ };
60
+ }
61
+ return {
62
+ name: 'Windows PowerShell',
63
+ status: 'fail',
64
+ detail: 'powershell is missing — this is unexpected on Windows.',
65
+ };
66
+ }
67
+ async function checkLinux() {
68
+ const distro = await detectLinuxDistro();
69
+ const found = [];
70
+ for (const tool of LINUX_BACKENDS) {
71
+ if (await commandExists(tool))
72
+ found.push(tool);
73
+ }
74
+ const checks = [];
75
+ checks.push({
76
+ name: 'Linux distro',
77
+ status: 'ok',
78
+ detail: distro.id === 'unknown'
79
+ ? 'Could not identify distro from /etc/os-release; install commands will be generic.'
80
+ : `Detected ${distro.id} (package manager: ${distro.packageManager}).`,
81
+ });
82
+ if (found.length === 0) {
83
+ checks.push({
84
+ name: 'Screenshot backend',
85
+ status: 'fail',
86
+ detail: 'No screenshot tool found. take_system_screenshot will not work.',
87
+ hint: getInstallCommand(distro.packageManager, [...RECOMMENDED_X11_PACKAGES]),
88
+ });
89
+ }
90
+ else {
91
+ checks.push({
92
+ name: 'Screenshot backend',
93
+ status: 'ok',
94
+ detail: `Found: ${found.join(', ')}. Will use ${found[0]} (highest priority).`,
95
+ });
96
+ }
97
+ if (await commandExists('xdotool')) {
98
+ checks.push({
99
+ name: 'xdotool (window-by-name)',
100
+ status: 'ok',
101
+ detail: 'xdotool is installed — windowName capture supported.',
102
+ });
103
+ }
104
+ else {
105
+ checks.push({
106
+ name: 'xdotool (window-by-name)',
107
+ status: 'warn',
108
+ detail: 'xdotool is not installed — windowName capture will fail; windowId still works.',
109
+ hint: getInstallCommand(distro.packageManager, ['xdotool']),
110
+ });
111
+ }
112
+ return checks;
113
+ }
114
+ const STATUS_GLYPH = {
115
+ ok: '[OK] ',
116
+ warn: '[WARN]',
117
+ fail: '[FAIL]',
118
+ };
119
+ export function formatDoctorReport(report) {
120
+ const lines = [];
121
+ lines.push('universal-screenshot-mcp doctor');
122
+ lines.push('');
123
+ lines.push(`Platform: ${report.platform}`);
124
+ lines.push(`Node: ${report.nodeVersion}`);
125
+ lines.push('');
126
+ for (const check of report.checks) {
127
+ lines.push(`${STATUS_GLYPH[check.status]} ${check.name}`);
128
+ lines.push(` ${check.detail}`);
129
+ if (check.hint) {
130
+ lines.push(` → ${check.hint}`);
131
+ }
132
+ lines.push('');
133
+ }
134
+ if (report.hasFailures) {
135
+ lines.push('Result: FAILED — see hints above.');
136
+ }
137
+ else if (report.hasWarnings) {
138
+ lines.push('Result: OK with warnings — some optional features need extra setup.');
139
+ }
140
+ else {
141
+ lines.push('Result: OK — all checks passed.');
142
+ }
143
+ return lines.join('\n');
144
+ }
@@ -0,0 +1,100 @@
1
+ // ============================================================================
2
+ // Linux distro detection + package install command formatting
3
+ //
4
+ // Used by linux-provider runtime errors, the --doctor subcommand, and the
5
+ // startup stderr warning so all three surfaces produce the same actionable
6
+ // install instructions.
7
+ // ============================================================================
8
+ import { readFile } from 'node:fs/promises';
9
+ const ID_TO_PACKAGE_MANAGER = {
10
+ // Debian family
11
+ debian: 'apt',
12
+ ubuntu: 'apt',
13
+ pop: 'apt',
14
+ mint: 'apt',
15
+ linuxmint: 'apt',
16
+ kali: 'apt',
17
+ raspbian: 'apt',
18
+ elementary: 'apt',
19
+ // Red Hat family
20
+ fedora: 'dnf',
21
+ rhel: 'dnf',
22
+ centos: 'dnf',
23
+ rocky: 'dnf',
24
+ almalinux: 'dnf',
25
+ ol: 'dnf',
26
+ // Arch family
27
+ arch: 'pacman',
28
+ manjaro: 'pacman',
29
+ endeavouros: 'pacman',
30
+ artix: 'pacman',
31
+ // SUSE family
32
+ opensuse: 'zypper',
33
+ 'opensuse-leap': 'zypper',
34
+ 'opensuse-tumbleweed': 'zypper',
35
+ sles: 'zypper',
36
+ suse: 'zypper',
37
+ // Alpine
38
+ alpine: 'apk',
39
+ };
40
+ /**
41
+ * Parse /etc/os-release content into a DistroInfo. Pure function — no I/O.
42
+ */
43
+ export function parseOsRelease(content) {
44
+ const fields = {};
45
+ for (const line of content.split('\n')) {
46
+ const match = line.match(/^([A-Z_]+)=(.*)$/);
47
+ if (!match)
48
+ continue;
49
+ let value = match[2].trim();
50
+ if ((value.startsWith('"') && value.endsWith('"')) ||
51
+ (value.startsWith("'") && value.endsWith("'"))) {
52
+ value = value.slice(1, -1);
53
+ }
54
+ fields[match[1]] = value;
55
+ }
56
+ const id = (fields.ID ?? 'unknown').toLowerCase();
57
+ const idLike = (fields.ID_LIKE ?? '').toLowerCase().split(/\s+/).filter(Boolean);
58
+ let packageManager = 'unknown';
59
+ for (const candidate of [id, ...idLike]) {
60
+ if (ID_TO_PACKAGE_MANAGER[candidate]) {
61
+ packageManager = ID_TO_PACKAGE_MANAGER[candidate];
62
+ break;
63
+ }
64
+ }
65
+ return { id, idLike, packageManager };
66
+ }
67
+ /**
68
+ * Read /etc/os-release and return DistroInfo. Returns an "unknown" record
69
+ * if the file is unreadable (rare on real Linux, possible in minimal containers).
70
+ */
71
+ export async function detectLinuxDistro(path = '/etc/os-release') {
72
+ try {
73
+ const content = await readFile(path, 'utf8');
74
+ return parseOsRelease(content);
75
+ }
76
+ catch {
77
+ return { id: 'unknown', idLike: [], packageManager: 'unknown' };
78
+ }
79
+ }
80
+ /**
81
+ * Build a copy-pasteable install command for the given package manager.
82
+ * For unknown distros, returns a generic instruction listing the package names.
83
+ */
84
+ export function getInstallCommand(packageManager, packages) {
85
+ const pkgs = packages.join(' ');
86
+ switch (packageManager) {
87
+ case 'apt': return `sudo apt install ${pkgs}`;
88
+ case 'dnf': return `sudo dnf install ${pkgs}`;
89
+ case 'pacman': return `sudo pacman -S ${pkgs}`;
90
+ case 'zypper': return `sudo zypper install ${pkgs}`;
91
+ case 'apk': return `sudo apk add ${pkgs}`;
92
+ case 'unknown':
93
+ default: return `install with your distro's package manager: ${pkgs}`;
94
+ }
95
+ }
96
+ /**
97
+ * Default recommendation for full take_system_screenshot support on X11 Linux.
98
+ * Wayland users want `grim` instead — covered separately in error messages.
99
+ */
100
+ export const RECOMMENDED_X11_PACKAGES = ['maim', 'xdotool'];
@@ -2,6 +2,7 @@
2
2
  // Linux screenshot provider — fallback chain of native tools
3
3
  // ============================================================================
4
4
  import { execFileAsync, commandExists, sleep } from './screenshot-provider.js';
5
+ import { detectLinuxDistro, getInstallCommand } from './linux-deps.js';
5
6
  /**
6
7
  * Linux screenshot provider with automatic tool detection.
7
8
  * Probes for available tools in priority order and uses the first one found.
@@ -16,6 +17,7 @@ export class LinuxProvider {
16
17
  }
17
18
  async captureFullscreen(opts) {
18
19
  const backend = await this.getBackend();
20
+ this.assertSupportedOptions(opts);
19
21
  if (opts.delay && opts.delay > 0)
20
22
  await sleep(opts.delay);
21
23
  switch (backend) {
@@ -41,6 +43,13 @@ export class LinuxProvider {
41
43
  }
42
44
  async captureWindow(opts) {
43
45
  const backend = await this.getBackend();
46
+ this.assertSupportedOptions(opts);
47
+ // grim cannot capture per-window on Wayland — fail fast with the
48
+ // backend-specific error before attempting xdotool resolution, which
49
+ // would otherwise mask the real reason with a misleading message.
50
+ if (backend === 'grim') {
51
+ throw new Error('Window capture is not supported on Wayland with grim. Use fullscreen or region mode.');
52
+ }
44
53
  if (opts.delay && opts.delay > 0)
45
54
  await sleep(opts.delay);
46
55
  // Try to resolve window ID from name using xdotool (X11 only)
@@ -78,8 +87,6 @@ export class LinuxProvider {
78
87
  throw new Error('maim requires a window ID or xdotool for window-by-name capture');
79
88
  }
80
89
  break;
81
- case 'grim':
82
- throw new Error('Window capture is not supported on Wayland with grim. Use fullscreen or region mode.');
83
90
  case 'import':
84
91
  if (xWindowId) {
85
92
  await execFileAsync('import', ['-window', xWindowId, opts.outputPath]);
@@ -92,6 +99,7 @@ export class LinuxProvider {
92
99
  }
93
100
  async captureRegion(opts) {
94
101
  const backend = await this.getBackend();
102
+ this.assertSupportedOptions(opts);
95
103
  if (opts.delay && opts.delay > 0)
96
104
  await sleep(opts.delay);
97
105
  const geometry = `${opts.width}x${opts.height}+${opts.x}+${opts.y}`;
@@ -121,6 +129,13 @@ export class LinuxProvider {
121
129
  }
122
130
  }
123
131
  // ── Private helpers ────────────────────────────────────────────────────
132
+ assertSupportedOptions(opts) {
133
+ if (opts.includeCursor) {
134
+ throw new Error('Linux provider does not support includeCursor — none of the supported backends ' +
135
+ '(maim, scrot, gnome-screenshot, spectacle, grim, import) expose a cursor flag in our argv. ' +
136
+ 'Use macOS or Windows for cursor capture.');
137
+ }
138
+ }
124
139
  async detectBackend() {
125
140
  if (this._detected)
126
141
  return;
@@ -139,14 +154,28 @@ export class LinuxProvider {
139
154
  async getBackend() {
140
155
  await this.detectBackend();
141
156
  if (!this._backend) {
142
- throw new Error('No screenshot tool found. Install one of: maim, scrot, gnome-screenshot, spectacle, grim, or ImageMagick (import).');
157
+ const distro = await detectLinuxDistro();
158
+ const installCmd = getInstallCommand(distro.packageManager, ['maim', 'xdotool']);
159
+ throw new Error('No screenshot tool found on this Linux system. ' +
160
+ 'take_system_screenshot needs one of: maim, scrot, gnome-screenshot, spectacle, grim (Wayland), or ImageMagick (import). ' +
161
+ `For a typical X11 install: ${installCmd}. ` +
162
+ 'See README for distro-specific instructions.');
143
163
  }
144
164
  return this._backend;
145
165
  }
146
166
  /**
147
- * Find an X11 window ID by application name using xdotool.
167
+ * Find an X11 window ID by application name using xdotool. Throws a helpful
168
+ * install hint when xdotool is missing — without it, no Linux backend can
169
+ * honor a windowName request.
148
170
  */
149
171
  async findXWindowId(name) {
172
+ if (!(await commandExists('xdotool'))) {
173
+ const distro = await detectLinuxDistro();
174
+ const installCmd = getInstallCommand(distro.packageManager, ['xdotool']);
175
+ throw new Error('Window-by-name capture requires xdotool, which is not installed. ' +
176
+ `Install it with: ${installCmd}. ` +
177
+ 'Alternatively, pass an explicit windowId.');
178
+ }
150
179
  try {
151
180
  const { stdout } = await execFileAsync('xdotool', ['search', '--name', name]);
152
181
  const ids = stdout.trim().split('\n').filter(Boolean);
@@ -2,12 +2,29 @@
2
2
  // Windows screenshot provider — PowerShell + .NET System.Drawing
3
3
  // ============================================================================
4
4
  import { execFileAsync, commandExists, sleep } from './screenshot-provider.js';
5
+ const POWERSHELL_FALLBACK_PATHS = [
6
+ 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',
7
+ 'C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe',
8
+ ];
9
+ async function resolvePowerShell() {
10
+ if (await commandExists('powershell'))
11
+ return 'powershell';
12
+ for (const p of POWERSHELL_FALLBACK_PATHS) {
13
+ try {
14
+ await execFileAsync(p, ['-Command', 'echo ok']);
15
+ return p;
16
+ }
17
+ catch { /* try next */ }
18
+ }
19
+ return null;
20
+ }
5
21
  /**
6
22
  * Windows screenshot provider using PowerShell with .NET System.Drawing.
7
23
  * Zero external dependencies — PowerShell and .NET are built into all modern Windows.
8
24
  */
9
25
  export class WindowsProvider {
10
26
  platform = 'Windows';
27
+ powershellPath = null;
11
28
  static DPI_AWARE_SNIPPET = `
12
29
  Add-Type -TypeDefinition @"
13
30
  using System;
@@ -15,24 +32,35 @@ using System.Runtime.InteropServices;
15
32
  public class DpiAwareness {
16
33
  [DllImport("user32.dll")]
17
34
  public static extern bool SetProcessDPIAware();
35
+ [DllImport("user32.dll", SetLastError = true)]
36
+ public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
18
37
  }
19
38
  "@
20
- [DpiAwareness]::SetProcessDPIAware() | Out-Null`.trim();
39
+ try { [DpiAwareness]::SetProcessDpiAwarenessContext([IntPtr]::new(-4)) | Out-Null } catch { [DpiAwareness]::SetProcessDPIAware() | Out-Null }`.trim();
21
40
  async isAvailable() {
22
- return commandExists('powershell');
41
+ this.powershellPath = await resolvePowerShell();
42
+ return this.powershellPath !== null;
23
43
  }
24
44
  async captureFullscreen(opts) {
25
45
  if (opts.delay && opts.delay > 0)
26
46
  await sleep(opts.delay);
27
47
  const format = this.dotNetFormat(opts.format);
28
- const displayIndex = (opts.display ?? 1) - 1; // Convert 1-based to 0-based
48
+ // No display specified → capture entire virtual screen (all monitors combined)
49
+ // display specified → capture that specific monitor
50
+ const captureAllDisplays = opts.display === undefined || opts.display === null;
51
+ const displayIndex = captureAllDisplays ? 0 : (opts.display - 1);
52
+ const boundsScript = captureAllDisplays
53
+ ? `
54
+ $bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen`
55
+ : `
56
+ $screens = [System.Windows.Forms.Screen]::AllScreens
57
+ $screen = if (${displayIndex} -lt $screens.Length) { $screens[${displayIndex}] } else { [System.Windows.Forms.Screen]::PrimaryScreen }
58
+ $bounds = $screen.Bounds`;
29
59
  const script = `
30
60
  ${WindowsProvider.DPI_AWARE_SNIPPET}
31
61
  Add-Type -AssemblyName System.Windows.Forms
32
62
  Add-Type -AssemblyName System.Drawing
33
- $screens = [System.Windows.Forms.Screen]::AllScreens
34
- $screen = if (${displayIndex} -lt $screens.Length) { $screens[${displayIndex}] } else { [System.Windows.Forms.Screen]::PrimaryScreen }
35
- $bounds = $screen.Bounds
63
+ ${boundsScript}
36
64
  $bitmap = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height)
37
65
  $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
38
66
  ${opts.includeCursor ? '$cursorPos = [System.Windows.Forms.Cursor]::Position\n' : ''}
@@ -111,11 +139,13 @@ $bitmap.Dispose()
111
139
  }
112
140
  // ── Private helpers ────────────────────────────────────────────────────
113
141
  async runPowerShell(script) {
114
- await execFileAsync('powershell', [
142
+ const cmd = this.powershellPath ?? 'powershell';
143
+ const encoded = Buffer.from(script, 'utf16le').toString('base64');
144
+ await execFileAsync(cmd, [
115
145
  '-ExecutionPolicy', 'Bypass',
116
146
  '-NoProfile',
117
147
  '-NonInteractive',
118
- '-Command', script,
148
+ '-EncodedCommand', encoded,
119
149
  ]);
120
150
  }
121
151
  dotNetFormat(format) {
@@ -1,5 +1,5 @@
1
1
  import { promises as fsPromises } from 'fs';
2
- import { dirname, join, resolve, relative } from 'path';
2
+ import { dirname, join, resolve, relative, isAbsolute } from 'path';
3
3
  const defaultFileSystem = {
4
4
  realpath: (path) => fsPromises.realpath(path),
5
5
  };
@@ -59,14 +59,15 @@ export async function validateOutputPath(customPath, defaultName, config, fileSy
59
59
  realAllowedDir = resolve(allowedDir);
60
60
  }
61
61
  const relativePath = relative(realAllowedDir, realPath);
62
- // If relative path doesn't start with '..' and isn't absolute, it's within the allowed dir
63
- if (!relativePath.startsWith('..') && !relativePath.startsWith('/')) {
62
+ // isAbsolute() catches the cross-drive case on Windows, where relative() returns
63
+ // an absolute path like 'D:\\foo' that doesn't start with '/' or '..'.
64
+ if (!relativePath.startsWith('..') && !isAbsolute(relativePath)) {
64
65
  return { valid: true, path: realPath };
65
66
  }
66
67
  }
67
68
  // Path is outside all allowed directories (after symlink resolution)
68
69
  return {
69
70
  valid: false,
70
- error: 'Output path must be within allowed directories (~/Desktop/Screenshots, ~/Downloads, ~/Documents, or /tmp). Symlinks to other locations are not permitted.',
71
+ error: 'Output path must be within allowed directories (~/Desktop/Screenshots, ~/Documents, ~/Downloads, or the system temp directory). Symlinks to other locations are not permitted.',
71
72
  };
72
73
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "universal-screenshot-mcp",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "description": "An MCP server for capturing web page screenshots via Puppeteer and cross-platform system screenshots via native OS tools",
5
5
  "author": "Seth Bang",
6
6
  "license": "Apache-2.0",
@@ -21,7 +21,7 @@
21
21
  ],
22
22
  "type": "module",
23
23
  "engines": {
24
- "node": ">=18.0.0"
24
+ "node": "^20.19.0 || ^22.13.0 || >=24"
25
25
  },
26
26
  "repository": {
27
27
  "type": "git",
@@ -58,11 +58,12 @@
58
58
  },
59
59
  "devDependencies": {
60
60
  "@types/node": "^22.0.0",
61
- "@typescript-eslint/eslint-plugin": "^8.54.0",
62
- "@typescript-eslint/parser": "^8.54.0",
61
+ "@typescript-eslint/eslint-plugin": "^8.59.0",
62
+ "@typescript-eslint/parser": "^8.59.0",
63
63
  "@vitest/coverage-v8": "^4.0.18",
64
- "eslint": "^9.39.2",
65
- "typescript": "^5.7.0",
64
+ "eslint": "^10.2.1",
65
+ "jiti": "^2.4.0",
66
+ "typescript": "^6.0.0",
66
67
  "vitest": "^4.0.18"
67
68
  }
68
69
  }