universal-screenshot-mcp 1.5.0 → 1.6.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
@@ -10,12 +10,13 @@ An [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) server that
10
10
 
11
11
  - **Web Page Screenshots** — Capture any public URL using a headless Chromium browser
12
12
  - **Cross-Platform System Screenshots** — Fullscreen, window, or region capture using native OS tools (macOS `screencapture`, Linux `maim`/`scrot`/`gnome-screenshot`/etc., Windows PowerShell+.NET)
13
+ - **Inline Images** — Web captures come back to the model as an image as well as a saved file (downscaled copy; system captures stay path-only unless you opt in)
13
14
  - **Security-First Design** — SSRF prevention, path traversal protection, DNS rebinding defense, command injection prevention, and DoS limiting
14
15
  - **MCP Native** — Integrates directly with Claude Desktop, Cursor, and any MCP-compatible client
15
16
 
16
17
  ## Requirements
17
18
 
18
- - **Node.js** >= 18.0.0
19
+ - **Node.js** `^22.13.0 || >=24`
19
20
  - **Chromium** is downloaded automatically by Puppeteer on first run
20
21
 
21
22
  ### Platform-Specific Requirements for `take_system_screenshot`
@@ -138,7 +139,7 @@ Captures a web page (or a specific element) via a headless Puppeteer browser.
138
139
  | `selector` | string | — | CSS selector to capture a specific element |
139
140
  | `waitForSelector` | string | — | Wait for this selector before capturing |
140
141
  | `waitForTimeout` | number | — | Delay in milliseconds (0–30000) |
