scrapeunblocker-mcp 0.1.4 → 0.2.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.
Files changed (3) hide show
  1. package/README.md +43 -1
  2. package/dist/index.js +225 -11
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -11,10 +11,51 @@ You bring your **own** API key. Nothing is shared or proxied through us.
11
11
 
12
12
  | Tool | What it does |
13
13
  |------|--------------|
14
- | `fetch_html` | Fetch the fully rendered HTML of a URL. |
14
+ | `fetch_html` | Fetch the fully rendered HTML of a URL (optionally after running interactive browser `steps`). |
15
+ | `list_elements` | List a page's notable elements with a ready-to-use selector for each (selector discovery). |
15
16
  | `fetch_parsed` | Fetch a page and return AI-parsed structured JSON. |
16
17
  | `google_search` | Run a Google search and return organic results as JSON. |
17
18
 
19
+ ### Browser steps (interact, then capture)
20
+
21
+ Some pages only reveal what you need after you interact with them - accept a
22
+ cookie banner, click a tab, type into a search box and submit, or scroll to
23
+ trigger lazy loading. Pass an optional `steps` array to `fetch_html` and those
24
+ actions run in a **real browser**, in order, after the page loads; the resulting
25
+ HTML is then returned.
26
+
27
+ Available actions:
28
+
29
+ | Action | Fields |
30
+ |--------|--------|
31
+ | `wait_for` | `selector`, `selector_type?` (`css`/`xPath`/`className`/`tagName`), `timeout_ms?` |
32
+ | `wait_for_text` | `value`, `timeout_ms?` |
33
+ | `wait` | `value` (ms) |
34
+ | `click` | `selector`, `selector_type?`, `timeout_ms?` |
35
+ | `type` | `selector`, `selector_type?`, `value`, `clear?`, `timeout_ms?` (typed human-like) |
36
+ | `select` | `selector`, `selector_type?`, `value`, `timeout_ms?` |
37
+ | `press_key` | `value` (`Enter`, `Tab`, `Escape`, `Backspace`, `Delete`, `Space`, `Arrow*`, `Home`, `End`, `PageUp`, `PageDown`) |
38
+ | `scroll` | `value` (`"bottom"` or a pixel offset) |
39
+
40
+ Steps are **not idempotent** - they run once per call. If a step fails,
41
+ `fetch_html` returns which step failed, why, and the page HTML at that moment so
42
+ you can fix the selector and retry.
43
+
44
+ ### List elements (discover selectors first)
45
+
46
+ `list_elements` loads a page and returns a JSON list of its notable elements
47
+ (links, inputs, buttons, selects, ...), each with a ready-to-use `selector` plus
48
+ `tag`, `text` and useful attributes (`name`, `id`, `type`, `placeholder`,
49
+ `aria_label`, `href`, ...):
50
+
51
+ ```json
52
+ { "url": "https://example.com", "count": 42, "elements": [ { "tag": "input", "selector": "#search", "type": "text", "placeholder": "Search", "aria_label": "Search" } ] }
53
+ ```
54
+
55
+ The natural workflow is **discover, then act**: call `list_elements` to find the
56
+ selectors you need, then pass matching `steps` to `fetch_html` to click/type/
57
+ select and capture the resulting HTML.
58
+
18
59
  ## Get an API key
19
60
 
