universal-screenshot-mcp 1.0.0 → 1.1.1

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
@@ -112,7 +112,7 @@ Captures a web page (or a specific element) via a headless Puppeteer browser.
112
112
  | `selector` | string | — | CSS selector to capture a specific element |
113
113
  | `waitForSelector` | string | — | Wait for this selector before capturing |
114
114
  | `waitForTimeout` | number | — | Delay in milliseconds (0–30000) |
115
- | `outputPath` | string | — | Output file path (default: `~/Desktop/Screenshots`) |
115
+ | `outputPath` | string | — | Output file path (default: `~/Documents/screenshots`) |
116
116
 
117
117
  **Example prompt:**
118
118
  > Take a screenshot of https://example.com at 1920x1080
@@ -131,7 +131,7 @@ Captures the desktop, a specific application window, or a screen region using na
131
131
  | `includeCursor` | boolean | — | Include the mouse cursor in the capture |
132
132
  | `format` | enum | — | `png` (default) or `jpg` |
133
133
  | `delay` | number | — | Capture delay in seconds (0–10) |
134
- | `outputPath` | string | — | Output file path (default: `~/Desktop/Screenshots`) |
134
+ | `outputPath` | string | — | Output file path (default: `~/Documents/screenshots`) |
135
135
 
136
136
  #### Cross-Platform Feature Support
137
137
 
@@ -148,13 +148,23 @@ Captures the desktop, a specific application window, or a screen region using na
148
148
  **Example prompt:**
149
149
  > Take a system screenshot of the Safari window
150
150
 
151
- ## Output Directories
151
+ ## Configuration
152
152
 
153
- Screenshots are saved to `~/Desktop/Screenshots` by default. Custom output paths must resolve to one of these allowed directories:
153
+ ### Environment Variables
154
+
155
+ | Variable | Default | Description |
156
+ |----------|---------|-------------|
157
+ | `SCREENSHOT_OUTPUT_DIR` | `Documents/screenshots` | Default output directory relative to `~` |
158
+ | `ALLOW_LOCAL` | `false` | Set to `true` to allow screenshotting `localhost`/`127.x.x.x`/`[::1]` (useful for local dev servers) |
159
+
160
+ ### Output Directories
161
+
162
+ Screenshots are saved to `~/Documents/screenshots` by default (configurable via `SCREENSHOT_OUTPUT_DIR`). Custom output paths must resolve to one of these allowed directories:
154
163
 
155
164
  | Directory | Description |
156
165
  |------------------------|--------------------------|
157
- | `~/Desktop/Screenshots`| Default output location |
166
+ | `~/Documents/screenshots` | Default output location (configurable) |
167
+ | `~/Desktop/Screenshots`| Original default location |
158
168
  | `~/Downloads` | User downloads folder |
159
169
  | `~/Documents` | User documents folder |
160
170
  | `/tmp` | System temp directory |
@@ -176,15 +186,19 @@ For full details, see [`docs/security.md`](docs/security.md).
176
186
 
177
187
  ### Scripts
178
188
 
179
- | Command | Description |
180
- |----------------------|-----------------------------------|
181
- | `npm run build` | Compile TypeScript to `build/` |
182
- | `npm run watch` | Recompile on file changes |
183
- | `npm test` | Run tests with Vitest |
184
- | `npm run test:watch` | Run tests in watch mode |
185
- | `npm run test:coverage` | Run tests with coverage report |
186
- | `npm run lint` | Lint source with ESLint |
187
- | `npm run inspector` | Launch MCP Inspector for debugging|
189
+ | Command | Description |
190
+ |----------------------|----------------------------------------|
191
+ | `npm run build` | Compile TypeScript to `build/` |
192
+ | `npm run watch` | Recompile on file changes |
193
+ | `npm test` | Unit tests (fast, fully mocked) |
194
+ | `npm run test:integration` | Integration tests (real DNS/filesystem) |
195
+ | `npm run test:e2e` | E2E tests (real Puppeteer/native tools)|
196
+ | `npm run test:all` | All test tiers together |
197
+ | `npm run test:linux` | Linux e2e via Docker (requires Docker) |
198
+ | `npm run test:watch` | Run tests in watch mode |
199
+ | `npm run test:coverage` | Run tests with coverage report |
200
+ | `npm run lint` | Lint source with ESLint |
201
+ | `npm run inspector` | Launch MCP Inspector for debugging |
188
202
 