141
- | `outputPath` | string | — | Output file path (default: `~/Documents/screenshots`) |
142
+ | `outputPath` | string | — | Output file path: absolute, or relative to the default output directory (`~/Documents/screenshots` or `SCREENSHOT_OUTPUT_DIR`). Must be a file, not a directory; a path ending in `/` or `\` counts as a directory. The extension sets the format: `.jpg`/`.jpeg`, `.webp`, otherwise PNG (reported as `image/png`). |
142
143
 
143
144
  **Example prompt:**
144
145
  > Take a screenshot of https://example.com at 1920x1080
@@ -155,9 +156,9 @@ Captures the desktop, a specific application window, or a screen region using na
155
156
  | `region` | object | — | `{ x, y, width, height }` for region mode |
156
157
  | `display` | number | — | Display number for multi-monitor setups |
157
158
  | `includeCursor` | boolean | — | Include the mouse cursor in the capture |
158
- | `format` | enum | — | `png` (default) or `jpg` |
159
+ | `format` | enum | — | `png` or `jpg`. Defaults to the `outputPath` extension (`.png`, `.jpg`, `.jpeg`), else `png`. A `format` that conflicts with the extension is rejected |
159
160
  | `delay` | number | — | Capture delay in seconds (0–10) |
160
- | `outputPath` | string | — | Output file path (default: `~/Documents/screenshots`) |
161
+ | `outputPath` | string | — | Output file path: absolute, or relative to the default output directory (`~/Documents/screenshots` or `SCREENSHOT_OUTPUT_DIR`). Must be a file, not a directory; a path ending in `/` or `\` counts as a directory. |
161
162
 
162
163
  #### Cross-Platform Feature Support
163
164
 
@@ -174,6 +175,19 @@ Captures the desktop, a specific application window, or a screen region using na
174
175
  **Example prompt:**
175
176
  > Take a system screenshot of the Safari window
176
177
 
178
+ ### Results
179
+
180
+ Both tools return, in order:
181
+
182
+ 1. a text block, `Screenshot saved: <path>` (or `System screenshot saved: <path>`), always first;
183
+ 2. an image block with a downscaled JPEG copy (long edge 1568 px, about 1 MB at most), when inlining is on for that tool. Any capture taller than max(1.5 × its width, 1568 px) is cropped to its top region for this copy only (`inline.cropped: true`); the saved file is never altered. If inlining fails the screenshot is still saved and the reason is reported;
184
+ 3. optional note text (inlining skipped, cropped, or renamed);
185
+ 4. a final text block with the JSON serialization of `structuredContent` (for clients that ignore structured output). `structuredContent` is also returned as a separate result field with the same data: `path`, `requestedPath` (only if renamed), `mimeType`, `bytes`, `inline`, plus `url`/`finalUrl` for web captures or `mode` for system captures.
186
+
187
+ **Existing files are never overwritten.** If `outputPath` (or a timestamped default) already exists, a numeric suffix is added: a second capture to `latest.png` is saved as `latest-1.png`. Always use the returned path.
188
+
189
+ A client cancel stops the capture as soon as it can; a pending browser launch is allowed to finish first, and on macOS a window-by-name lookup runs to completion before the cancel takes effect. `take_screenshot` reports progress when the client asks for it.
190
+
177
191
  ## Configuration
178
192
 
179
193
  ### Environment Variables
@@ -182,6 +196,11 @@ Captures the desktop, a specific application window, or a screen region using na
182
196
  |----------|---------|-------------|
183
197
  | `SCREENSHOT_OUTPUT_DIR` | `Documents/screenshots` | Default output directory relative to `~` |
184
198
  | `ALLOW_LOCAL` | `false` | Set to `true` to allow screenshotting `localhost`/`127.x.x.x`/`[::1]` (useful for local dev servers) |
199
+ | `SCREENSHOT_INLINE` | `web` | Which captures are also returned to the model as an inline image: `web` (`take_screenshot` only), `all` (also `take_system_screenshot`), or `none`. **`all` sends the contents of your desktop to the model provider.** Environment only; the model cannot change it. Empty means the default; an unrecognised value acts as `none` and logs one warning |
200
+
201
+ Web captures are now sent to the model inline by default; set `SCREENSHOT_INLINE=none` to keep the 1.5 behaviour (path only).
202
+
203
+ Page subresources such as images are not SSRF-checked, so with default inlining a hostile page's LAN images can reach the model; on sensitive networks, set `SCREENSHOT_INLINE=none` (see [`docs/SECURITY.md`](docs/SECURITY.md#inline-images)).
185
204
 
186
205
  ### Output Directories
187
206
 
@@ -193,7 +212,7 @@ Screenshots are saved to `~/Documents/screenshots` by default (configurable via
193
212
  | `~/Desktop/Screenshots`| Original default location |
194
213
  | `~/Downloads` | User downloads folder |
195
214
  | `~/Documents` | User documents folder |
196
- | `/tmp` | System temp directory |
215
+ | `os.tmpdir()` | System temp directory (on macOS this is the per-user `$TMPDIR`, not `/tmp`) |
197
216
 
198
217
  ## Security
199
218
 
@@ -201,13 +220,13 @@ This server implements multiple layers of security hardening:
201
220
 
202
221
  | ID | Threat | Mitigation |
203
222
  |---------|-----------------------|---------------------------------------------------------------------------------------------|
204
- | SEC-001 | SSRF / DNS rebinding | URLs validated against blocked IP ranges; DNS resolved pre-request with IP pinning via `--host-resolver-rules`; navigation redirects re-validated |
223
+ | SEC-001 | SSRF / DNS rebinding | URLs validated against blocked IP ranges; DNS resolved pre-request with IP pinning via `--host-resolver-rules`; navigation requests re-validated; a blocked main-frame navigation or a page left on Chrome's error page (including an HTTP error with an empty body) fails the call (a blocked iframe is left blank) |
205
224
  | SEC-003 | Command injection | All subprocesses use `execFile` (no shell); app names validated against `SAFE_APP_NAME_PATTERN` |
206
- | SEC-004 | Path traversal | Output paths validated with `fs.realpath()` symlink resolution; restricted to allowed directories |
207
- | SEC-005 | Denial of service | Concurrent Puppeteer instances limited to 3 via semaphore; 120 s hard deadline per call, after which the browser is killed and the slot freed |
225
+ | SEC-004 | Path traversal | Output paths validated with `fs.realpath()` symlink resolution; restricted to allowed directories; directories rejected; existing files never overwritten |
226
+ | SEC-005 | Denial of service | Concurrent Puppeteer instances limited to 3 via semaphore; 120 s hard deadline per call, after which the browser is killed and the slot freed; inline image work limited to 2 concurrent jobs with a 10 s timeout |
208
227
  | SEC-006 | Popup SSRF bypass | Chromium's popup blocker kept on (Puppeteer disables it by default); any popup that still opens is closed |
209
228
 
210
- For full details, see [`docs/security.md`](docs/security.md).
229
+ For full details, see [`docs/SECURITY.md`](docs/SECURITY.md).
211
230
 
212
231
  ## Development
213
232
 
@@ -219,35 +238,43 @@ For full details, see [`docs/security.md`](docs/security.md).
219
238
  | `npm run watch` | Recompile on file changes |
220
239
  | `npm test` | Unit tests (fast, fully mocked) |
221
240
  | `npm run test:integration` | Integration tests (real DNS/filesystem) |
222
- | `npm run test:e2e` | E2E tests (real Puppeteer/native tools)|
241
+ | `npm run test:e2e` | E2E tests (real Puppeteer/native tools; run `npm run build` first) |
223
242
  | `npm run test:all` | All test tiers together |
224
243
  | `npm run test:linux` | Linux e2e via Docker (requires Docker) |
225
244
  | `npm run test:watch` | Run tests in watch mode |
226
245
  | `npm run test:coverage` | Run tests with coverage report |
227
246
  | `npm run lint` | Lint source with ESLint |
247
+ | `npm run typecheck` | Type-check `src/` and `tests/` |
228
248
  | `npm run inspector` | Launch MCP Inspector for debugging |
229
249
 
230
250
  ### Project Structure
231
251
 
232
252
  ```
