universal-screenshot-mcp 1.0.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Seth Bang
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,234 @@
1
+ # Universal Screenshot MCP
2
+
3
+ [![npm version](https://img.shields.io/npm/v/universal-screenshot-mcp.svg)](https://www.npmjs.com/package/universal-screenshot-mcp)
4
+ [![MCP Registry](https://img.shields.io/badge/MCP_Registry-io.github.sethbang%2Fscreenshot--server-blue)](https://registry.modelcontextprotocol.io)
5
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green.svg)](LICENSE)
6
+
7
+ An [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) server that provides AI assistants with screenshot capabilities — both web page capture via [Puppeteer](https://pptr.dev/) and cross-platform system screenshots using native OS tools.
8
+
9
+ ## Features
10
+
11
+ - **Web Page Screenshots** — Capture any public URL using a headless Chromium browser
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
+ - **Security-First Design** — SSRF prevention, path traversal protection, DNS rebinding defense, command injection prevention, and DoS limiting
14
+ - **MCP Native** — Integrates directly with Claude Desktop, Cursor, and any MCP-compatible client
15
+
16
+ ## Requirements
17
+
18
+ - **Node.js** >= 18.0.0
19
+ - **Chromium** is downloaded automatically by Puppeteer on first run
20
+
21
+ ### Platform-Specific Requirements for `take_system_screenshot`
22
+
23
+ | Platform | Required Tools | Notes |
24
+ |----------|---------------|-------|
25
+ | **macOS** | `screencapture` (built-in) | No additional installation needed |
26
+ | **Linux** | One of: `maim`, `scrot`, `gnome-screenshot`, `spectacle`, `grim`, or `import` (ImageMagick) | `maim` or `scrot` recommended for full feature support. For window-by-name capture, also install `xdotool`. |
27
+ | **Windows** | `powershell` (built-in) | Uses .NET `System.Drawing` — no additional installation needed |
28
+
29
+ #### Linux Installation Examples
30
+
31
+ ```bash
32
+ # Ubuntu/Debian (recommended)
33
+ sudo apt install maim xdotool
34
+
35
+ # Fedora
36
+ sudo dnf install maim xdotool
37
+
38
+ # Arch Linux
39
+ sudo pacman -S maim xdotool
40
+
41
+ # Wayland (Sway, etc.)
42
+ sudo apt install grim
43
+ ```
44
+
45
+ ## Quick Start
46
+
47
+ ### Install from npm
48
+
49
+ ```bash
50
+ npm install -g universal-screenshot-mcp
51
+ ```
52
+
53
+ Or run directly with `npx`:
54
+
55
+ ```bash
56
+ npx universal-screenshot-mcp
57
+ ```
58
+
59
+ ### Install from Source
60
+
61
+ ```bash
62
+ git clone https://github.com/sethbang/mcp-screenshot-server.git
63
+ cd mcp-screenshot-server
64
+ npm install
65
+ npm run build
66
+ ```
67
+
68
+ ### Configure Your MCP Client
69
+
70
+ Add the server to your MCP client configuration. For **Claude Desktop**, edit `~/Library/Application Support/Claude/claude_desktop_config.json`:
71
+
72
+ ```json
73
+ {
74
+ "mcpServers": {
75
+ "screenshot-server": {
76
+ "command": "npx",
77
+ "args": ["-y", "universal-screenshot-mcp"]
78
+ }
79
+ }
80
+ }
81
+ ```
82
+
83
+ Or if installed from source:
84
+
85
+ ```json
86
+ {
87
+ "mcpServers": {
88
+ "screenshot-server": {
89
+ "command": "node",
90
+ "args": ["/absolute/path/to/mcp-screenshot-server/build/index.js"]
91
+ }
92
+ }
93
+ }
94
+ ```
95
+
96
+ For **Cursor** or other MCP clients, consult their documentation for the equivalent configuration.
97
+
98
+ ## Tools
99
+
100
+ The server exposes two MCP tools:
101
+
102
+ ### `take_screenshot`
103
+
104
+ Captures a web page (or a specific element) via a headless Puppeteer browser.
105
+
106
+ | Parameter | Type | Required | Description |
107
+ |-------------------|---------|----------|--------------------------------------------------|
108
+ | `url` | string | ✅ | URL to capture (http/https only) |
109
+ | `width` | number | — | Viewport width (1–3840) |
110
+ | `height` | number | — | Viewport height (1–2160) |
111
+ | `fullPage` | boolean | — | Capture the full scrollable page |
112
+ | `selector` | string | — | CSS selector to capture a specific element |
113
+ | `waitForSelector` | string | — | Wait for this selector before capturing |
114
+ | `waitForTimeout` | number | — | Delay in milliseconds (0–30000) |
115
+ | `outputPath` | string | — | Output file path (default: `~/Desktop/Screenshots`) |
116
+
117
+ **Example prompt:**
118
+ > Take a screenshot of https://example.com at 1920x1080
119
+
120
+ ### `take_system_screenshot`
121
+
122
+ Captures the desktop, a specific application window, or a screen region using native OS tools. Works on **macOS**, **Linux**, and **Windows**.
123
+
124
+ | Parameter | Type | Required | Description |
125
+ |-----------------|---------|----------|----------------------------------------------------------|
126
+ | `mode` | enum | ✅ | `fullscreen`, `window`, or `region` |
127
+ | `windowId` | number | — | Window ID for window mode |
128
+ | `windowName` | string | — | App name (e.g. `"Safari"`, `"Firefox"`) for window mode |
129
+ | `region` | object | — | `{ x, y, width, height }` for region mode |
130
+ | `display` | number | — | Display number for multi-monitor setups |
131
+ | `includeCursor` | boolean | — | Include the mouse cursor in the capture |
132
+ | `format` | enum | — | `png` (default) or `jpg` |
133
+ | `delay` | number | — | Capture delay in seconds (0–10) |
134
+ | `outputPath` | string | — | Output file path (default: `~/Desktop/Screenshots`) |
135
+
136
+ #### Cross-Platform Feature Support
137
+
138
+ | Feature | macOS | Linux | Windows |
139
+ |---------|-------|-------|---------|
140
+ | Fullscreen | ✅ | ✅ | ✅ |
141
+ | Region | ✅ | ✅ (maim, scrot, grim, import) | ✅ |
142
+ | Window by name | ✅ | ⚠️ X11 + xdotool | ⚠️ best-effort |
143
+ | Window by ID | ✅ | ✅ X11 only | ⚠️ HWND |
144
+ | Multi-display | ✅ | ⚠️ tool-dependent | ✅ |
145
+ | Include cursor | ✅ | ⚠️ tool-dependent | ⚠️ |
146
+ | Delay | ✅ | ✅ | ✅ |
147
+
148
+ **Example prompt:**
149
+ > Take a system screenshot of the Safari window
150
+
151
+ ## Output Directories
152
+
153
+ Screenshots are saved to `~/Desktop/Screenshots` by default. Custom output paths must resolve to one of these allowed directories:
154
+
155
+ | Directory | Description |
156
+ |------------------------|--------------------------|
157
+ | `~/Desktop/Screenshots`| Default output location |
158
+ | `~/Downloads` | User downloads folder |
159
+ | `~/Documents` | User documents folder |
160
+ | `/tmp` | System temp directory |
161
+
162
+ ## Security
163
+
164
+ This server implements multiple layers of security hardening:
165
+
166
+ | ID | Threat | Mitigation |
167
+ |---------|-----------------------|---------------------------------------------------------------------------------------------|
168
+ | 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 |
169
+ | SEC-003 | Command injection | All subprocesses use `execFile` (no shell); app names validated against `SAFE_APP_NAME_PATTERN` |
170
+ | SEC-004 | Path traversal | Output paths validated with `fs.realpath()` symlink resolution; restricted to allowed directories |
171
+ | SEC-005 | Denial of service | Concurrent Puppeteer instances limited to 3 via semaphore |
172
+
173
+ For full details, see [`docs/security.md`](docs/security.md).
174
+
175
+ ## Development
176
+
177
+ ### Scripts
178
+
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|
188
+
189
+ ### Project Structure
190
+
191
+ ```
192
+ src/
193
+ ├── index.ts # Entry point — stdio transport
194
+ ├── server.ts # MCP server factory
195
+ ├── config/
196
+ │ ├── index.ts # Static constants (limits, allowed dirs)
197
+ │ └── runtime.ts # Singleton semaphore, default directory
198
+ ├── tools/
199
+ │ ├── take-screenshot.ts # Web page capture tool
200
+ │ └── take-system-screenshot.ts # macOS system capture tool
201
+ ├── types/
202
+ │ └── index.ts # Shared TypeScript interfaces
203
+ ├── utils/
204
+ │ ├── helpers.ts # Response builders, file utilities
205
+ │ ├── screenshot-provider.ts # Cross-platform provider interface + factory
206
+ │ ├── macos-provider.ts # macOS: screencapture wrapper
207
+ │ ├── linux-provider.ts # Linux: maim/scrot/gnome-screenshot/etc.
208
+ │ ├── windows-provider.ts # Windows: PowerShell + .NET System.Drawing
209
+ │ ├── macos.ts # Window ID lookup via CoreGraphics
210
+ │ └── semaphore.ts # Async concurrency limiter
211
+ └── validators/
212
+ ├── path.ts # Output path validation (SEC-004)
213
+ └── url.ts # URL/SSRF validation (SEC-001)
214
+ ```
215
+
216
+ ### Testing
217
+
218
+ Tests use [Vitest](https://vitest.dev/) with full dependency injection — no real network calls, filesystem access, or subprocess execution in tests.
219
+
220
+ ```bash
221
+ npm test
222
+ ```
223
+
224
+ ### Debugging with MCP Inspector
225
+
226
+ ```bash
227
+ npm run inspector
228
+ ```
229
+
230
+ This launches the [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector) connected to your built server, allowing you to invoke tools interactively.
231
+
232
+ ## License
233
+
234
+ [Apache-2.0](LICENSE) — Copyright 2026 Seth Bang
@@ -0,0 +1,28 @@
1
+ // ============================================================================
2
+ // Configuration Constants
3
+ // ============================================================================
4
+ import { join } from 'path';
5
+ /**
6
+ * Maximum number of concurrent Puppeteer browser instances.
7
+ * Each instance spawns a Chromium process consuming 100-500MB of memory.
8
+ * SEC-005: Prevents resource exhaustion / DoS attacks.
9
+ */
10
+ export const MAX_CONCURRENT_SCREENSHOTS = 3;
11
+ /**
12
+ * Resolved allowed output directories for screenshots.
13
+ * Only these directories (and their subdirectories) are permitted for file output.
14
+ * Uses process.env.HOME at module load time (pure computation, no I/O side effects).
15
+ */
16
+ export const homeDir = process.env.HOME || '/tmp';
17
+ export const ALLOWED_OUTPUT_DIRS = [
18
+ join(homeDir, 'Desktop', 'Screenshots'), // ~/Desktop/Screenshots (default output)
19
+ '/tmp', // System temp directory
20
+ join(homeDir, 'Downloads'), // ~/Downloads
21
+ join(homeDir, 'Documents'), // ~/Documents
22
+ ];
23
+ /**
24
+ * Regex for validating macOS application names used in window-capture mode.
25
+ * Only allows alphanumeric characters, spaces, hyphens, and underscores
26
+ * to prevent command injection in Swift code execution.
27
+ */
28
+ export const SAFE_APP_NAME_PATTERN = /^[a-zA-Z0-9 \-_]+$/;
@@ -0,0 +1,16 @@
1
+ import { Semaphore } from '../utils/semaphore.js';
2
+ import { MAX_CONCURRENT_SCREENSHOTS, homeDir } from './index.js';
3
+ import { mkdirSync } from 'fs';
4
+ import { join } from 'path';
5
+ export { homeDir };
6
+ export const defaultOutDir = join(homeDir, 'Desktop', 'Screenshots');
7
+ // SINGLETON — the only Semaphore instance in the entire codebase
8
+ export const puppeteerSemaphore = new Semaphore(MAX_CONCURRENT_SCREENSHOTS);
9
+ // Lazy directory creation — called by tools on first use, not at import
10
+ let _defaultDirCreated = false;
11
+ export function ensureDefaultDirectory() {
12
+ if (!_defaultDirCreated) {
13
+ mkdirSync(defaultOutDir, { recursive: true });
14
+ _defaultDirCreated = true;
15
+ }
16
+ }
package/build/index.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
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);
10
+ process.exit(1);
11
+ });
@@ -0,0 +1,12 @@
1
+ import { createRequire } from 'node:module';
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { registerTakeScreenshot } from './tools/take-screenshot.js';
4
+ import { registerTakeSystemScreenshot } from './tools/take-system-screenshot.js';
5
+ const require = createRequire(import.meta.url);
6
+ const { version } = require('../package.json');
7
+ export function createServer() {
8
+ const server = new McpServer({ name: 'screenshot-server', version });
9
+ registerTakeScreenshot(server);
10
+ registerTakeSystemScreenshot(server);
11
+ return server;
12
+ }
@@ -0,0 +1,132 @@
1
+ import { z } from 'zod';
2
+ import puppeteer from 'puppeteer';
3
+ import { puppeteerSemaphore, defaultOutDir, ensureDefaultDirectory } from '../config/runtime.js';
4
+ import { ALLOWED_OUTPUT_DIRS, MAX_CONCURRENT_SCREENSHOTS } from '../config/index.js';
5
+ import { validateUrl } from '../validators/url.js';
6
+ import { validateOutputPath } from '../validators/path.js';
7
+ import { ok, err, timestamp, ensureDir } from '../utils/helpers.js';
8
+ // Semaphore protects expensive Puppeteer operations
9
+ export function registerTakeScreenshot(server) {
10
+ server.registerTool('take_screenshot', {
11
+ description: 'Capture web page or element via headless browser. Saves to ~/Desktop/Screenshots by default.',
12
+ inputSchema: {
13
+ url: z.string().describe('URL to capture'),
14
+ width: z.number().min(1).max(3840).optional().describe('Viewport width'),
15
+ height: z.number().min(1).max(2160).optional().describe('Viewport height'),
16
+ fullPage: z.boolean().optional().describe('Capture full page'),
17
+ selector: z.string().optional().describe('CSS selector for element'),
18
+ waitForSelector: z.string().optional().describe('Wait for selector'),
19
+ waitForTimeout: z.number().min(0).max(30000).optional().describe('Delay in ms'),
20
+ outputPath: z.string().optional().describe('Absolute path, or relative to home dir'),
21
+ },
22
+ }, async ({ url, width, height, fullPage, selector, waitForSelector, waitForTimeout, outputPath: custom }) => {
23
+ ensureDefaultDirectory(); // Ensure the default directory exists
24
+ // Security: Validate URL before making request (SSRF prevention)
25
+ // Now async to support DNS resolution for DNS rebinding protection (SEC-001)
26
+ const urlValidation = await validateUrl(url);
27
+ if (!urlValidation.valid) {
28
+ return err(`URL validation failed: ${urlValidation.error}`);
29
+ }
30
+ // Security: Validate output path (path traversal prevention)
31
+ // SEC-004: Now async to resolve symlinks before validation
32
+ const pathValidation = await validateOutputPath(custom, `screenshot-${timestamp()}.png`, { allowedOutputDirs: ALLOWED_OUTPUT_DIRS, defaultOutDir });
33
+ if (!pathValidation.valid) {
34
+ return err(`Output path validation failed: ${pathValidation.error}`);
35
+ }
36
+ const dest = pathValidation.path;
37
+ // SEC-005: DoS Protection - Limit concurrent Puppeteer instances
38
+ // Try to acquire a permit without waiting. If at capacity, reject immediately
39
+ // rather than queuing (which would still allow memory exhaustion via queued requests).
40
+ // Each browser instance consumes 100-500MB, so we limit to MAX_CONCURRENT_SCREENSHOTS.
41
+ if (!puppeteerSemaphore.tryAcquire()) {
42
+ return err(`Concurrent screenshot limit reached (max ${MAX_CONCURRENT_SCREENSHOTS}). ` +
43
+ `Please wait for existing screenshots to complete.`);
44
+ }
45
+ // Declare browser outside try block to ensure cleanup in finally
46
+ let browser;
47
+ try {
48
+ // SEC-001: IP pinning to protect against DNS rebinding attacks
49
+ const browserArgs = [
50
+ '--no-sandbox',
51
+ '--disable-setuid-sandbox',
52
+ ];
53
+ if (urlValidation.resolvedIp && urlValidation.hostname) {
54
+ browserArgs.push(`--host-resolver-rules=MAP ${urlValidation.hostname} ${urlValidation.resolvedIp}`);
55
+ }
56
+ browser = await puppeteer.launch({ headless: true, args: browserArgs });
57
+ const page = await browser.newPage();
58
+ if (width && height)
59
+ await page.setViewport({ width, height });
60
+ // SEC-001: Intercept requests to prevent SSRF via HTTP redirects.
61
+ // page.goto() follows redirects by default; a 302 to an internal host
62
+ // would bypass the initial URL validation and --host-resolver-rules pin.
63
+ await page.setRequestInterception(true);
64
+ page.on('request', async (req) => {
65
+ try {
66
+ // Only validate navigation requests (initial load + redirects).
67
+ // Subresource requests (images, scripts, etc.) are allowed through
68
+ // since blocking them would break most pages, and the primary SSRF
69
+ // threat is navigation-level redirects to internal services.
70
+ if (req.isNavigationRequest()) {
71
+ const reqUrl = req.url();
72
+ // Allow the original validated URL through without re-validation
73
+ if (reqUrl === url) {
74
+ req.continue();
75
+ return;
76
+ }
77
+ // Validate redirect target against SSRF rules
78
+ const redirectValidation = await validateUrl(reqUrl);
79
+ if (!redirectValidation.valid) {
80
+ req.abort('blockedbyclient');
81
+ return;
82
+ }
83
+ req.continue();
84
+ }
85
+ else {
86
+ req.continue();
87
+ }
88
+ }
89
+ catch {
90
+ // If validation throws unexpectedly, abort the request rather than
91
+ // leaving it dangling (which would hang page navigation until timeout).
92
+ try {
93
+ req.abort('failed');
94
+ }
95
+ catch { /* request may already be handled */ }
96
+ }
97
+ });
98
+ await page.goto(url, { waitUntil: 'networkidle0', timeout: 30000 });
99
+ if (waitForSelector)
100
+ await page.waitForSelector(waitForSelector, { timeout: 30000 });
101
+ if (waitForTimeout)
102
+ await new Promise(r => setTimeout(r, waitForTimeout));
103
+ ensureDir(dest);
104
+ if (selector) {
105
+ const el = await page.$(selector);
106
+ if (!el) {
107
+ return err(`Element not found: ${selector}`);
108
+ }
109
+ await el.screenshot({ path: dest });
110
+ }
111
+ else {
112
+ await page.screenshot({ path: dest, fullPage: fullPage || false });
113
+ }
114
+ return ok(`Screenshot saved: ${dest}`);
115
+ }
116
+ catch (e) {
117
+ return err(`Screenshot error: ${e instanceof Error ? e.message : e}`);
118
+ }
119
+ finally {
120
+ // Ensure browser is always closed to prevent resource leaks
121
+ // Close browser BEFORE releasing semaphore to avoid briefly exceeding concurrency limit
122
+ if (browser) {
123
+ try {
124
+ await browser.close();
125
+ }
126
+ catch { /* browser may already be dead */ }
127
+ }
128
+ // SEC-005: Always release permit to prevent deadlock, even on error
129
+ puppeteerSemaphore.release();
130
+ }
131
+ });
132
+ }