20
61
  Sign up and grab your key at **[app.scrapeunblocker.com](https://app.scrapeunblocker.com?utm_source=mcp&utm_medium=integration&utm_campaign=mcp-server)**. The server
@@ -76,6 +117,7 @@ SCRAPEUNBLOCKER_KEY=your_api_key_here npx -y scrapeunblocker-mcp
76
117
 
77
118
  - "Fetch the HTML of https://www.example-shop.com/product/123 and list the price."
78
119
  - "This page keeps blocking me: <url>. Use fetch_html to get it."
120
+ - "List the elements on <url>, then use fetch_html steps to type 'laptop' into the search box, press Enter, wait for the results, and give me the HTML."
79
121
  - "Search Google for 'best running shoes 2026' and give me the top 5 links."
80
122
 
81
123
  ## Development
package/dist/index.js CHANGED
@@ -4,12 +4,20 @@
4
4
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
6
  import { z } from "zod";
7
- import { ScrapeUnblockerClient } from "scrapeunblocker";
8
- var VERSION = "0.1.2";
7
+ import { APIError, ScrapeUnblockerClient } from "scrapeunblocker";
8
+ var VERSION = "0.2.1";
9
+ var DEFAULT_BASE_URL = "https://api.scrapeunblocker.com";
10
+ var API_KEY_HEADER = "x-scrapeunblocker-key";
9
11
  function resolveApiKey() {
10
12
  return process.env.SCRAPEUNBLOCKER_KEY ?? process.env.SCRAPEUNBLOCKER_API_KEY ?? void 0;
11
13
  }
12
14
  var MISSING_KEY_MESSAGE = "No ScrapeUnblocker API key found. Set the SCRAPEUNBLOCKER_KEY environment variable to your own key (get one at https://app.scrapeunblocker.com) and restart the MCP server.";
15
+ function resolveBaseUrl() {
16
+ return (process.env.SCRAPEUNBLOCKER_BASE_URL || DEFAULT_BASE_URL).replace(
17
+ /\/+$/,
18
+ ""
19
+ );
20
+ }
13
21
  function client() {
14
22
  const apiKey = resolveApiKey();
15
23
  if (!apiKey) throw new Error(MISSING_KEY_MESSAGE);
@@ -20,15 +28,128 @@ function errorText(err) {
20
28
  if (err instanceof Error) return err.message;
21
29
  return String(err);
22
30
  }
31
+ var TARGET_GONE = /* @__PURE__ */ new Set([404, 410]);
32
+ function targetGoneStatus(status, originStatus) {
33
+ const origin = Number(originStatus);
34
+ if (TARGET_GONE.has(origin)) return origin;
35
+ return TARGET_GONE.has(status) ? status : null;
36
+ }
37
+ function targetGoneText(url, code, page) {
38
+ const reason = code === 410 ? "Gone" : "Not Found";
39
+ const head = `The target page does not exist: ${url} answered HTTP ${code} (${reason}). This is the website's own answer, not a block or an API failure. The call was billed, and retrying returns the same result - check the URL instead.`;
40
+ return page.trim() ? `${head}
41
+
42
+ The target's own ${code} page follows:
43
+
44
+ ${page}` : `${head}
45
+
46
+ The target sent no page body.`;
47
+ }
48
+ function errorResult(url, err) {
49
+ const gone = err instanceof APIError ? targetGoneStatus(err.statusCode) : null;
50
+ if (gone !== null) {
51
+ const body = err instanceof APIError ? err.body ?? "" : "";
52
+ return { content: [{ type: "text", text: targetGoneText(url, gone, body) }] };
53
+ }
54
+ return { content: [{ type: "text", text: errorText(err) }], isError: true };
55
+ }
56
+ async function getPageSourceRaw(params) {
57
+ const apiKey = resolveApiKey();
58
+ if (!apiKey) throw new Error(MISSING_KEY_MESSAGE);
59
+ const query = new URLSearchParams();
60
+ for (const [key, value] of Object.entries(params)) {
61
+ if (value === void 0 || value === null) continue;
62
+ query.set(key, String(value));
63
+ }
64
+ const url = `${resolveBaseUrl()}/getPageSource?${query.toString()}`;
65
+ const response = await fetch(url, {
66
+ method: "POST",
67
+ headers: {
68
+ [API_KEY_HEADER]: apiKey,
69
+ "User-Agent": `scrapeunblocker-mcp/${VERSION}`,
70
+ Accept: "*/*"
71
+ }
72
+ });
73
+ const text = await response.text();
74
+ return {
75
+ status: response.status,
76
+ ok: response.ok,
77
+ text,
78
+ originStatus: response.headers.get("x-origin-status")
79
+ };
80
+ }
23
81
  var server = new McpServer({
24
82
  name: "scrapeunblocker",
25
83
  version: VERSION
26
84
  });
85
+ var selectorTypeSchema = z.enum(["css", "xPath", "className", "tagName"]).describe("How `selector` is interpreted. Defaults to 'css'.");
86
+ var pressableKeySchema = z.enum([
87
+ "Enter",
88
+ "Tab",
89
+ "Escape",
90
+ "Backspace",
91
+ "Delete",
92
+ "Space",
93
+ "ArrowUp",
94
+ "ArrowDown",
95
+ "ArrowLeft",
96
+ "ArrowRight",
97
+ "Home",
98
+ "End",
99
+ "PageUp",
100
+ "PageDown"
101
+ ]);
102
+ var stepSchema = z.discriminatedUnion("action", [
103
+ z.object({
104
+ action: z.literal("wait_for"),
105
+ selector: z.string().describe("Selector to wait for (until present)."),
106
+ selector_type: selectorTypeSchema.optional(),
107
+ timeout_ms: z.number().int().positive().optional()
108
+ }).describe("Wait until an element matching `selector` exists."),
109
+ z.object({
110
+ action: z.literal("wait_for_text"),
111
+ value: z.string().describe("Text to wait for anywhere on the page."),
112
+ timeout_ms: z.number().int().positive().optional()
113
+ }).describe("Wait until the given text appears on the page."),
114
+ z.object({
115
+ action: z.literal("wait"),
116
+ value: z.number().int().nonnegative().describe("Fixed pause in milliseconds.")
117
+ }).describe("Pause for a fixed number of milliseconds."),
118
+ z.object({
119
+ action: z.literal("click"),
120
+ selector: z.string().describe("Selector of the element to click."),
121
+ selector_type: selectorTypeSchema.optional(),
122
+ timeout_ms: z.number().int().positive().optional()
123
+ }).describe("Click the element matching `selector`."),
124
+ z.object({
125
+ action: z.literal("type"),
126
+ selector: z.string().describe("Selector of the field to type into."),
127
+ selector_type: selectorTypeSchema.optional(),
128
+ value: z.string().describe("Text to type (entered human-like)."),
129
+ clear: z.boolean().optional().describe("Clear the field before typing."),
130
+ timeout_ms: z.number().int().positive().optional()
131
+ }).describe("Type text into an input, character by character."),
132
+ z.object({
133
+ action: z.literal("select"),
134
+ selector: z.string().describe("Selector of the <select> element."),
135
+ selector_type: selectorTypeSchema.optional(),
136
+ value: z.string().describe("The option value to select."),
137
+ timeout_ms: z.number().int().positive().optional()
138
+ }).describe("Choose an option in a <select> dropdown by value."),
139
+ z.object({
140
+ action: z.literal("press_key"),
141
+ value: pressableKeySchema.describe("The key to press.")
142
+ }).describe("Press a single keyboard key."),
143
+ z.object({
144
+ action: z.literal("scroll"),
145
+ value: z.union([z.literal("bottom"), z.number().int()]).describe("'bottom' to scroll to the end, or a pixel offset.")
146
+ }).describe("Scroll the page to the bottom or by a pixel amount.")
147
+ ]);
27
148
  server.registerTool(
28
149
  "fetch_html",
29
150
  {
30
151
  title: "Fetch page HTML",
31
- description: "Fetch the fully rendered HTML of any web page through ScrapeUnblocker, bypassing anti-bot protection (Cloudflare, DataDome, PerimeterX, Akamai, Shape). Use this when a normal fetch is blocked (403/429, captcha, 'access denied') or when the page needs a real browser to render. Returns the raw HTML as text.",
152
+ description: "Fetch the fully rendered HTML of any web page through ScrapeUnblocker, bypassing anti-bot protection (Cloudflare, DataDome, PerimeterX, Akamai, Shape). Use this when a normal fetch is blocked (403/429, captcha, 'access denied') or when the page needs a real browser to render. Returns the raw HTML as text.\n\nFor pages that need interaction (accept a cookie banner, click a tab, type into a search box, scroll to trigger lazy loading) pass `steps`: an ordered list of browser actions run in a real browser AFTER the page loads, then the resulting HTML is returned. Workflow: first call the `list_elements` tool to discover the real selectors on the page, then build `steps` against them. Steps are NOT idempotent - they run once per call. If a step fails, this tool returns which step failed, why, and the page HTML at that moment so you can fix the selector and retry.",
32
153
  inputSchema: {
33
154
  url: z.string().url().describe("The absolute URL to fetch (http/https)."),
34
155
  proxy_country: z.string().length(2).optional().describe(
@@ -41,21 +162,114 @@ server.registerTool(
41
162
  `The CSS selector or JS expression paired with wait_method (e.g. '#price' or 'document.readyState==="complete"').`
42
163
  ),
43
164
  method_timeout_seconds: z.number().int().positive().optional().describe("Cap in seconds for the render-wait method."),
44
- sleep_seconds: z.number().positive().optional().describe("Extra seconds to wait after load before capturing the HTML.")
165
+ sleep_seconds: z.number().positive().optional().describe("Extra seconds to wait after load before capturing the HTML."),
166
+ steps: z.array(stepSchema).optional().describe(
167
+ "Optional ordered browser actions to run in a real browser after the page loads, before the HTML is captured. Use `list_elements` first to find selectors. Runs once (not idempotent)."
168
+ )
45
169
  }
46
170
  },
47
171
  async (args) => {
48
172
  try {
49
- const html = await client().getPageSource(args.url, {
50
- proxyCountry: args.proxy_country,
173
+ if (!args.steps || args.steps.length === 0) {
174
+ const html = await client().getPageSource(args.url, {
175
+ proxyCountry: args.proxy_country,
176
+ method: args.wait_method,
177
+ value: args.wait_value,
178
+ methodTimeout: args.method_timeout_seconds,
179
+ timeSleep: args.sleep_seconds
180
+ });
181
+ return { content: [{ type: "text", text: html }] };
182
+ }
183
+ const res = await getPageSourceRaw({
184
+ url: args.url,
185
+ proxy_country: args.proxy_country,
51
186
  method: args.wait_method,
52
187
  value: args.wait_value,
53
- methodTimeout: args.method_timeout_seconds,
54
- timeSleep: args.sleep_seconds
188
+ method_timeout: args.method_timeout_seconds,
189
+ time_sleep: args.sleep_seconds,
190
+ steps: JSON.stringify(args.steps)
55
191
  });
56
- return { content: [{ type: "text", text: html }] };
192
+ const gone = targetGoneStatus(res.status, res.originStatus);
193
+ if (gone !== null) {
194
+ return { content: [{ type: "text", text: targetGoneText(args.url, gone, res.text) }] };
195
+ }
196
+ if (res.ok) {
197
+ return { content: [{ type: "text", text: res.text }] };
198
+ }
199
+ if (res.status === 422) {
200
+ let detail = {};
201
+ try {
202
+ detail = JSON.parse(res.text);
203
+ } catch {
204
+ }
205
+ if (detail.error === "step_failed") {
206
+ const idx = typeof detail.step_index === "number" ? detail.step_index : void 0;
207
+ const summary = `Browser step failed` + (idx !== void 0 ? ` at index ${idx}` : "") + (detail.action ? ` (${detail.action})` : "") + (detail.selector ? ` on selector ${JSON.stringify(detail.selector)}` : "") + `: ${detail.reason ?? "unknown reason"}.
208
+
209
+ Fix the selector or step (use list_elements to inspect the page) and retry. The page HTML at the point of failure follows:
210
+
211
+ ` + (detail.html ?? "");
212
+ return { content: [{ type: "text", text: summary }], isError: true };
213
+ }
214
+ return {
215
+ content: [{ type: "text", text: res.text }],
216
+ isError: true
217
+ };
218
+ }
219
+ return {
220
+ content: [
221
+ {
222
+ type: "text",
223
+ text: `ScrapeUnblocker returned HTTP ${res.status}: ${res.text.slice(0, 500)}`
224
+ }
225
+ ],
226
+ isError: true
227
+ };
57
228
  } catch (err) {
58
- return { content: [{ type: "text", text: errorText(err) }], isError: true };
229
+ return errorResult(args.url, err);
230
+ }
231
+ }
232
+ );
233
+ server.registerTool(
234
+ "list_elements",
235
+ {
236
+ title: "List page elements (selector discovery)",
237
+ description: "Load a page through ScrapeUnblocker and return a JSON list of its notable elements (links, inputs, buttons, selects, etc.) with a ready-to-use `selector` for each, plus tag, text and useful attributes (name, id, type, placeholder, aria_label, href, ...). Read-only and does not interact with the page. This is the discovery half of interactive scraping: call `list_elements` to find the selectors you need, then pass matching `steps` to `fetch_html` to click/type/select and capture the resulting HTML.",
238
+ inputSchema: {
239
+ url: z.string().url().describe("The absolute URL whose elements you want to list."),
240
+ proxy_country: z.string().length(2).optional().describe("Optional ISO country code to route through, e.g. 'US'.")
241
+ }
242
+ },
243
+ async (args) => {
244
+ try {
245
+ const res = await getPageSourceRaw({
246
+ url: args.url,
247
+ list_elements: true,
248
+ proxy_country: args.proxy_country
249
+ });
250
+ const gone = targetGoneStatus(res.status, res.originStatus);
251
+ if (!res.ok && gone === null) {
252
+ return {
253
+ content: [
254
+ {
255
+ type: "text",
256
+ text: `ScrapeUnblocker returned HTTP ${res.status}: ${res.text.slice(0, 500)}`
257
+ }
258
+ ],
259
+ isError: true
260
+ };
261
+ }
262
+ let out = res.text;
263
+ try {
264
+ out = JSON.stringify(JSON.parse(res.text), null, 2);
265
+ } catch {
266
+ }
267
+ if (gone !== null) {
268
+ return { content: [{ type: "text", text: targetGoneText(args.url, gone, out) }] };
269
+ }
270
+ return { content: [{ type: "text", text: out }] };
271
+ } catch (err) {
272
+ return errorResult(args.url, err);
59
273
  }
60
274
  }
61
275
  );
@@ -82,7 +296,7 @@ server.registerTool(
82
296
  content: [{ type: "text", text: JSON.stringify(parsed, null, 2) }]
83
297
  };
84
298
  } catch (err) {
85
- return { content: [{ type: "text", text: errorText(err) }], isError: true };
299
+ return errorResult(args.url, err);
86
300
  }
87
301
  }
88
302
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scrapeunblocker-mcp",
3
- "version": "0.1.4",
3
+ "version": "0.2.1",
4
4
  "mcpName": "com.scrapeunblocker/scrapeunblocker-mcp",
5
5
  "description": "Model Context Protocol (MCP) server for ScrapeUnblocker - lets Claude fetch any web page's HTML (or AI-parsed JSON) through the ScrapeUnblocker anti-bot API, using your own API key.",
6
6
  "keywords": [