233
253
  src/
234
- ├── index.ts # Entry point — stdio transport
235
- ├── server.ts # MCP server factory
254
+ ├── index.ts # Entry point: --doctor, or serveStdio()
255
+ ├── server.ts # MCP server factory (instructions, cache hints)
236
256
  ├── config/
237
- │ ├── index.ts # Static constants (limits, allowed dirs)
238
- │ └── runtime.ts # Singleton semaphore, default directory
257
+ │ ├── index.ts # Static constants (limits, allowed dirs, SCREENSHOT_INLINE)
258
+ │ ├── instructions.ts # Server instructions sent to clients
259
+ │ └── runtime.ts # Semaphore singletons, default directory
239
260
  ├── tools/
240
261
  │ ├── take-screenshot.ts # Web page capture tool
241
- │ └── take-system-screenshot.ts # macOS system capture tool
262
+ │ ├── take-system-screenshot.ts # Cross-platform system capture tool
263
+ │ └── output-schemas.ts # outputSchema / structuredContent shapes
242
264
  ├── types/
243
265
  │ └── index.ts # Shared TypeScript interfaces
244
266
  ├── utils/
245
- │ ├── helpers.ts # Response builders, file utilities
267
+ │ ├── helpers.ts # Result builders, MIME types, file utilities
268
+ │ ├── output-file.ts # Temp file + exclusive commit (no overwrite)
269
+ │ ├── inline-image.ts # Downscaled inline JPEG via sharp
270
+ │ ├── progress.ts # Progress notifications
246
271
  │ ├── screenshot-provider.ts # Cross-platform provider interface + factory
247
272
  │ ├── macos-provider.ts # macOS: screencapture wrapper
248
273
  │ ├── linux-provider.ts # Linux: maim/scrot/gnome-screenshot/etc.
249
274
  │ ├── windows-provider.ts # Windows: PowerShell + .NET System.Drawing
250
275
  │ ├── macos.ts # Window ID lookup via CoreGraphics
276
+ │ ├── doctor.ts # --doctor host probe
277
+ │ ├── linux-deps.ts # Distro-specific install hints
251
278
  │ └── semaphore.ts # Async concurrency limiter
252
279
  └── validators/
253
280
  ├── path.ts # Output path validation (SEC-004)