189
203
  ### Project Structure
190
204
 
@@ -215,10 +229,16 @@ src/
215
229
 
216
230
  ### Testing
217
231
 
218
- Tests use [Vitest](https://vitest.dev/) with full dependency injection — no real network calls, filesystem access, or subprocess execution in tests.
232
+ Tests use [Vitest](https://vitest.dev/) in three tiers:
233
+
234
+ - **Unit** (`npm test`) — Full dependency injection, no real I/O. Fast feedback loop.
235
+ - **Integration** (`npm run test:integration`) — Real DNS resolution, real filesystem with temp directories, real Puppeteer against a local HTTP server.
236
+ - **E2E** (`npm run test:e2e`) — Real native screenshot tools. macOS tests run natively; Linux tests run in Docker via `npm run test:linux`.
219
237
 
220
238
  ```bash
221
- npm test
239
+ npm test # Unit tests (~300ms)
240
+ npm run test:linux # Linux provider tests in Docker
241
+ npm run test:all # Everything
222
242
  ```
223
243
 
224
244
  ### Debugging with MCP Inspector
@@ -8,14 +8,28 @@ import { join } from 'path';
8
8
  * SEC-005: Prevents resource exhaustion / DoS attacks.
9
9
  */
10
10
  export const MAX_CONCURRENT_SCREENSHOTS = 3;
11
+ /**
12
+ * When true, allows loopback addresses (127.x.x.x, ::1, localhost) in URL validation.
13
+ * All other private/reserved ranges remain blocked regardless of this setting.
14
+ * Useful for screenshotting local dev servers. Off by default for SSRF safety.
15
+ */
16
+ export const ALLOW_LOCAL = process.env.ALLOW_LOCAL === 'true';
11
17
  /**
12
18
  * Resolved allowed output directories for screenshots.
13
19
  * Only these directories (and their subdirectories) are permitted for file output.
14
20
  * Uses process.env.HOME at module load time (pure computation, no I/O side effects).
15
21
  */
16
22
  export const homeDir = process.env.HOME || '/tmp';
23
+ /**
24
+ * Resolved default output directory for screenshots.
25
+ * Priority: 1) SCREENSHOT_OUTPUT_DIR env var 2) ~/Documents/screenshots 3) ~/Desktop/Screenshots
26
+ */
27
+ export const configuredOutDir = process.env.SCREENSHOT_OUTPUT_DIR
28
+ ? join(homeDir, process.env.SCREENSHOT_OUTPUT_DIR.replace(/^~\/?/, ''))
29
+ : join(homeDir, 'Documents', 'screenshots');
17
30
  export const ALLOWED_OUTPUT_DIRS = [
18
- join(homeDir, 'Desktop', 'Screenshots'), // ~/Desktop/Screenshots (default output)
31
+ join(homeDir, 'Desktop', 'Screenshots'), // ~/Desktop/Screenshots (original default)
32
+ configuredOutDir, // Configured default output directory
19
33
  '/tmp', // System temp directory
20
34
  join(homeDir, 'Downloads'), // ~/Downloads
21
35
  join(homeDir, 'Documents'), // ~/Documents
@@ -1,9 +1,13 @@
1
1
  import { Semaphore } from '../utils/semaphore.js';
2
- import { MAX_CONCURRENT_SCREENSHOTS, homeDir } from './index.js';
2
+ import { MAX_CONCURRENT_SCREENSHOTS, homeDir, configuredOutDir } from './index.js';
3
3
  import { mkdirSync } from 'fs';
4
- import { join } from 'path';
5
4
  export { homeDir };
6
- export const defaultOutDir = join(homeDir, 'Desktop', 'Screenshots');
5
+ /**
6
+ * Default output directory for screenshots.
7
+ * Configurable via SCREENSHOT_OUTPUT_DIR environment variable.
8
+ * Falls back to ~/Documents/screenshots, then ~/Desktop/Screenshots.
9
+ */
10
+ export const defaultOutDir = configuredOutDir;
7
11
  // SINGLETON — the only Semaphore instance in the entire codebase
8
12
  export const puppeteerSemaphore = new Semaphore(MAX_CONCURRENT_SCREENSHOTS);
9
13
  // Lazy directory creation — called by tools on first use, not at import
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import puppeteer from 'puppeteer';
3
3
  import { puppeteerSemaphore, defaultOutDir, ensureDefaultDirectory } from '../config/runtime.js';
4
- import { ALLOWED_OUTPUT_DIRS, MAX_CONCURRENT_SCREENSHOTS } from '../config/index.js';
4
+ import { ALLOWED_OUTPUT_DIRS, MAX_CONCURRENT_SCREENSHOTS, ALLOW_LOCAL } from '../config/index.js';
5
5
  import { validateUrl } from '../validators/url.js';
6
6
  import { validateOutputPath } from '../validators/path.js';
7
7
  import { ok, err, timestamp, ensureDir } from '../utils/helpers.js';
@@ -23,7 +23,7 @@ export function registerTakeScreenshot(server) {
23
23
  ensureDefaultDirectory(); // Ensure the default directory exists
24
24
  // Security: Validate URL before making request (SSRF prevention)
25
25
  // Now async to support DNS resolution for DNS rebinding protection (SEC-001)
26
- const urlValidation = await validateUrl(url);
26
+ const urlValidation = await validateUrl(url, { allowLocal: ALLOW_LOCAL });
27
27
  if (!urlValidation.valid) {
28
28
  return err(`URL validation failed: ${urlValidation.error}`);
29
29
  }
@@ -51,7 +51,11 @@ export function registerTakeScreenshot(server) {
51
51
  '--disable-setuid-sandbox',
52
52
  ];
53
53
  if (urlValidation.resolvedIp && urlValidation.hostname) {
54
- browserArgs.push(`--host-resolver-rules=MAP ${urlValidation.hostname} ${urlValidation.resolvedIp}`);
54
+ // Chromium requires bracket notation for IPv6 addresses in host-resolver-rules
55
+ const pinnedIp = urlValidation.resolvedIp.includes(':')
56
+ ? `[${urlValidation.resolvedIp}]`
57
+ : urlValidation.resolvedIp;
58
+ browserArgs.push(`--host-resolver-rules=MAP ${urlValidation.hostname} ${pinnedIp}`);
55
59
  }
56
60
  browser = await puppeteer.launch({ headless: true, args: browserArgs });
57
61
  const page = await browser.newPage();
@@ -75,7 +79,7 @@ export function registerTakeScreenshot(server) {
75
79
  return;
76
80
  }
77
81
  // Validate redirect target against SSRF rules
78
- const redirectValidation = await validateUrl(reqUrl);
82
+ const redirectValidation = await validateUrl(reqUrl, { allowLocal: ALLOW_LOCAL });
79
83
  if (!redirectValidation.valid) {
80
84
  req.abort('blockedbyclient');
81
85
  return;
@@ -8,6 +8,16 @@ import { execFileAsync, commandExists, sleep } from './screenshot-provider.js';
8
8
  */
9
9
  export class WindowsProvider {
10
10
  platform = 'Windows';
11
+ static DPI_AWARE_SNIPPET = `
12
+ Add-Type -TypeDefinition @"
13
+ using System;
14
+ using System.Runtime.InteropServices;
15
+ public class DpiAwareness {
16
+ [DllImport("user32.dll")]
17
+ public static extern bool SetProcessDPIAware();
18
+ }
19
+ "@
20
+ [DpiAwareness]::SetProcessDPIAware() | Out-Null`.trim();
11
21
  async isAvailable() {
12
22
  return commandExists('powershell');
13
23
  }
@@ -17,6 +27,7 @@ export class WindowsProvider {
17
27
  const format = this.dotNetFormat(opts.format);
18
28
  const displayIndex = (opts.display ?? 1) - 1; // Convert 1-based to 0-based
19
29
  const script = `
30
+ ${WindowsProvider.DPI_AWARE_SNIPPET}
20
31
  Add-Type -AssemblyName System.Windows.Forms
21
32
  Add-Type -AssemblyName System.Drawing
22
33
  $screens = [System.Windows.Forms.Screen]::AllScreens
@@ -49,6 +60,7 @@ $hwnd = $proc.MainWindowHandle
49
60
  `
50
61
  : `$hwnd = [IntPtr]::new(${opts.windowId})`;
51
62
  const script = `
63
+ ${WindowsProvider.DPI_AWARE_SNIPPET}
52
64
  Add-Type -AssemblyName System.Drawing
53
65
  Add-Type @"
54
66
  using System;
@@ -86,6 +98,7 @@ $bitmap.Dispose()
86
98
  await sleep(opts.delay);
87
99
  const format = this.dotNetFormat(opts.format);
88
100
  const script = `
101
+ ${WindowsProvider.DPI_AWARE_SNIPPET}
89
102
  Add-Type -AssemblyName System.Drawing
90
103
  $bitmap = New-Object System.Drawing.Bitmap(${opts.width}, ${opts.height})
91
104
  $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
@@ -3,6 +3,34 @@ import { URL } from 'url';
3
3
  const defaultDnsResolver = {
4
4
  lookup: (hostname, options) => dns.lookup(hostname, options),
5
5
  };
6
+ /** Check if an IP is a loopback address. */
7
+ function isLoopback(ip, family) {
8
+ if (family === 4) {
9
+ return /^127\./.test(ip);
10
+ }
11
+ const normalized = ip.toLowerCase();
12
+ if (normalized === '::1')
13
+ return true;
14
+ // ::ffff:127.x.x.x (dotted form)
15
+ if (/^::ffff:127\./.test(normalized))
16
+ return true;
17
+ // ::ffff:7f00:0 through ::ffff:7fff:ffff (hex form for 127.0.0.0/8)
18
+ const hexMatch = normalized.match(/^::ffff:([0-9a-f]{1,4}):[0-9a-f]{1,4}$/);
19
+ if (hexMatch) {
20
+ const high = parseInt(hexMatch[1], 16);
21
+ if ((high >> 8) === 127)
22
+ return true;
23
+ }
24
+ return false;
25
+ }
26
+ /** Wrapper that applies the allowLocal policy over isBlockedIPv4/isBlockedIPv6. */
27
+ function shouldBlockIp(ip, family, allowLocal) {
28
+ const result = family === 4 ? isBlockedIPv4(ip) : isBlockedIPv6(ip);
29
+ if (result.blocked && allowLocal && isLoopback(ip, family)) {
30
+ return { blocked: false };
31
+ }
32
+ return result;
33
+ }
6
34
  /** Check if an IPv4 address is in a blocked range. */
7
35
  export function isBlockedIPv4(ip) {
8
36
  const ipv4Match = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
@@ -100,7 +128,9 @@ export function isBlockedIPv6(ip) {
100
128
  * Validate a URL for SSRF prevention with DNS rebinding protection (SEC-001).
101
129
  * Returns resolvedIp and hostname on success to enable IP pinning.
102
130
  */
103
- export async function validateUrl(urlString, dnsResolver = defaultDnsResolver) {
131
+ export async function validateUrl(urlString, options) {
132
+ const allowLocal = options?.allowLocal ?? false;
133
+ const dnsResolver = options?.dnsResolver ?? defaultDnsResolver;
104
134
  let parsed;
105
135
  try {
106
136
  parsed = new URL(urlString);
@@ -113,20 +143,21 @@ export async function validateUrl(urlString, dnsResolver = defaultDnsResolver) {
113
143
  return { valid: false, error: 'Only http and https protocols are allowed' };
114
144
  }
115
145
  const hostname = parsed.hostname.toLowerCase();
116
- // Block localhost by name
117
- if (hostname === 'localhost' || hostname === 'localhost.localdomain') {
118
- return { valid: false, error: 'Access to localhost is not allowed' };
119
- }
120
- // Block IPv6 localhost in bracket notation
121
- if (hostname === '[::1]') {
122
- return { valid: false, error: 'Access to IPv6 localhost is not allowed' };
146
+ // Block localhost by name (unless allowLocal is enabled)
147
+ if (!allowLocal) {
148
+ if (hostname === 'localhost' || hostname === 'localhost.localdomain') {
149
+ return { valid: false, error: 'Access to localhost is not allowed' };
150
+ }
151
+ if (hostname === '[::1]') {
152
+ return { valid: false, error: 'Access to IPv6 localhost is not allowed' };
153
+ }
123
154
  }
124
155
  // Check if hostname is a literal IP address
125
156
  const isLiteralIPv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.test(hostname);
126
157
  const isLiteralIPv6 = hostname.startsWith('[') && hostname.endsWith(']');
127
158
  if (isLiteralIPv4) {
128
159
  // Direct IPv4 - validate immediately
129
- const ipCheck = isBlockedIPv4(hostname);
160
+ const ipCheck = shouldBlockIp(hostname, 4, allowLocal);
130
161
  if (ipCheck.blocked) {
131
162
  return { valid: false, error: ipCheck.reason };
132
163
  }
@@ -135,7 +166,7 @@ export async function validateUrl(urlString, dnsResolver = defaultDnsResolver) {
135
166
  if (isLiteralIPv6) {
136
167
  // Direct IPv6 - validate immediately (strip brackets)
137
168
  const ipv6 = hostname.slice(1, -1);
138
- const ipCheck = isBlockedIPv6(ipv6);
169
+ const ipCheck = shouldBlockIp(ipv6, 6, allowLocal);
139
170
  if (ipCheck.blocked) {
140
171
  return { valid: false, error: ipCheck.reason };
141
172
  }
@@ -152,16 +183,8 @@ export async function validateUrl(urlString, dnsResolver = defaultDnsResolver) {
152
183
  // Check ALL resolved IPs - if any is blocked, reject the entire request
153
184
  let firstNonBlockedIp;
154
185
  for (const addr of addresses) {
155
- if (addr.family === 4) {
156
- const ipCheck = isBlockedIPv4(addr.address);
157
- if (ipCheck.blocked) {
158
- return { valid: false, error: `DNS resolved to blocked IP: ${ipCheck.reason}` };
159
- }
160
- if (!firstNonBlockedIp)
161
- firstNonBlockedIp = addr.address;
162
- }
163
- else if (addr.family === 6) {
164
- const ipCheck = isBlockedIPv6(addr.address);
186
+ if (addr.family === 4 || addr.family === 6) {
187
+ const ipCheck = shouldBlockIp(addr.address, addr.family, allowLocal);
165
188
  if (ipCheck.blocked) {
166
189
  return { valid: false, error: `DNS resolved to blocked IP: ${ipCheck.reason}` };
167
190
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "universal-screenshot-mcp",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
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",
@@ -43,6 +43,10 @@
43
43
  "watch": "tsc --watch",
44
44
  "inspector": "npx @modelcontextprotocol/inspector build/index.js",
45
45
  "test": "vitest run",
46
+ "test:integration": "vitest run --config vitest.integration.config.ts",
47
+ "test:e2e": "vitest run --config vitest.e2e.config.ts",
48
+ "test:linux": "bash scripts/run-linux-tests.sh",
49
+ "test:all": "vitest run --config vitest.all.config.ts",
46
50
  "test:watch": "vitest",
47
51
  "test:coverage": "vitest run --coverage",
48
52
  "lint": "eslint src/"