@crawlbrulee/mcp 1.3.3 → 1.5.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.
Files changed (3) hide show
  1. package/README.md +115 -29
  2. package/dist/index.js +169 -59
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -49,7 +49,7 @@ claude mcp add crawlbrulee -- npx -y @crawlbrulee/mcp
49
49
  other stdio hosts run the same command: `npx -y @crawlbrulee/mcp`. a few of them (Codex,
50
50
  Cursor, Windsurf, Gemini CLI, Claude Desktop) need the key or the variable named in their
51
51
  config file, and VS Code and the Claude Code plugin can ask for the key in a masked prompt.
52
- the file and the entry for each one: [mcp setup in the docs](https://crawlbrulee.com/docs/mcp#install).
52
+ the file and the entry for each one: [mcp setup in the docs](https://crawlbrulee.com/docs/mcp/local#install).
53
53
 
54
54
  if a key stops working (`invalid_credentials`), it's expired, revoked or mistyped: create a
55
55
  new one the same way, replace the old one, and start your agent again.
@@ -72,7 +72,7 @@ server failing to come up. see
72
72
  ### `scrape`
73
73
 
74
74
  fetch a single url and return the requested content (markdown, cleaned
75
- html, raw html, links, images, screenshot, page metadata).
75
+ html, raw html, links, images, screenshot, pdf, page metadata).
76
76
 
77
77
  **input** — only `url` is required; everything else has sane defaults.
78
78
 
@@ -95,34 +95,83 @@ html, raw html, links, images, screenshot, page metadata).
95
95
 