@@ -260,7 +287,7 @@ Tests use [Vitest](https://vitest.dev/) in three tiers:
260
287
 
261
288
  - **Unit** (`npm test`) — Full dependency injection, no real I/O. Fast feedback loop.
262
289
  - **Integration** (`npm run test:integration`) — Real DNS resolution, real filesystem with temp directories, real Puppeteer against a local HTTP server.
263
- - **E2E** (`npm run test:e2e`) — Real native screenshot tools. macOS tests run natively; Linux tests run in Docker via `npm run test:linux`; Windows tests run on the `windows-latest` CI runner.
290
+ - **E2E** (`npm run test:e2e`) — Real native screenshot tools and the built server, so run `npm run build` first. macOS tests run natively; Linux tests run in Docker via `npm run test:linux`; Windows tests run on the `windows-latest` CI runner.
264
291
 
265
292
  ```bash
266
293
  npm test # Unit tests (~300ms)
@@ -34,7 +34,7 @@ export const ALLOW_LOCAL = process.env.ALLOW_LOCAL === 'true';
34
34
  export const homeDir = process.env.HOME || homedir();
35
35
  /**
36
36
  * Resolved default output directory for screenshots.
37
- * Priority: 1) SCREENSHOT_OUTPUT_DIR env var 2) ~/Documents/screenshots 3) ~/Desktop/Screenshots
37
+ * SCREENSHOT_OUTPUT_DIR (relative to the home directory) if set, otherwise ~/Documents/screenshots.
38
38
  */
39
39
  export const configuredOutDir = process.env.SCREENSHOT_OUTPUT_DIR
40
40
  ? join(homeDir, process.env.SCREENSHOT_OUTPUT_DIR.replace(/^~\/?/, ''))
@@ -52,3 +52,37 @@ export const ALLOWED_OUTPUT_DIRS = [
52
52
  * to prevent command injection in Swift code execution.
53
53
  */
54
54
  export const SAFE_APP_NAME_PATTERN = /^[a-zA-Z0-9 \-_]+$/;
55
+ /**
56
+ * Parse the SCREENSHOT_INLINE value. Unset, empty or whitespace-only -> 'web'. Case/whitespace are
57
+ * ignored. Any unrecognised value -> 'none', with one warning.
58
+ */
59
+ export function parseInlinePolicy(raw, warn) {
60
+ if (raw === undefined)
61
+ return 'web';
62
+ const v = raw.trim().toLowerCase();
63
+ if (v === '')
64
+ return 'web';
65
+ if (v === 'web' || v === 'all' || v === 'none')
66
+ return v;
67
+ warn(`Unrecognised SCREENSHOT_INLINE value "${raw}"; expected web, all or none. Inline images disabled.`);
68
+ return 'none';
69
+ }
70
+ /** Which screenshots are returned inline as images. Environment only. */
71
+ export const INLINE_POLICY = parseInlinePolicy(process.env.SCREENSHOT_INLINE, console.error);
72
+ /** Longest edge of the inline copy, in pixels. */
73
+ export const INLINE_MAX_EDGE_PX = 1568;
74
+ /** Maximum base64 length (characters) of the inline copy. */
75
+ export const INLINE_MAX_BYTES = 1_000_000;
76
+ export const INLINE_FORMAT = 'jpeg';
77
+ /** JPEG qualities tried in order until the result fits INLINE_MAX_BYTES. */
78
+ export const INLINE_QUALITY_STEPS = [80, 65, 50];
79
+ /**
80
+ * Height/width ratio of the top region kept when the inline copy is cropped.
81
+ * Any capture (not only full-page ones) is cropped to its top
82
+ * round(width * INLINE_MAX_ASPECT) pixels when its height exceeds
83
+ * max(round(width * INLINE_MAX_ASPECT), INLINE_MAX_EDGE_PX).
84
+ */
85
+ export const INLINE_MAX_ASPECT = 1.5;
86
+ export const INLINE_TIMEOUT_MS = 10_000;
87
+ /** Maximum concurrent inline-image (sharp) jobs. */
88
+ export const MAX_CONCURRENT_INLINE = 2;
@@ -0,0 +1,10 @@
1
+ import { configuredOutDir, ALLOWED_OUTPUT_DIRS } from './index.js';
2
+ /** Server-level instructions sent to clients at connection time. */
3
+ export const SERVER_INSTRUCTIONS = [
4
+ 'Screenshot tools: take_screenshot (web pages) and take_system_screenshot (desktop, window, region).',
5
+ `Files are saved to ${configuredOutDir} by default (~/Documents/screenshots unless SCREENSHOT_OUTPUT_DIR is set). outputPath must name a file (not a directory) inside one of: ${ALLOWED_OUTPUT_DIRS.join(', ')}.`,
6
+ 'Existing files are never overwritten: if the target exists, a numeric suffix is added to the file name.',
7
+ 'localhost and loopback URLs are blocked unless the server runs with ALLOW_LOCAL=true.',
8
+ 'SCREENSHOT_INLINE controls inline images in results: "web" (default) returns web captures inline, "all" also inlines system captures, "none" returns file paths only.',
9
+ 'take_system_screenshot mode "window" needs windowName (app name, e.g. "Safari") or windowId.',
10
+ ].join('\n');
@@ -1,15 +1,16 @@
1
1
  import { Semaphore } from '../utils/semaphore.js';
2
- import { MAX_CONCURRENT_SCREENSHOTS, homeDir, configuredOutDir } from './index.js';
2
+ import { MAX_CONCURRENT_SCREENSHOTS, MAX_CONCURRENT_INLINE, homeDir, configuredOutDir } from './index.js';
3
3
  import { mkdirSync } from 'fs';
4
4
  export { homeDir };
5
5
  /**
6
6
  * Default output directory for screenshots.
7
- * Configurable via SCREENSHOT_OUTPUT_DIR environment variable.
8
- * Falls back to ~/Documents/screenshots, then ~/Desktop/Screenshots.
7
+ * Configurable via SCREENSHOT_OUTPUT_DIR environment variable; otherwise
8
+ * ~/Documents/screenshots. (There is no further fallback.)
9
9
  */
10
10
  export const defaultOutDir = configuredOutDir;
11
- // SINGLETON — the only Semaphore instance in the entire codebase
11
+ // SINGLETONS — the only Semaphore instances in the entire codebase
12
12
  export const puppeteerSemaphore = new Semaphore(MAX_CONCURRENT_SCREENSHOTS);
13
+ export const inlineSemaphore = new Semaphore(MAX_CONCURRENT_INLINE);
13
14
  // Lazy directory creation — called by tools on first use, not at import
14
15
  let _defaultDirCreated = false;
15
16
  export function ensureDefaultDirectory() {
package/build/server.js CHANGED
@@ -1,11 +1,21 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { McpServer } from '@modelcontextprotocol/server';
3
+ import { SERVER_INSTRUCTIONS } from './config/instructions.js';
3
4
  import { registerTakeScreenshot } from './tools/take-screenshot.js';
4
5
  import { registerTakeSystemScreenshot } from './tools/take-system-screenshot.js';
5
6
  const require = createRequire(import.meta.url);
6
7
  const { version } = require('../package.json');
7
8
  export function createServer() {
8
- const server = new McpServer({ name: 'screenshot-server', version });
9
+ const server = new McpServer({ name: 'screenshot-server', version }, {
10
+ instructions: SERVER_INSTRUCTIONS,
11
+ cacheHints: {
12
+ 'tools/list': { ttlMs: 3_600_000, cacheScope: 'public' },
13
+ 'server/discover': { ttlMs: 3_600_000, cacheScope: 'private' },
14
+ },
15
+ // Largest real input is 13 elements: take_system_screenshot's 9 top-level
16
+ // fields + 4 in region.
17
+ maxToolInputElements: 64,
18
+ });
9
19
  registerTakeScreenshot(server);
10
20
  registerTakeSystemScreenshot(server);
11
21
  return server;
@@ -0,0 +1,28 @@
1
+ // ============================================================================
2
+ // Output schemas (D5) — the structuredContent shape of each tool's success result
3
+ // ============================================================================
4
+ import { z } from 'zod';
5
+ /** Whether an inline image copy was included, and why not. */
6
+ export const inlineInfoSchema = z.object({
7
+ included: z.boolean(),
8
+ reason: z.string().optional(),
9
+ width: z.number().optional(),
10
+ height: z.number().optional(),
11
+ cropped: z.boolean().optional(),
12
+ });
13
+ const baseOutputShape = {
14
+ path: z.string().describe('Where the file was actually saved'),
15
+ requestedPath: z.string().optional().describe('Present only when the requested path existed and the file was saved under a new name'),
16
+ mimeType: z.string().describe('MIME type of the saved file, from its extension'),
17
+ bytes: z.number().describe('Saved file size in bytes'),
18
+ inline: inlineInfoSchema.describe('Whether an inline image copy is included in this result'),
19
+ };
20
+ export const webOutputSchema = z.object({
21
+ ...baseOutputShape,
22
+ url: z.string().describe('The URL that was requested'),
23
+ finalUrl: z.string().describe('The page URL after redirects'),
24
+ });
25
+ export const systemOutputSchema = z.object({
26
+ ...baseOutputShape,
27
+ mode: z.enum(['fullscreen', 'window', 'region']),
28
+ });