96
96
  `zero_data_retention` (boolean, default `false`) keeps the result out of the shared cache; anything stored to deliver it is kept for 24 hours, then deleted. it adds 1 credit and must be enabled for your organization. `scrape_async` takes it too. see [zero data retention](https://crawlbrulee.com/docs/zero-data-retention).
97
97
 
98
- **named values with `extract.elements`.** to pull a few values from a page — prices, titles, links — give each one a name and a CSS selector, instead of reading the whole markdown. they come back in `elements` under the same names. `all: true` returns every match as a list, and `fields` reads named values inside each match. it costs no extra credits. `scrape_async` takes it too.
98
+ **named values with `extract.elements`.** to pull a few values from a page — prices, titles, links — give each one a name and a CSS selector, instead of reading the whole markdown. they come back in `elements` under the same names. `all: true` returns every match as a list, and `fields` reads named values inside each match (`:scope` reads the match itself). markdown and metadata stay on unless you turn them off, as the example does. it costs no extra credits. `scrape_async` takes it too.
99
99
 
100
100
  ```jsonc
101
101
  {
102
- "url": "https://books.toscrape.com/",
102
+ "url": "https://shop.example.com/books/",
103
103
  "extract": {
104
+ "markdown": false,
105
+ "metadata": false,
104
106
  "elements": {
105
107
  "heading": "h1",
106
108
  "books": {
107
- "selector": "article.product_pod",
109
+ "selector": "article.book",
108
110
  "all": true,
109
111
  "fields": {
110
112
  "title": { "selector": "h3 a", "output": "attribute", "attribute": "title" },
111
- "price": ".price_color",
113
+ "price": ".price",
112
114
  },
113
115
  },
114
116
  },
115
117
  },
116
118
  }
117
119
  // → "elements": {
118
- // "heading": "All products",
119
- // "books": [{ "title": "A Light in the Attic", "price": "£51.77" }, ...]
120
+ // "heading": "Books",
121
+ // "books": [{ "title": "The Night Garden", "price": "€18.90" }, ...]
120
122
  // }
121
123
  ```
122
124
 
123
- a name with no match is `null` (or `[]` with `all: true`). limits and selector rules: see [elements](https://crawlbrulee.com/docs/scrape/elements).
125
+ a name with no match is `null` (or `[]` with `all: true`). limits and selector rules: see [targeted extraction](https://crawlbrulee.com/docs/scrape/targeted-extraction).
124
126
 
125
- **output** — full scrape result. page metadata (title, OG tags, etc.) is returned under `metadata`. extracted `images` are returned as absolute urls — query strings are preserved, and relative `src`s are resolved against the page url. screenshots are returned as signed download urls the agent can fetch separately. in rare cases a screenshot can't be captured: when you requested other outputs too, the `screenshot` field is simply left out while the rest is still returned — but a screenshot-only call that can't deliver errors instead (`unsupported_screenshot_output`, HTTP 422, when the content type can't be screenshotted) and isn't billed. the result also carries `page_status_code` and a top-level `response_meta.usage` block:
127
+ **your own headers and cookies with `headers` and `cookies`.** send your own HTTP headers and cookies to the site, for example an `Authorization` header or a fixed `User-Agent` that a site has on its allowlist. headers go only to the origin of `url` (or its https version, for an http url) and cookies only to its host, never to another site on a redirect. up to 10 headers and 20 cookies. a request with headers or cookies never reads from or writes to the cache, and costs the same as a normal fresh scrape. `scrape_async` takes them too.
128
+
129
+ ```jsonc
130
+ {
131
+ "url": "https://app.example.com/orders",
132
+ "headers": { "Authorization": "Bearer ...", "X-Tenant-Id": "acme" },
133
+ "cookies": [{ "name": "session_id", "value": "a1b2c3" }],
134
+ }
135
+ ```
136
+
137
+ > [!WARNING]
138
+ > header and cookie values pass through your chat with the AI, so the AI host may keep them in its history. use short-lived tokens or a test account, and never a password you can't change.
139
+
140
+ your own `User-Agent` can lower the success rate, and the response then carries the `custom_user_agent` warning. never put secrets in the `User-Agent`. the limits and which headers can't be set: see [headers and cookies](https://crawlbrulee.com/docs/scrape/custom-headers-and-cookies).
141
+
142
+ **save the page as a pdf with `extract.pdf`.** you get a real document, with text you can select and links that work. `{}` takes every default: the page on a4 sheets, as it looks on screen. a pdf costs what a screenshot costs, and a pdf and a screenshot in one request are billed once. `scrape_async` takes it too.
143
+
144
+ ```jsonc
145
+ {
146
+ "url": "https://example.com/report",
147
+ "extract": {
148
+ "markdown": false,
149
+ "metadata": false,
150
+ "pdf": { "layout": "pages", "paper": "letter", "landscape": false, "media": "print" },
151
+ },
152
+ }
153
+ // → "pdf": { "url": "https://...", "bytes": 48213 }
154
+ ```
155
+
156
+ | option | values | default | what it does |
157
+ | ----------- | ------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------- |
158
+ | `layout` | `pages` \| `single_page` | `pages` | `pages` puts the page on sheets of paper. `single_page` makes one page as tall as the web page, up to 15,000 px. |
159
+ | `paper` | `a4` \| `letter` | `a4` | paper size. only with `pages`. |
160
+ | `landscape` | `true` \| `false` | `false` | turn the paper sideways. only with `pages`. |
161
+ | `media` | `screen` \| `print` | `screen` | `print` uses the site's own print style, which on many sites hides menus and images. |
162
+
163
+ the pdf link is a signed link that expires 24 hours after the scrape, like a screenshot link: download the file and keep it, not the link. a cached copy answers only when it has a pdf made with the same settings; `cache.max_age: 0` always makes a new one. in rare cases the pdf can't be made: you still get the rest of the scrape, with the `pdf_unavailable` warning, and the request costs what it costs without the pdf.
164
+
165
+ **dark-theme screenshots with `color_scheme`.** set `extract.screenshot.color_scheme` to `dark` to ask the site for its dark theme. a site with no dark theme looks the same as with `light`, the default. it costs no extra credits. when the request also asks for `extract.pdf`, the pdf shows the dark theme too; a pdf on its own is made with the light theme.
166
+
167
+ ```jsonc
168
+ {
169
+ "url": "https://example.com",
170
+ "extract": { "screenshot": { "type": "viewport", "color_scheme": "dark" } },
171
+ }
172
+ ```
173
+
174
+ **output** — full scrape result. page metadata (title, OG tags, etc.) is returned under `metadata`. extracted `images` are returned as absolute urls — query strings are preserved, and relative `src`s are resolved against the page url. screenshots and pdfs are returned as signed download urls the agent can fetch separately. in rare cases a screenshot can't be captured: when you requested other outputs too, the `screenshot` field is left out while the rest is still returned. a screenshot-only call (every other format off: `markdown: false` and `metadata: false`, and no `cleaned_html`, `raw_html`, `links`, `images` or `elements`) that can't deliver errors instead (`unsupported_screenshot_output`, HTTP 422, when the content type can't be screenshotted) and isn't billed. a pdf-only call works the same way, with `unsupported_pdf_output`. when no capture could be made at all, such a call fails with `internal_server_error` (HTTP 500), also not billed. a `scrape_async` job that asks only for a screenshot, a pdf or both and gets none ends `failed` and isn't billed: `scrape_result` then returns the same `unsupported_screenshot_output` or `unsupported_pdf_output`, or `job_failed` when the capture could not be made. the result also carries `page_status_code` and a top-level `response_meta.usage` block:
126
175
 
127
176
  ```jsonc
128
177
  {
@@ -150,15 +199,15 @@ a name with no match is `null` (or `[]` with `all: true`). limits and selector r
150
199
 
151
200
  alongside `response_meta.usage`, the result surfaces any non-fatal `warnings` — stable string codes an agent can switch on. an outsized page is truncated rather than refused, and the code names which part was cut:
152
201
 
153
- | code | what it means for the payload |
154
- | ------------------------- | ----------------------------------------------------------------------------------------------------- |
155
- | `screenshot_truncated` | the page was taller than the scrolling-capture height cap; the screenshot covers the top of the page. |
156
- | `links_truncated` | the page had more than 30,000 links; the `links` array is cut at the cap and is incomplete. |
157
- | `inline_images_truncated` | the page had more than 10,000 inline images; the `images` array is cut at the cap and is incomplete. |
158
- | `raw_html_truncated` | the page body exceeded 10,000,000 characters; `raw_html` is cut at a tag boundary, never mid-tag. |
159
- | `elements_truncated` | an `elements` value hit a limit; see [elements](https://crawlbrulee.com/docs/scrape/elements). |
202
+ | code | what it means for the payload |
203
+ | ------------------------- | -------------------------------------------------------------------------------------------------------------------- |
204
+ | `screenshot_truncated` | the page was taller than the scrolling-capture height cap; the screenshot covers the top of the page. |
205
+ | `links_truncated` | the page had more than 30,000 links; the `links` array is cut at the cap and is incomplete. |
206
+ | `inline_images_truncated` | the page had more than 10,000 inline images; the `images` array is cut at the cap and is incomplete. |
207
+ | `raw_html_truncated` | the page body exceeded 10,000,000 characters; `raw_html` is cut at a tag boundary, never mid-tag. |
208
+ | `elements_truncated` | an `elements` value hit a limit; see [targeted extraction](https://crawlbrulee.com/docs/scrape/targeted-extraction). |
160
209
 
161
- one more code is not about size: `screenshot_unavailable` means a screenshot was asked for, but the page came back from the http engine without one. the rest of the result is still there.
210
+ more codes are not about size. `screenshot_unavailable` means a screenshot was asked for, but the page came back from the http engine without one; the rest of the result is still there. `pdf_unavailable` means the same for a pdf. `pdf_single_page_overflow` means a `single_page` pdf was taller than 15,000 px, so it goes on over more pages. `custom_user_agent` means the request set its own `User-Agent` header; this can lower the success rate.
162
211
 
163
212
  and if you requested an extract that doesn't apply to the content type (e.g. `metadata` of a JSON file), the field name comes back in an `unsupported_fields` list — with the rest of the payload still returned.
164
213
 
@@ -193,7 +242,7 @@ the job lifecycle is documented under [async scrape](https://crawlbrulee.com/doc
193
242
 
194
243
  ### `scrape_status`
195
244
 
196
- look up the current lifecycle status of an async job: `pending`, `running`, `done`, or `failed` (with an `error` message when failed). once the job is `done` the response also carries a `response_meta.usage` block (`total_credit_cost` and its parts, billed `engine`, resolved `proxy` tier). a cache hit is represented by `engine: "cache"`. a job whose page the site served ends `done` even when that page is a 404 — read `page_status_code` in the result. poll until `done`, then call `scrape_result`.
245
+ look up the current lifecycle status of an async job: `pending`, `running`, `done`, or `failed` (with an `error` message when failed). once the job is `done` the response also carries a `response_meta.usage` block (`total_credit_cost` and its parts, billed `engine`, resolved `proxy` tier). a cache hit is represented by `engine: "cache"`. a job whose page the site served ends `done` even when that page is a 404 — read `page_status_code` in the result. a job that asked only for a screenshot, a pdf or both and got none ends `failed`, not billed; `scrape_result` names the reason. poll until `done`, then call `scrape_result`.
197
246
 
198
247
  ```jsonc
199
248
  { "job_id": "..." }
@@ -201,7 +250,7 @@ look up the current lifecycle status of an async job: `pending`, `running`, `don
201
250
 
202
251
  ### `scrape_result`
203
252
 
204
- fetch the extracted content of a completed async job — the same result shape as the synchronous `scrape` tool (including `page_status_code`, `metadata`, `elements` and `response_meta.usage`). errors if the job is still `pending`/`running`, so check `scrape_status` first.
253
+ fetch the extracted content of a completed async job — the same result shape as the synchronous `scrape` tool (including `page_status_code`, `metadata`, `elements` and `response_meta.usage`). errors if the job is still `pending`/`running`, so check `scrape_status` first. a `failed` job returns `job_failed`, or `unsupported_screenshot_output` / `unsupported_pdf_output` for a capture-only job on a content type that can't be captured.
205
254
 
206
255
  ```jsonc
207
256
  { "job_id": "..." }
@@ -209,11 +258,23 @@ fetch the extracted content of a completed async job — the same result shape a
209
258
 
210
259
  ### `map`
211
260
 
212
- build (or fetch a cached) link-map for a website. combines sitemap discovery with homepage link extraction. use this to enumerate a site before scraping selected pages. each link is just `{ url }`.
261
+ build (or fetch a cached) link map of a website from its sitemaps, plus the links on its home page. use this to enumerate a site before scraping selected pages. every link is `{ url, type, lastmod }`: `type` is `page` or `sitemap`, and `lastmod` is the entry's date from the sitemap, in UTC, or `null` when the sitemap gives none. a link found on the home page is a `page` with `lastmod: null`.
262
+
263
+ a plain map (`{ "url": "https://example.com" }`) returns pages. it reads the site's top sitemap files and two levels of nested ones, and adds the links on the home page.
264
+
265
+ | field | values | default | what it does |
266
+ | ---------------- | ------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
267
+ | `sitemap_url` | a full http or https address | none | start from this sitemap file. it must be on the same site as `url`, or on a host the site's robots.txt names, such as a CDN. left out: start from the site's own top sitemap files. |
268
+ | `depth` | `0` to `3` | `3` | how many levels of nested sitemaps to follow (see below). |
269
+ | `entries` | `pages` \| `sitemaps` \| `all` | `pages` | what to return: page addresses, sitemap files, or both. |
270
+ | `modified_since` | a date, or ISO 8601 with a zone | none | only entries whose `lastmod` is at or after it (see below). |
271
+ | `max_results` | `1` to `100000` | `5000` | the most entries the map finds, counting only the kind in `entries`. a discovery budget, not a trim at the end (see below). |
272
+ | `limit` | `1` to `10000` | `5000` | links per page of the answer. it only pages the answer. |
273
+ | `sitemap_only` | `true` \| `false` | `false` | use the sitemaps only: leave out the links found on the home page. |
213
274
 
214
- `max_urls` (default `5000`, max `100000`) is a discovery budget, not a trim at the end — discovery stops as soon as that many urls are found, so a smaller value is a faster, cheaper crawl. `limit` (default `5000`, max `10000`) only pages the answer.
275
+ `max_results` stops discovery as soon as that many entries of the asked kind are found, so a smaller value is a faster, lighter map. a map stopped that way returns exactly that many links with `response_capped: false`. the signal that the site has more is `truncation.discovery_cap_reason`.
215
276
 
216
- returned urls are normalized the same way `scrape` normalizes its returned `url`, so map-then-scrape stays on one host. results are ordered with the most useful links first.
277
+ returned urls are normalized the same way `scrape` normalizes its returned `url`, so map-then-scrape stays on one host. results are ordered with the most useful links first. the site root is listed only when a sitemap lists it.
217
278
 
218
279
  the response's `response_meta` carries `pagination`, `truncation`, and a `usage` block (`total_credit_cost` = `engine_credit_cost` × `proxy_multiplier` + `zero_data_retention_credit_cost`, billed `engine`, resolved `proxy` tier). map has no screenshot slicing and no `page_status_code`, since it reads many files, not one page. a map that found nothing because the site answered only with statuses we don't bill (a `5xx`, for example), or not at all, is empty and free.
219
280
 
@@ -222,7 +283,7 @@ the response's `response_meta` carries `pagination`, `truncation`, and a `usage`
222
283
  "url": "https://example.com",
223
284
  "sitemap_only": false,
224
285
  "types": { "internal": true, "external": false, "internal_subdomains": true },
225
- "max_urls": 5000,
286
+ "max_results": 5000,
226
287
  "page": 1,
227
288
  "limit": 1000,
228
289
  "zero_data_retention": false,
@@ -231,23 +292,46 @@ the response's `response_meta` carries `pagination`, `truncation`, and a `usage`
231
292
 
232
293
  `zero_data_retention` works as it does on `scrape` (see [zero data retention](https://crawlbrulee.com/docs/zero-data-retention)).
233
294
 
234
- a map stopped by your own `max_urls` returns exactly that many links with `response_capped: false` — the signal that the site has more is `truncation.discovery_cap_reason`:
235
-
236
295
  ```jsonc
237
296
  {
238
297
  "truncation": {
239
298
  "storage_capped": false,
240
299
  "response_capped": false,
241
- "total_before_max_urls": 5000,
300
+ "total_before_max_results": 5000,
242
301
  "total_detected_before_storage_cap": 5000,
243
302
  "discovery_capped": true, // discovery stopped before reading every sitemap file
244
303
  "sitemaps_skipped": 3, // files skipped or only partly read
245
- "discovery_cap_reason": "max_urls", // retry with a higher max_urls
304
+ "unread_sitemaps": [], // sitemap files this call did not read whole
305
+ "discovery_cap_reason": "max_results", // retry with a higher max_results
246
306
  },
247
307
  }
248
308
  ```
249
309
 
250
- `discovery_cap_reason` is one of `max_urls`, `time`, `file_budget`, `depth`, `file_size`, `unread_files`, or `null` when nothing stopped discovery. only `max_urls` is a limit you can raise from the request. `unread_files` means a sitemap file the site publishes could not be read at all this time — often temporary, so asking again later can return more. `time`, `file_budget`, `depth` and `file_size` mean the site itself is big, slow or deep, and a retry will not help.
310
+ `discovery_cap_reason` is one of these, or `null` when nothing stopped discovery:
311
+
312
+ - `max_results`: your own `max_results` was reached. ask again with a higher one to get more.
313
+ - `depth`: there are sitemap files past the `depth` you asked for. they are in `unread_sitemaps`. this is the answer to the depth you chose, not a fault.
314
+ - `unread_files`: a sitemap file could not be read whole this time. when its download broke off, the links received before the break are returned, and the file is in `unread_sitemaps`. often temporary, so asking again later can return more.
315
+ - `time`, `file_budget`, `file_size`: the site is big or slow, and a retry will not help. with `file_size`, a file of pages that turns out too large while it is read gives the links in its first part. a file that says up front that it is over the size limit, or any other file that turns out too large (such as a sitemap index), gives nothing and is in `unread_sitemaps`.
316
+
317
+ #### map a very large site in several calls
318
+
319
+ a very large or deep site is mapped in several calls: list its sitemap files with `depth: 0` and `entries: "sitemaps"`, then read each one with `sitemap_url`. `truncation.unread_sitemaps` names the files a call did not read whole, to read next. the full walk-through is in [map a very large or deep site in several calls](https://crawlbrulee.com/docs/map/sitemaps#map-a-very-large-or-deep-site-in-several-calls).
320
+
321
+ ```jsonc
322
+ // 1. list the site's top sitemap files
323
+ { "url": "https://example.com", "depth": 0, "entries": "sitemaps" }
324
+ // 2. read one of them
325
+ { "url": "https://example.com", "sitemap_url": "https://example.com/sitemap-products-1.xml.gz" }
326
+ ```
327
+
328
+ `modified_since` leaves out every entry with no `lastmod`, and a map with it is always fresh, so `cache.max_age` does nothing. see [find what changed since a date](https://crawlbrulee.com/docs/map/sitemaps#find-what-changed-since-a-date).
329
+
330
+ if the site answers `429` on the file in `sitemap_url`, on its robots.txt or on one of its top sitemap files, the tool returns `too_many_requests` (not billed): wait and try again.
331
+
332
+ #### old names
333
+
334
+ `max_urls` is the old name of `max_results`, and `total_before_max_urls` of `total_before_max_results`. both still work and mean the same. the api drops them on 2027-02-01. this tool still takes `max_urls` and sends it as `max_results`; when you give both, only `max_results` is used.
251
335
 
252
336
  see the [map endpoint](https://crawlbrulee.com/docs/map) for discovery rules and pagination semantics.
253
337
 
@@ -290,6 +374,8 @@ agents can branch on the `errorName` code. the set comes from the sdk's `ApiErro
290
374
  | `zero_data_retention_not_enabled` | `zero_data_retention` is not enabled for your organization (HTTP 403). not billed. |
291
375
  | `scrape_error` | the scrape could not be completed. a page the site served, even a 404, is never this error. |
292
376
  | `unsupported_screenshot_output` | screenshot-only request on a content type that can't be screenshotted (HTTP 422). not billed. |
377
+ | `unsupported_pdf_output` | pdf-only request on a content type that can't be made into a pdf (HTTP 422). not billed. |
378
+ | `job_failed` | the async job ended `failed`, so it has no result (`scrape_result`, HTTP 400). |
293
379
  | `not_found` | async job ID unknown, or submitted more than 24 hours ago (`scrape_status` / `scrape_result`). |
294
380
  | `request_timeout` | network / read timeout. safe to retry. |
295
381
  | `client_closed_request` | caller cancelled before completion. |
package/dist/index.js CHANGED
@@ -121,9 +121,8 @@ function getScrapeScreenshotBeforeActionTotals(actions) {
121
121
  //#endregion
122
122
  //#region src/schemas/ScrapeCleanupSchemas.ts
123
123
  /**
124
- * Mirrors `packages/core/src/model/common/ScrapeCleanup*` in the server repo.
125
- * Kept in step by hand — this package deliberately does not import from the
126
- * monorepo. If the server's shape changes, change it here too.
124
+ * Mirrors the crawlbrulee api's own schema, kept in step by hand: when the
125
+ * api's shape changes, change it here too.
127
126
  */
128
127
  const DEFAULT_SCRAPE_CLEANUP = { ads_and_popups: true };
129
128
  const MAX_SCRAPE_EXCLUDE_SELECTORS = 100;
@@ -133,12 +132,26 @@ const Schema_ApiScrapeCleanup = z.object({
133
132
  exclude_selectors: z.array(z.string().max(500)).max(100).optional().describe("CSS selectors whose elements are removed before anything is captured. Affects the extracted content and the screenshot, never raw_html. Use it for a banner or widget that ads_and_popups does not recognise. Sending any selector here makes the request skip the cache.")
134
133
  }).strict().describe("What is removed from the page before any output is built. Applies to markdown, cleaned_html, links and images on every engine, and to the screenshot. Never applies to raw_html, which is always the page before we removed anything.");
135
134
 
135
+ //#endregion
136
+ //#region src/schemas/ScrapeCustomHeadersSchemas.ts
137
+ const MAX_SCRAPE_COOKIES = 20;
138
+ const MAX_SCRAPE_COOKIE_BYTES = 4096;
139
+ const MAX_SCRAPE_CUSTOM_HEADERS_AND_COOKIES_BYTES = 16384;
140
+ const HEADERS_AND_COOKIES_DOCS_URL = "https://crawlbrulee.com/docs/scrape/custom-headers-and-cookies";
141
+ const HEADERS_AND_COOKIES_CHAT_NOTE = "Header and cookie values pass through the chat with the AI, so the AI host may keep them in its history. Use short-lived tokens or a test account, and never a password you can't change.";
142
+ const HEADERS_AND_COOKIES_TOOL_TEXT = `To send your own headers or cookies to the site, set \`headers\` (for example \`Authorization\`, or a fixed \`User-Agent\`) or \`cookies\`. They go only to the site in \`url\`, and such a request never uses the cache. ${HEADERS_AND_COOKIES_CHAT_NOTE} Tell the user this before they share one. See ${HEADERS_AND_COOKIES_DOCS_URL}.`;
143
+ const Schema_ScrapeCustomHeaders = z.record(z.string(), z.string());
144
+ const Schema_ScrapeCookie = z.object({
145
+ name: z.string().min(1),
146
+ value: z.string()
147
+ }).strict();
148
+ const Schema_ScrapeCookies = z.array(Schema_ScrapeCookie).max(20);
149
+
136
150
  //#endregion
137
151
  //#region src/schemas/ScrapeElementsSchemas.ts
138
152
  /**
139
- * Mirrors `packages/core/src/model/common/ScrapeElements*` in the server repo.
140
- * Kept in step by hand — this package deliberately does not import from the
141
- * monorepo. If the server's shape changes, change it here too.
153
+ * Mirrors the crawlbrulee api's own schema, kept in step by hand: when the
154
+ * api's shape changes, change it here too.
142
155
  *
143
156
  * `extract.elements`: named values read from the page by CSS selector. `fields`
144
157
  * nests, at most ELEMENT_FIELDS_DEPTH deep. The schemas are built level by level
@@ -148,7 +161,7 @@ const Schema_ApiScrapeCleanup = z.object({
148
161
  * Only the public per-string limits are checked here. The total selector count, the
149
162
  * CSS syntax and the name length are left to the api, which answers a clear 400.
150
163
  */
151
- const ELEMENTS_DOCS_URL = "https://crawlbrulee.com/docs/scrape/elements";
164
+ const ELEMENTS_DOCS_URL = "https://crawlbrulee.com/docs/scrape/targeted-extraction";
152
165
  /** How deep `fields` may nest. The innermost level has no `fields`. */
153
166
  const ELEMENT_FIELDS_DEPTH = 3;
154
167
  const MAX_ELEMENT_SELECTOR_LENGTH = 500;
@@ -194,7 +207,7 @@ function buildElementsMap(fieldsDepth, top = false) {
194
207
  output: describeTop(z.enum(ELEMENT_OUTPUT_VALUES).optional(), top, "What to return for a match: `text` (default), `html` (the outer HTML) or `attribute`"),
195
208
  attribute: describeTop(z.string().min(1).max(100).optional(), top, "The attribute to read when `output` is `attribute`. `href` and `src` come back as full urls"),
196
209
  all: describeTop(z.boolean().default(false), top, "Return every match as a list instead of the first. Defaults to false"),
197
- ...fieldsDepth > 0 ? { fields: describeTop(buildElementsMap(fieldsDepth - 1).optional(), top, "Used instead of `output`: turns each match into an object of named values, each read inside that match only. Same shape as `elements`; nests up to 3 levels") } : {}
210
+ ...fieldsDepth > 0 ? { fields: describeTop(buildElementsMap(fieldsDepth - 1).optional(), top, "Used instead of `output`: turns each match into an object of named values, each read inside that match; the selector `:scope` reads the match itself. Same shape as `elements`; nests up to 3 levels") } : {}
198
211
  }).strict().superRefine(refineSpec);
199
212
  return z.record(z.string(), z.union([Schema_ElementSelector, spec]));
200
213
  }
@@ -210,10 +223,32 @@ const Schema_ScrapeElements = buildElementsMap(3, true);
210
223
  */
211
224
  const Schema_ScrapeElementValues = z.record(z.string(), z.unknown());
212
225
 
226
+ //#endregion
227
+ //#region src/schemas/ScrapePdfSchemas.ts
228
+ const SCRAPE_PDF_LAYOUT_VALUES = ["pages", "single_page"];
229
+ const SCRAPE_PDF_PAPER_VALUES = ["a4", "letter"];
230
+ const SCRAPE_PDF_MEDIA_VALUES = ["screen", "print"];
231
+ /** The tallest `single_page` PDF page, in css pixels. A taller page goes on over more pages. */
232
+ const MAX_SCRAPE_PDF_SINGLE_PAGE_HEIGHT_PX = 15e3;
233
+ const Schema_ApiScrapePdf = z.object({
234
+ layout: z.enum(SCRAPE_PDF_LAYOUT_VALUES).default("pages").describe(`\`pages\` (default): the page on sheets of paper, laid out as in the browser window (the desktop default, or the screenshot device and viewport when the request also asks for a screenshot) and shrunk to fit the paper width. \`single_page\`: one page as wide as the browser window and as tall as the web page, up to ${MAX_SCRAPE_PDF_SINGLE_PAGE_HEIGHT_PX.toLocaleString("en-US")} px; a taller page goes on over more pages, with the \`pdf_single_page_overflow\` warning.`),
235
+ paper: z.enum(SCRAPE_PDF_PAPER_VALUES).optional().describe("Paper size for `layout: \"pages\"`: `a4` (default) or `letter`. Not allowed with `single_page`."),
236
+ landscape: z.boolean().optional().describe("Turn the paper sideways, for `layout: \"pages\"`. Defaults to false. Not allowed with `single_page`."),
237
+ media: z.enum(SCRAPE_PDF_MEDIA_VALUES).default("screen").describe("`screen` (default): the page as it looks on screen. `print`: the site's own print style, which on many sites hides menus and images; a site without one looks as on screen.")
238
+ }).strict().superRefine((pdf, ctx) => {
239
+ if (pdf.layout !== "single_page") return;
240
+ for (const field of ["paper", "landscape"]) if (pdf[field] !== void 0) ctx.addIssue({
241
+ code: "custom",
242
+ path: [field],
243
+ message: `${field} is only allowed with layout "pages"; leave it out for "single_page".`
244
+ });
245
+ });
246
+
213
247
  //#endregion
214
248
  //#region src/schemas/ScrapeScreenshotSchemas.ts
215
249
  const Schema_ApiScrapeScreenshotType = z.enum(["viewport", "full_page"]).describe("Screenshot mode: viewport (visible area) or full_page (entire page)");
216
250
  const Schema_ScrapeScreenshotDeviceMode = z.enum(["desktop", "mobile"]).describe("Device mode to emulate for viewport sizing");
251
+ const Schema_ScrapeScreenshotColorScheme = z.enum(["light", "dark"]).describe("Color scheme to ask the site for: light or dark");
217
252
  const Schema_ScrapeScreenshotBeforeAction = z.discriminatedUnion("type", [z.object({
218
253
  type: z.literal("wait").describe("Wait for a duration before capturing"),
219
254
  ms: z.number().int().nonnegative().describe("Milliseconds to wait")
@@ -257,33 +292,37 @@ const Schema_ApiScrapeFormatScreenshot = z.object({
257
292
  type: Schema_ApiScrapeScreenshotType.describe("Screenshot capture mode"),
258
293
  viewport: Schema_ApiScrapeViewport.optional().describe("Custom viewport dimensions; uses device_mode defaults if omitted"),
259
294
  device_mode: Schema_ScrapeScreenshotDeviceMode.default(DEFAULT_SCRAPE_SCREENSHOT_DEVICE_MODE).describe("Emulate desktop or mobile device viewport"),
295
+ color_scheme: Schema_ScrapeScreenshotColorScheme.optional().describe("`light` (default) or `dark`. `dark` asks the site for its dark theme, if it has one, and the screenshot shows it. A site without a dark theme, or whose dark theme is only a switch on the page, looks the same as with `light`. When the request also asks for `extract.pdf`, the PDF shows the dark theme too. No extra credits."),
260
296
  actions_before: z.array(Schema_ScrapeScreenshotBeforeAction).max(5).default([]).describe("Actions to perform before taking the screenshot (wait, scroll)"),
261
297
  actions_after: z.array(Schema_ScrapeScreenshotAfterAction).max(1).default([]).describe("Actions to perform after taking the screenshot (e.g. slice into tiles)")
262
298
  }).strict().superRefine(refineScrapeScreenshotActionsBefore).describe("Screenshot capture configuration");
263
299
  const Schema_ApiScrapeCache = z.object({ max_age: z.union([z.number().int().nonnegative(), z.iso.datetime()]).default(DEFAULT_API_SCRAPE_CACHE_MAX_AGE_SECONDS).describe("Maximum cache age in seconds, or an ISO 8601 datetime cutoff") }).strict().describe("Cache settings for the scrape request");
264
300
  const Schema_ApiScrapeExtract = z.object({
265
301
  metadata: z.boolean().default(true).describe("Extract page metadata (title, description, OG tags, etc.) from the page head"),
266
- cleaned_html: z.boolean().default(true).describe("Extract cleaned HTML: the page body with scripts, styles, ads and cookie banners removed"),
267
- markdown: z.boolean().default(false).describe("Extract page content as clean Markdown"),
302
+ cleaned_html: z.boolean().default(false).describe("Extract cleaned HTML: the page body with scripts, styles, ads and cookie banners removed"),
303
+ markdown: z.boolean().default(true).describe("Extract page content as clean Markdown"),
268
304
  raw_html: z.boolean().default(false).describe("Return the raw, unprocessed HTML, up to 10,000,000 characters of page body. A larger body is truncated at a tag boundary and the response carries a `raw_html_truncated` warning."),
269
305
  links: z.boolean().default(false).describe("Extract links found on the page, up to 30,000 per page. Beyond that the array is truncated and the response carries a `links_truncated` warning."),
270
306
  images: z.boolean().default(false).describe("Extract inline images found on the page, up to 10,000 per page. Beyond that the array is truncated and the response carries an `inline_images_truncated` warning."),
271
307
  screenshot: Schema_ApiScrapeFormatScreenshot.optional().describe("Capture a screenshot of the page"),
272
- elements: Schema_ScrapeElements.optional().describe(`Named values to read from the page by CSS selector, returned in the top-level \`elements\` field under the same names. Each value is either a selector string (the text of the first match) or an object with \`selector\`, \`output\`, \`attribute\` and \`all\`. \`fields\` (instead of \`output\`) turns each match into an object of named values read inside that match only, so a list of product cards can return a title, price and url per card. A name with no match is null, or [] with \`all: true\`. Read after cleanup; \`<script>\` and \`<style>\` tags are not part of it. An invalid selector is a 400. No extra credits, also when the page comes from cache. Limits and selector rules: ${ELEMENTS_DOCS_URL}.`)
308
+ pdf: Schema_ApiScrapePdf.optional().describe("Save the page as a PDF: a real document with selectable text and working links, backgrounds printed, and no header or footer added. `{}` takes every default. The request runs in a browser. The response carries a top-level `pdf` with a signed link that expires 24 hours after the scrape. It costs what a screenshot costs, and a PDF and a screenshot in one request are billed once. A cached copy of the page answers only when it has a PDF made with the same settings; `cache.max_age: 0` always makes a new one. In rare cases the PDF cannot be made: the rest of the scrape still comes back, with the `pdf_unavailable` warning, and the request costs what it costs without the PDF. A PDF-only request (every other format off, `markdown` and `metadata` included) on a page that cannot be made into a PDF is a 422 `unsupported_pdf_output`, not billed. An async job in that case, or one that asked only for a PDF and got none, ends `failed` and is not billed. A PDF on its own is made with the light theme. When the same request also asks for a screenshot with `color_scheme: \"dark\"`, the PDF is dark too."),
309
+ elements: Schema_ScrapeElements.optional().describe(`Named values to read from the page by CSS selector, returned in the top-level \`elements\` field under the same names. Each value is either a selector string (the text of the first match) or an object with \`selector\`, \`output\`, \`attribute\` and \`all\`. \`fields\` (instead of \`output\`) turns each match into an object of named values read inside that match (the selector \`:scope\` reads the match itself, for example the matched element's own href), so a list of products can return a title, price and url per product. A name with no match is null, or [] with \`all: true\`. Read after cleanup; \`<script>\` and \`<style>\` tags are not part of it. An invalid selector is a 400. No extra credits, also when the page comes from cache. Limits and selector rules: ${ELEMENTS_DOCS_URL}.`)
273
310
  }).strict().describe("Which content formats to extract from the scraped page");
274
311
  const Schema_ApiScrapeLocation = z.object({
275
- locale: z.string().min(2).max(35).optional().describe("BCP-47 locale (2-35 chars, e.g. 'en-US', 'de-DE', 'pt-BR') driving Accept-Language and navigator.language"),
312
+ locale: z.string().min(2).max(35).optional().describe("BCP-47 locale (2-35 chars, e.g. 'en-US', 'de-DE', 'pt-BR'): the language to ask the site for"),
276
313
  country: z.string().regex(/^([a-zA-Z]{2}|europe)$/i, "country must be a 2-letter ISO 3166-1 alpha-2 code, 'eu', or 'europe'").optional().describe("ISO 3166-1 alpha-2 (e.g. 'us', 'de', 'br'; case-insensitive) driving the emulated browser timezone and proxy exit country. Also accepts 'eu' (random EU member state) or 'europe' (random European state incl. UK and non-EU).")
277
314
  }).strict().describe("Optional locale + country emulation for the scrape");
278
315
  const Schema_ApiScrapeRequest = z.object({
279
316
  url: z.string().describe("The URL to scrape. Known tracking parameters are removed before the page is fetched, so they are neither sent to the target site nor part of the cache key. Every other query parameter is kept verbatim and is part of the cache key."),
280
- extract: Schema_ApiScrapeExtract.prefault({}).describe("Which content formats to extract. Defaults to metadata + cleaned_html."),
317
+ extract: Schema_ApiScrapeExtract.prefault({}).describe("Which content formats to extract. Defaults to markdown + metadata."),
281
318
  cache: Schema_ApiScrapeCache.optional().describe("Cache settings for this request"),
282
319
  require_js: z.boolean().default(false).describe("Use a headless browser to render JavaScript before scraping"),
283
320
  cleanup: Schema_ApiScrapeCleanup.prefault({ ...DEFAULT_SCRAPE_CLEANUP }),
284
321
  proxy: Schema_ApiProxyType.describe("Proxy tier to use for fetching"),
285
322
  location: Schema_ApiScrapeLocation.optional(),
286
- zero_data_retention: z.boolean().optional().describe("Keeps the result out of the shared cache; anything stored to deliver it is kept for 24 hours, then deleted. Adds 1 credit. Must be enabled for your organization. See https://crawlbrulee.com/docs/zero-data-retention.")
323
+ zero_data_retention: z.boolean().optional().describe("Keeps the result out of the shared cache; anything stored to deliver it is kept for 24 hours, then deleted. Adds 1 credit. Must be enabled for your organization. See https://crawlbrulee.com/docs/zero-data-retention."),
324
+ headers: Schema_ScrapeCustomHeaders.optional().describe(`Your own HTTP headers to send to the site with the request, for example \`Authorization\`, an api key, or a fixed \`User-Agent\` that the site has on an allowlist. Sent only to the origin of \`url\` (same scheme, host and port), or to its https version when \`url\` is http, and not on a redirect to another origin. Up to ${10} headers; headers and cookies together up to ${MAX_SCRAPE_CUSTOM_HEADERS_AND_COOKIES_BYTES} bytes. Values are printable ASCII, with no space or tab at either end. Headers a browser doesn't let a web page set can't be set here either (a 400 names the header). Use \`cookies\` for cookies and \`location.locale\` for the language. Never put secrets in the \`User-Agent\`. Your own \`User-Agent\` can lower the success rate, and the response carries the \`custom_user_agent\` warning. A \`Referer\` must be the full http or https url of a public page, with no username or password; it is sent the way a browser sends it after a click on that page. A request with headers or cookies never reads from or writes to the cache. On a plain http url they travel unencrypted. ${HEADERS_AND_COOKIES_CHAT_NOTE} See ${HEADERS_AND_COOKIES_DOCS_URL}.`),
325
+ cookies: Schema_ScrapeCookies.optional().describe(`Your own cookies to send to the site with the request. Each is a \`name\` and a \`value\`, sent only to the host of \`url\`. Cookies the site sets while redirecting are not kept. Up to ${20} cookies, each up to ${MAX_SCRAPE_COOKIE_BYTES} bytes (name and value), counted toward the limit on \`headers\`. A value may not hold ";" or start or end with a space. A \`__Secure-\`, \`__Host-\` or \`__Http-\` cookie needs an https url. A request with headers or cookies never reads from or writes to the cache. ${HEADERS_AND_COOKIES_CHAT_NOTE} See ${HEADERS_AND_COOKIES_DOCS_URL}.`)
287
326
  }).strict();
288
327
 
289
328
  //#endregion
@@ -291,13 +330,11 @@ const Schema_ApiScrapeRequest = z.object({
291
330
  const Schema_ApiMapLocation = z.object({ country: z.string().regex(/^([a-zA-Z]{2}|europe)$/i, "country must be a 2-letter ISO 3166-1 alpha-2 code, 'eu', or 'europe'").optional().describe("ISO 3166-1 alpha-2 (e.g. 'us', 'de', 'br'; case-insensitive) hint for proxy egress country. Also accepts 'eu' (random EU member state) or 'europe' (random European state incl. UK and non-EU).") }).strict().describe("Optional country emulation for the map");
292
331
  const DEFAULT_API_MAP_CACHE_MAX_AGE_SECONDS = 604800;
293
332
  /**
294
- * How many URLs a /map call discovers and stores when the caller names no
295
- * limit. Sitemap discovery stops here, so the default is real crawl work, not
296
- * a slice taken at the end — 5000 covers the whole site for the great majority
297
- * of roots while keeping an unparameterised call cheap and fast.
333
+ * How many entries a /map call finds when the caller names no limit. Discovery
334
+ * stops here, so the default is real work, not a slice taken at the end.
298
335
  */
299
- const DEFAULT_API_MAP_MAX_URLS = 5e3;
300
- const MAX_API_MAP_MAX_URLS = 1e5;
336
+ const DEFAULT_API_MAP_MAX_RESULTS = 5e3;
337
+ const MAX_API_MAP_MAX_RESULTS = 1e5;
301
338
  const DEFAULT_API_MAP_PAGE_LIMIT = 5e3;
302
339
  const MAX_API_MAP_PAGE_LIMIT = 1e4;
303
340
  const Schema_ApiMapTypes = z.object({
@@ -306,13 +343,24 @@ const Schema_ApiMapTypes = z.object({
306
343
  external: z.boolean().default(true).describe("Include external links (different domains)")
307
344
  }).describe("Filter which link types to include in the map");
308
345
  const Schema_ApiMapCache = z.object({ max_age: z.union([z.number().int().nonnegative(), z.iso.datetime()]).default(DEFAULT_API_MAP_CACHE_MAX_AGE_SECONDS).describe("Maximum cache age in seconds, or an ISO 8601 datetime cutoff") }).describe("Cache settings for the map request");
346
+ const DEFAULT_API_MAP_DEPTH = 3;
347
+ const API_MAP_ENTRIES_VALUES = [
348
+ "pages",
349
+ "sitemaps",
350
+ "all"
351
+ ];
309
352
  const Schema_ApiMapRequest = z.object({
310
353
  url: z.string().describe("The website URL to map. Mapping always targets the site root, so the path, query string and fragment are dropped; known tracking parameters are removed before the request is processed."),
311
354
  proxy: Schema_ApiProxyType.default("auto").describe("Proxy tier to use for fetching"),
312
- sitemap_only: z.boolean().default(false).describe("Only use sitemap.xml — skip homepage link extraction"),
355
+ sitemap_only: z.boolean().default(false).describe("Use the sitemaps only: leave out the links found on the home page. A map with `modified_since` or `sitemap_url` never adds home page links."),
313
356
  types: Schema_ApiMapTypes.optional().describe("Filter which link types to include"),
314
357
  cache: Schema_ApiMapCache.optional().describe("Cache settings for this request"),
315
- max_urls: z.number().int().positive().max(MAX_API_MAP_MAX_URLS).default(DEFAULT_API_MAP_MAX_URLS).describe("Maximum number of URLs to discover and store in the map. Default 5000, maximum 100000. Sitemap discovery stops as soon as this many URLs have been found, so a smaller value is a faster and lighter crawl, not just a smaller answer."),
358
+ max_results: z.number().int().positive().max(MAX_API_MAP_MAX_RESULTS).optional().describe(`The most entries the map finds, counting only the kind asked for in \`entries\`. Default ${DEFAULT_API_MAP_MAX_RESULTS}, maximum ${MAX_API_MAP_MAX_RESULTS}. Discovery stops as soon as this many have been found, so a smaller value is a faster and lighter map, not just a smaller answer.`),
359
+ max_urls: z.number().int().positive().max(MAX_API_MAP_MAX_RESULTS).optional().describe("Deprecated: use `max_results`, which means the same. This tool sends it as `max_results`. When both are given, only `max_results` is used."),
360
+ sitemap_url: z.string().optional().describe("Start from this sitemap file, as a full http or https address. It must be on the same site as `url`, or on a host the site's robots.txt names, such as a CDN. Left out: start from the site's own top sitemap files."),
361
+ depth: z.number().int().nonnegative().optional().describe(`How many levels of nested sitemaps to follow: 0 to 3, default ${3}. With \`sitemap_url\`, level 0 is that file, and it is read. Without it, level 0 is the list of the site's top sitemap files, which 0 returns without reading them: \`depth: 0\` with \`entries: "sitemaps"\` lists them. A sitemap index holds only sitemap files, so reading one at a low depth with \`entries: "pages"\` returns no pages: ask with \`entries: "sitemaps"\` or a higher depth. A site with a deeper tree is mapped in several calls, one per file.`),
362
+ entries: z.enum(API_MAP_ENTRIES_VALUES).optional().describe("What to return: `pages` (page addresses, the default), `sitemaps` (sitemap files) or `all` (both)."),
363
+ modified_since: z.union([z.iso.date(), z.iso.datetime({ offset: true })]).optional().describe("Return only entries whose `lastmod` is at or after this date (`2026-11-01`, the start of that day in UTC) or date and time (ISO 8601, with a time zone). An entry with no `lastmod` is left out, so every entry returned matches; links found on the home page have none, so none is returned. A nested sitemap whose own `lastmod` is older is not read, so a site that does not update the dates in its sitemap index can hide changed pages. A request with this field is always mapped fresh: it never reads from or adds to the cache, so `cache.max_age` does nothing, and it is priced as a fresh map."),
316
364
  page: z.number().int().positive().default(1).describe("Page number for paginated results"),
317
365
  limit: z.number().int().positive().max(MAX_API_MAP_PAGE_LIMIT).default(DEFAULT_API_MAP_PAGE_LIMIT).describe("Number of URLs to return per page. Default 5000, maximum 10000."),
318
366
  location: Schema_ApiMapLocation.optional(),
@@ -358,6 +406,10 @@ const Schema_ApiScreenshotResponse = z.looseObject({
358
406
  properties: Schema_ApiScreenshotProperties.describe("Image properties for the full screenshot"),
359
407
  slices: z.array(Schema_ApiScreenshotSlice).optional().describe("Individual tile slices (present when slice action_after was requested)")
360
408
  });
409
+ const Schema_ApiPdfResponse = z.looseObject({
410
+ url: z.string().describe("Signed link to download the PDF. It expires 24 hours after the scrape (for an async scrape, 24 hours after you submitted it; fetching the result again does not extend it). Download the file, do not keep the link"),
411
+ bytes: z.number().int().describe("Size of the PDF file in bytes")
412
+ });
361
413
  const Schema_ApiPageInlineImgItem = z.looseObject({
362
414
  url: z.string().describe("Absolute URL of the image"),
363
415
  alt: z.string().nullable().describe("Alt text of the image, or null if not set")
@@ -423,8 +475,9 @@ const Schema_ApiScrapeSuccessResponse = z.looseObject({
423
475
  images: z.array(Schema_ApiPageInlineImgItem).optional().describe("Inline images found on the page"),
424
476
  links: z.array(Schema_ApiPageLink).optional().describe("Links found on the page"),
425
477
  screenshot: Schema_ApiScreenshotResponse.optional().describe("Screenshot of the page, if requested"),
478
+ pdf: Schema_ApiPdfResponse.optional().describe("PDF of the page, if requested with `extract.pdf` and it could be made"),
426
479
  metadata: Schema_ApiScrapeMeta.optional().describe("Extracted page metadata (title, OG tags, etc.)"),
427
- warnings: z.array(z.string()).optional().describe("Non-error notices about the scrape. Truncation codes — `screenshot_truncated` (long page exceeded the scrolling-screenshot height cap), `links_truncated` / `inline_images_truncated` (page had more links/images than the per-page extraction caps), `raw_html_truncated` (rendered HTML exceeded the per-page size budget) — mean the field is present but capped. `elements_truncated` means at least one `elements` value hit a limit: a list was cut at 1,000 matches, the request reached 10,000 matches in total, or a value did not fit the ~1 MB of values allowed per request (that value is then null, never cut short). Unavailability codes — `links_unavailable` / `inline_images_unavailable` / `metadata_unavailable` — mean that optional field could not be extracted and was omitted (null/empty) while the rest of the scrape succeeded, so an empty field carrying one of these does NOT mean the page had none. `screenshot_unavailable` means a screenshot was asked for, but the page came back from the http engine without one. Stable string codes — clients can switch on them. Warnings are stored with the result: async result fetches and cache hits carry them too, filtered to the fields the request asked for. `metadata_truncated` is retired and no longer sent: metadata has no size limit of its own now, though the code can still appear on results stored before that change."),
480
+ warnings: z.array(z.string()).optional().describe("Non-error notices about the scrape. Truncation codes — `screenshot_truncated` (long page exceeded the scrolling-screenshot height cap), `links_truncated` / `inline_images_truncated` (page had more links/images than the per-page extraction caps), `raw_html_truncated` (rendered HTML exceeded the per-page size budget) — mean the field is present but capped. `elements_truncated` means at least one `elements` value hit a limit: a list was cut at 1,000 matches, the request reached 10,000 matches in total, or a value did not fit the ~1 MB of values allowed per request (that value is then null, never cut short). Unavailability codes — `links_unavailable` / `inline_images_unavailable` / `metadata_unavailable` — mean that optional field could not be extracted and was omitted (null/empty) while the rest of the scrape succeeded, so an empty field carrying one of these does NOT mean the page had none. `screenshot_unavailable` means a screenshot was asked for, but the page came back from the http engine without one. `pdf_unavailable` means a PDF was asked for, but the page came back without one: it came back from the http engine, the site answered an empty error page, the PDF was over 50 MB, or it did not finish in time. `pdf_single_page_overflow` means a `single_page` PDF was taller than the 15,000 px page limit and goes on over more pages. `custom_user_agent` means the request set its own `User-Agent` header; this can lower the success rate. Stable string codes — clients can switch on them. Warnings are stored with the result: async result fetches and cache hits carry them too, filtered to the fields the request asked for. `metadata_truncated` is retired and no longer sent: metadata has no size limit of its own now, though the code can still appear on results stored before that change."),
428
481
  response_meta: Schema_ApiResponseMeta.describe("Request-level metadata. `response_meta.usage` reports what the request cost (total_credit_cost and its parts), the billed engine and the resolved proxy tier.")
429
482
  });
430
483
 
@@ -433,7 +486,7 @@ const Schema_ApiScrapeSuccessResponse = z.looseObject({
433
486
  const API_RESOLVED_PROXY_TIER_VALUES = ["basic", "advanced"];
434
487
  /** Which limit stopped sitemap discovery first. The FIRST limit to fire wins. */
435
488
  const DISCOVERY_CAP_REASONS = [
436
- "max_urls",
489
+ "max_results",
437
490
  "time",
438
491
  "file_budget",
439
492
  "depth",
@@ -449,22 +502,29 @@ const Schema_ApiMapUsageMeta = z.looseObject({
449
502
  engine: openEnum(["http", "cache"]).describe("The map billing engine: `http` for fresh discovery or `cache` for a cached result"),
450
503
  proxy: openEnum(API_RESOLVED_PROXY_TIER_VALUES).describe("The proxy tier the request actually ran on (resolved value — never `auto`)")
451
504
  });
452
- const Schema_ApiMapLinkItem = z.looseObject({ url: z.string().describe("The discovered URL") });
505
+ const API_MAP_LINK_TYPE_VALUES = ["page", "sitemap"];
506
+ const Schema_ApiMapLinkItem = z.looseObject({
507
+ url: z.string().describe("The discovered URL"),
508
+ type: openEnum(API_MAP_LINK_TYPE_VALUES).optional().describe("`page` for a page address, `sitemap` for a sitemap file, which you can read with `sitemap_url` in another call (a file on another site only when the site's robots.txt names its host). A link found on the home page is a `page`."),
509
+ lastmod: z.string().nullable().optional().describe("The entry's `lastmod` from the sitemap, as an ISO 8601 date and time in UTC, or null when the sitemap gives none or it cannot be read. Always null for a link found on the home page.")
510
+ });
453
511
  const Schema_ApiMapPagination = z.looseObject({
454
512
  page: z.number().int().positive().describe("Current page number"),
455
513
  limit: z.number().int().positive().describe("Number of items per page"),
456
- total: z.number().int().nonnegative().describe("Total number of URLs in the map"),
514
+ total: z.number().int().nonnegative().describe("How many links this answer holds across all its pages, after `entries`, `types` and `max_results` are applied"),
457
515
  total_pages: z.number().int().nonnegative().describe("Total number of pages available"),
458
516
  has_more: z.boolean().describe("Whether more pages are available")
459
517
  });
460
518
  const Schema_ApiMapTruncation = z.looseObject({
461
- storage_capped: z.boolean().describe("Whether the stored map hit the 100000-URL storage cap."),
462
- response_capped: z.boolean().describe("Whether more links were eligible than max_urls, so the list was trimmed. Discovery itself stops at max_urls, so this is normally true only when home-page links pushed the total past it. See discovery_cap_reason for a discovery stop."),
463
- total_before_max_urls: z.number().int().nonnegative().describe("Total URLs found before applying the max_urls cap"),
464
- total_detected_before_storage_cap: z.number().int().nonnegative().describe("Total URLs detected during discovery before the storage cap was applied"),
519
+ storage_capped: z.boolean().describe("Whether the map found more than 100,000 URLs, the most one map holds, so some were left out."),
520
+ response_capped: z.boolean().describe("Whether more links were eligible than max_results, so the list was trimmed. Discovery itself stops at max_results, so this is normally true only when home-page links pushed the total past it. See discovery_cap_reason for a discovery stop."),
521
+ total_before_max_results: z.number().int().nonnegative().optional().describe("Total links found before applying max_results. Older api versions do not send it."),
522
+ total_before_max_urls: z.number().int().nonnegative().optional().describe("Deprecated: use total_before_max_results, which always has the same value. The api stops sending it on 2027-02-01."),
523
+ total_detected_before_storage_cap: z.number().int().nonnegative().describe("Total URLs found, before the 100,000-URL limit of one map"),
465
524
  discovery_capped: z.boolean().describe("Whether sitemap discovery stopped before it had read every sitemap file it found. When true, the site has more pages than this map lists."),
466
525
  sitemaps_skipped: z.number().int().nonnegative().describe("How many sitemap files were skipped or only partly read during discovery, because a file was too large, could not be fetched, or the discovery limits were reached."),
467
- discovery_cap_reason: openEnum(DISCOVERY_CAP_REASONS).nullable().describe("Which limit stopped sitemap discovery first, or null when nothing stopped it. \"max_urls\" means your own max_urls was reached — ask again with a higher one to get more. \"time\" means discovery ran out of its time budget, \"file_budget\" that the site has more sitemap files than one request reads, \"depth\" that its sitemap indexes nest too deeply, and \"file_size\" that a sitemap file was too large to read. \"unread_files\" means a sitemap file the site publishes could not be read at all this time — the request for it failed or was rate limited, or the file was not a readable sitemap. Only \"max_urls\" is a limit you can raise from the request; \"unread_files\" is often temporary, so asking again later can return more.")
526
+ unread_sitemaps: z.array(z.string()).optional().describe("The sitemap files this call knew about but did not read whole, because a limit stopped it, the file could not be read, or its download broke off. Read each one with `sitemap_url` in another call, except a file that says it is over the size limit: no call reads that one. Files past `depth` are listed here. Up to 1000 addresses; empty when every file was read. When the list is full, ask the same with `entries: \"sitemaps\"` to get every sitemap file as a link. Older api versions do not send it."),
527
+ discovery_cap_reason: openEnum(DISCOVERY_CAP_REASONS).nullable().describe("Which limit stopped sitemap discovery first, or null when nothing stopped it. \"max_results\": your own max_results was reached; ask again with a higher one to get more. \"depth\": there are sitemap files past the `depth` you asked for, listed in unread_sitemaps; this is the answer to the depth you chose, not a fault (with `depth: 0` it is how a site's top sitemap files are listed). \"time\": discovery ran out of its time budget. \"file_budget\": the site has more sitemap files than one request reads. \"file_size\": a sitemap file was too large. A file that says up front that it is over the size limit is not downloaded: nothing comes back from it, and it is listed in unread_sitemaps. A file of pages that turns out too large while it is read returns the links in its first part. Any other file that turns out too large, such as a sitemap index, returns nothing and is listed. \"unread_files\": a sitemap file the site publishes could not be read whole this time (the request failed or was rate limited, the download broke off, or the file was not a readable sitemap). When a download broke off, the links received before the break are returned, and the file is listed in unread_sitemaps. Asking again later can return more.")
468
528
  });
469
529
  const Schema_ApiMapResult = z.looseObject({
470
530
  links: z.array(Schema_ApiMapLinkItem).describe("List of discovered URLs for the current page"),
@@ -478,20 +538,37 @@ const Schema_ApiMapResult = z.looseObject({
478
538
  //#endregion
479
539
  //#region src/tools/map.ts
480
540
  const DESCRIPTION$6 = [
481
- "Build (or fetch a cached) link-map for a website by combining sitemap discovery with homepage",
482
- "link extraction. Returns paginated lists of discovered URLs, each item just { url }.",
483
- "Filterable by link type (internal / external / subdomain). Use this to enumerate a site before",
484
- "scraping selected pages.",
485
- "`max_urls` (default 5000, max 100000) is a discovery budget, not a trim at the end: discovery",
486
- "stops as soon as that many URLs are found, so a smaller value is a faster, cheaper crawl.",
487
- "A map stopped that way returns exactly `max_urls` links with `response_capped` false — the",
488
- "signal that the site has more is `response_meta.truncation.discovery_cap_reason`. When that is",
489
- "\"max_urls\", ask again with a higher `max_urls` to get more; \"unread_files\" means a sitemap file",
490
- "could not be read this time and is often temporary, so asking again later can return more;",
491
- "\"time\", \"file_budget\", \"depth\" and \"file_size\" mean the site itself is big, slow or deep and a",
492
- "retry will not help. `discovery_capped` says discovery stopped early, `sitemaps_skipped` how",
493
- "many sitemap files were skipped or only partly read.",
541
+ "Build (or fetch a cached) link map of a website from its sitemaps, plus the links on its home",
542
+ "page. Returns paginated links, each { url, type, lastmod }: `type` is `page` or `sitemap`, and",
543
+ "`lastmod` is the date from the sitemap (UTC) or null. Filterable by link type (internal /",
544
+ "external / subdomain). Use this to enumerate a site before scraping selected pages.",
545
+ "By default the map reads the site's top sitemap files and 2 levels of nested ones (`depth` 3),",
546
+ "returns pages (`entries`) and finds up to 5000 of them (`max_results`, max 100000).",
547
+ "`max_results` is a discovery budget, not a trim at the end: discovery stops as soon as that many",
548
+ "entries of the asked kind are found, so a smaller value is a faster map. A map stopped that way",
549
+ "returns exactly `max_results` links with `response_capped` false; the signal that the site has",
550
+ "more is `response_meta.truncation.discovery_cap_reason`. \"max_results\": ask again with a higher",
551
+ "`max_results`. \"depth\": there are sitemap files past the `depth` you asked for, listed in",
552
+ "`unread_sitemaps`; that is the answer to your depth, not a fault. \"unread_files\": a sitemap file",
553
+ "could not be read whole this time, often temporary, so asking again later can return more. \"time\",",
554
+ "\"file_budget\" and \"file_size\": the site is big or slow, and a retry will not help.",
555
+ "`discovery_capped` says discovery stopped early, `sitemaps_skipped` how many sitemap files were",
556
+ "skipped or only partly read.",
494
557
  "`limit` (default 5000, max 10000) only pages the answer.",
558
+ "To map a very large site in several calls, list its top sitemap files with `depth: 0` and",
559
+ "`entries: \"sitemaps\"`, then read each one with `sitemap_url` (on the same site as `url`, or on a",
560
+ "host the site's robots.txt names, such as a CDN).",
561
+ "`truncation.unread_sitemaps` names the files a call did not read whole, to read next (except",
562
+ "a file that says it is over the size limit: no call reads that one); when that",
563
+ "list is full, ask the same with `entries: \"sitemaps\"` to get every sitemap file as a link, paged.",
564
+ "A sitemap index holds only sitemap files, so reading one at a low `depth` with",
565
+ "`entries: \"pages\"` returns no pages: ask with `entries: \"sitemaps\"` or a higher `depth`.",
566
+ "`modified_since` keeps only entries whose `lastmod` is at or after it: an entry with no",
567
+ "`lastmod` is left out (so no home page link is returned), and a nested sitemap with an older",
568
+ "`lastmod` is not read. A request with `modified_since` is always mapped fresh, never from the",
569
+ "cache, and priced as a fresh map. A map with `modified_since` or `sitemap_url` adds no home page",
570
+ "links. If the site answers 429 on the file in `sitemap_url`, on its robots.txt or on one of",
571
+ "its top sitemap files, the tool returns `too_many_requests` (not billed): wait and retry.",
495
572
  "Set `zero_data_retention: true` to keep the result out of the shared cache; anything stored to deliver it is kept for 24 hours, then deleted. It adds 1 credit and must be enabled for the organization (else a `zero_data_retention_not_enabled` error, not billed). See https://crawlbrulee.com/docs/zero-data-retention.",
496
573
  "Returned URLs are normalized the same way `scrape` normalizes its returned `url`, so",
497
574
  "map-then-scrape stays on one host. Results are ordered with the most useful links first.",
@@ -499,7 +576,9 @@ const DESCRIPTION$6 = [
499
576
  "`proxy_multiplier` + `zero_data_retention_credit_cost`, plus `engine` and `proxy` (the resolved tier, never `auto`). Map has no screenshot slicing and no",
500
577
  "`page_status_code`: it reads many files, not one page. A map that found nothing because the site",
501
578
  "answered only with statuses we don't bill (a 5xx, for example), or not at all, is empty and free. If the site cannot be reached, the",
502
- "tool can return a `target_unreachable` error (HTTP 502, not billed): retry later or check the URL."
579
+ "tool can return a `target_unreachable` error (HTTP 502, not billed): retry later or check the URL.",
580
+ "The full walk-through for a very large or deep site:",
581
+ "https://crawlbrulee.com/docs/map/sitemaps#map-a-very-large-or-deep-site-in-several-calls."
503
582
  ].join(" ");
504
583
  function registerMapTool(server, getClient) {
505
584
  server.registerTool("map", {
@@ -507,18 +586,33 @@ function registerMapTool(server, getClient) {
507
586
  description: DESCRIPTION$6,
508
587
  inputSchema: Schema_ApiMapRequest.shape,
509
588
  outputSchema: Schema_ApiMapResult
510
- }, (args) => runTool(async () => await getClient().map(args)));
589
+ }, (args) => runTool(async () => await getClient().map(toApiBody(args))));
590
+ }
591
+ /**
592
+ * `max_urls` is the old name of `max_results`. The tool sends it as `max_results`, so it
593
+ * keeps working after the api drops the old name. When both are given, `max_results` wins,
594
+ * as it does in the api.
595
+ */
596
+ function toApiBody(args) {
597
+ const { max_urls: maxUrls, ...body } = args;
598
+ if (maxUrls !== void 0 && body.max_results === void 0) return {
599
+ ...body,
600
+ max_results: maxUrls
601
+ };
602
+ return body;
511
603
  }
512
604
 
513
605
  //#endregion
514
606
  //#region src/tools/scrape.ts
515
607
  const DESCRIPTION$5 = [
516
608
  "Fetch a single URL via the crawlbrulee scraping API and return the requested content",
517
- "(markdown, cleaned HTML, raw HTML, links, images, screenshot, page metadata in `metadata`).",
609
+ "(markdown, cleaned HTML, raw HTML, links, images, screenshot, PDF, page metadata in `metadata`).",
518
610
  "Use this for one-shot page extraction. For full-site discovery use the `map` tool first.",
519
611
  "To pull named values such as prices, titles or links, set `extract.elements` (name → CSS selector)",
520
612
  "instead of reading the whole markdown: they come back in `elements`, for no extra credits.",
521
- "Rules: https://crawlbrulee.com/docs/scrape/elements.",
613
+ "Markdown and metadata stay on unless you set `markdown: false` and `metadata: false`, so send",
614
+ "both to get only the values.",
615
+ "Rules: https://crawlbrulee.com/docs/scrape/targeted-extraction.",
522
616
  "Check `page_status_code` before you trust the content: it is the HTTP status the site answered",
523
617
  "with for the final page. A page the site served is a successful result whatever its status, so a",
524
618
  "404 or 503 page comes back with its content, not as an error. A 404 means the markdown is the",
@@ -526,8 +620,12 @@ const DESCRIPTION$5 = [
526
620
  "407, 408, 429 and 451; 5xx pages are never billed.",
527
621
  "If the site cannot be reached at all the tool returns a `target_unreachable` error (HTTP 502,",
528
622
  "not billed): retry later or check the URL.",
529
- "Screenshot URLs in the response are signed download links that expire 24 hours after the scrape:",
530
- "download the image if you need it later; do not keep the link.",
623
+ "Set `extract.pdf: {}` to save the page as a PDF (pages or one long page, a4 or letter); it",
624
+ "costs what a screenshot costs, and both together are billed once. Set",
625
+ "`extract.screenshot.color_scheme: \"dark\"` for a screenshot of the site's dark theme, at no extra",
626
+ "cost; the PDF then shows it too.",
627
+ "Screenshot and PDF URLs in the response are signed download links that expire 24 hours after the",
628
+ "scrape: download the file if you need it later; do not keep the link.",
531
629
  "The response also carries `response_meta.usage`: `total_credit_cost` = `engine_credit_cost` ×",
532
630
  "`proxy_multiplier` + `screenshot_slicing_credit_cost` + `zero_data_retention_credit_cost`, plus `engine` and `proxy` (the resolved",
533
631
  "tier — never `auto`). `engine` is the billed engine (`http`, `browser`, `screenshot`, `cache`); a",
@@ -546,7 +644,11 @@ const DESCRIPTION$5 = [
546
644
  "while the rest of the scrape succeeded, so do NOT conclude the page had no links/images/metadata",
547
645
  "— re-run the scrape instead. An empty field with no such warning does mean the page had none.",
548
646
  "`screenshot_unavailable` means a screenshot was asked for, but the page came back from the http",
549
- "engine without one."
647
+ "engine without one. `pdf_unavailable` means the PDF could not be made; the rest is there.",
648
+ "`pdf_single_page_overflow` means a `single_page` PDF was too tall for one page and goes on over",
649
+ "more pages. `custom_user_agent` means the request set its own `User-Agent` header; this",
650
+ "can lower the success rate.",
651
+ HEADERS_AND_COOKIES_TOOL_TEXT
550
652
  ].join(" ");
551
653
  function registerScrapeTool(server, getClient) {
552
654
  server.registerTool("scrape", {
@@ -592,12 +694,14 @@ const DESCRIPTION$4 = [
592
694
  "fetch prefer the synchronous `scrape` tool, which blocks and returns the page directly.",
593
695
  "Poll the job with `scrape_status` and fetch the page with `scrape_result` once done.",
594
696
  "Takes `extract.elements` like `scrape` (named values by CSS selector, no extra credits); the",
595
- "result carries them in `elements`. Rules: https://crawlbrulee.com/docs/scrape/elements.",
697
+ "result carries them in `elements`. Rules: https://crawlbrulee.com/docs/scrape/targeted-extraction.",
698
+ "Takes `extract.pdf` (save the page as a PDF) and `extract.screenshot.color_scheme` like `scrape`.",
596
699
  "Optionally attach a per-job completion `webhook`: we deliver a single",
597
700
  "signed `scrape.complete` POST to your endpoint when the job finishes (HTTPS required",
598
701
  "in production), and echoes your opaque `webhook.metadata` back in the delivery",
599
702
  "(under `data.metadata`, alongside `data.page_status_code` (on success) and `data.response_meta.usage`).",
600
- "Set `zero_data_retention: true` to keep the result out of the shared cache; anything stored to deliver it is kept for 24 hours, then deleted. It adds 1 credit and must be enabled for the organization (else a `zero_data_retention_not_enabled` error, not billed). See https://crawlbrulee.com/docs/zero-data-retention."
703
+ "Set `zero_data_retention: true` to keep the result out of the shared cache; anything stored to deliver it is kept for 24 hours, then deleted. It adds 1 credit and must be enabled for the organization (else a `zero_data_retention_not_enabled` error, not billed). See https://crawlbrulee.com/docs/zero-data-retention.",
704
+ HEADERS_AND_COOKIES_TOOL_TEXT
601
705
  ].join(" ");
602
706
  function registerScrapeAsyncTool(server, getClient) {
603
707
  server.registerTool("scrape_async", {
@@ -612,18 +716,22 @@ function registerScrapeAsyncTool(server, getClient) {
612
716
  //#region src/tools/scrapeResult.ts
613
717
  const DESCRIPTION$3 = [
614
718
  "Fetch the extracted content of a completed async scrape job (the same result shape as the",
615
- "synchronous `scrape` tool: markdown, cleaned HTML, raw HTML, links, images, screenshot,",
719
+ "synchronous `scrape` tool: markdown, cleaned HTML, raw HTML, links, images, screenshot, PDF,",
616
720
  "page metadata in `metadata`, values from `extract.elements` in `elements`, and",
617
721
  "`response_meta.usage`). Errors if the job is still `pending`/`running` — check",
618
722
  "`scrape_status` first (status `done`) before calling this.",
723
+ "A `failed` job has no result: this returns `job_failed`. A job that asked only for a",
724
+ "screenshot, a PDF or both, on a content type that cannot be captured (such as JSON or plain",
725
+ "text), returns `unsupported_screenshot_output` or `unsupported_pdf_output` instead, as `scrape`",
726
+ "does. Either way the job is not billed.",
619
727
  "Check `page_status_code` before you trust the content: it is the HTTP status the site answered",
620
728
  "with for the final page. A page the site served is a successful result whatever its status, so a",
621
729
  "404 or 503 page comes back with its content, not as an error. A 404 means the markdown is the",
622
730
  "site's \"not found\" page, not the page you asked for. 2xx and 4xx pages are billed, except 403,",
623
731
  "407, 408, 429 and 451; 5xx pages are never billed.",
624
- "A job answers for 24 hours after it was submitted, then returns `not_found`. Screenshot URLs are",
625
- "signed download links that expire at the same moment, however late you fetch the result: download",
626
- "the image if you need it later."
732
+ "A job answers for 24 hours after it was submitted, then returns `not_found`. Screenshot and PDF",
733
+ "URLs are signed download links that expire at the same moment, however late you fetch the",
734
+ "result: download the file if you need it later."
627
735
  ].join(" ");
628
736
  function registerScrapeResultTool(server, getClient) {
629
737
  server.registerTool("scrape_result", {
@@ -643,7 +751,9 @@ const DESCRIPTION$2 = [
643
751
  "resolved proxy tier) once it is `done`. A job whose page the site served ends `done` even when",
644
752
  "that page is a 404 or 503 — read `page_status_code` in the result. A job that could not reach",
645
753
  "the site at all ends `failed` (the `error` text is a general message, not the reason) and is not",
646
- "billed; retry later or check the url. Poll this until the status is",
754
+ "billed; retry later or check the url. A job that asked only for a screenshot, a PDF or both",
755
+ "and got no capture also ends `failed` and is not billed; `scrape_result` then names the reason.",
756
+ "Poll this until the status is",
647
757
  "`done`, then call `scrape_result` to fetch",
648
758
  "the page. If you registered a completion webhook on submit you can skip polling and react",
649
759
  "to the delivery instead. A job answers for 24 hours after it was submitted; after that this",
@@ -712,7 +822,7 @@ function registerWhoamiTool(server, getClient) {
712
822
  //#endregion
713
823
  //#region src/version.ts
714
824
  const SERVER_NAME = "crawlbrulee";
715
- const SERVER_VERSION = "1.3.3";
825
+ const SERVER_VERSION = "1.5.0";
716
826
 
717
827
  //#endregion
718
828
  //#region src/server.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlbrulee/mcp",
3
- "version": "1.3.3",
3
+ "version": "1.5.0",
4
4
  "mcpName": "io.github.crawlbrulee/mcp",
5
5
  "description": "official mcp server for crawlbrulee — EU-native web scraping for AI agents & developers. native scrape and map tools for your agent.",
6
6
  "keywords": [
@@ -63,7 +63,7 @@
63
63
  "prepublishOnly": "pnpm verify"
64
64
  },
65
65
  "dependencies": {
66
- "@crawlbrulee/sdk": "^1.3.0",
66
+ "@crawlbrulee/sdk": "^1.5.0",
67
67
  "@modelcontextprotocol/sdk": "^1.32.1",
68
68
  "zod": "^4.0.0"
69
69
  },