@crawlbrulee/mcp 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +440 -491
  2. package/package.json +6 -6
package/dist/index.js CHANGED
@@ -1,576 +1,525 @@
1
1
  #!/usr/bin/env node
2
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
- import { Crawlbrulee, isCrawlbruleeError, ENV_API_KEY } from '@crawlbrulee/sdk';
5
- import { z } from 'zod';
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { Crawlbrulee, ENV_API_KEY, isCrawlbruleeError } from "@crawlbrulee/sdk";
5
+ import { z } from "zod";
6
6
 
7
+ //#region src/client.ts
7
8
  function createDefaultClientFactory() {
8
- let cached;
9
- return () => {
10
- if (cached) return cached;
11
- cached = Crawlbrulee.fromEnv();
12
- return cached;
13
- };
9
+ let cached;
10
+ return () => {
11
+ if (cached) return cached;
12
+ cached = Crawlbrulee.fromEnv();
13
+ return cached;
14
+ };
14
15
  }
16
+
17
+ //#endregion
18
+ //#region src/errors.ts
19
+ /**
20
+ * Build a tool success envelope from an SDK result. The JSON-stringified
21
+ * body is what non-structured-aware hosts display; `structuredContent`
22
+ * carries the typed payload for hosts that respect the output schema.
23
+ */
15
24
  function toToolSuccess(result) {
16
- return {
17
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
18
- structuredContent: result
19
- };
25
+ return {
26
+ content: [{
27
+ type: "text",
28
+ text: JSON.stringify(result, null, 2)
29
+ }],
30
+ structuredContent: result
31
+ };
20
32
  }
33
+ /**
34
+ * Run an SDK call and wrap the outcome in the appropriate MCP envelope.
35
+ * All four tool handlers share this shape — keeps them down to a one-line
36
+ * forward to the SDK.
37
+ */
21
38
  async function runTool(fn) {
22
- try {
23
- return toToolSuccess(await fn());
24
- } catch (err) {
25
- return toToolError(err);
26
- }
39
+ try {
40
+ return toToolSuccess(await fn());
41
+ } catch (err) {
42
+ return toToolError(err);
43
+ }
27
44
  }
28
- var MISSING_API_KEY_REMEDIATION = `${ENV_API_KEY} is not set on the MCP host. Add --env ${ENV_API_KEY}=cwbl_... to your "claude mcp add" command (or the equivalent env block in your MCP client config), then restart the host.`;
45
+ const MISSING_API_KEY_REMEDIATION = `${ENV_API_KEY} is not set on the MCP host. Add --env ${ENV_API_KEY}=cwbl_... to your "claude mcp add" command (or the equivalent env block in your MCP client config), then restart the host.`;
46
+ /**
47
+ * Map any thrown value into the MCP tool-error envelope. SDK errors carry
48
+ * stable `errorName` codes and HTTP `status`; both go into the surfaced
49
+ * message so the calling agent can branch on them (e.g. retry on
50
+ * `rate_limited`, prompt the user on `invalid_credentials`).
51
+ *
52
+ * One special case: the SDK throws a generic `CrawlbruleeError` (status 0,
53
+ * errorName null) when `CRAWLBRULEE_API_KEY` is missing. We rewrite that
54
+ * to a clearer `missing_api_key` code with setup guidance.
55
+ */
29
56
  function toToolError(err) {
30
- if (isCrawlbruleeError(err)) {
31
- if (isMissingApiKeyError(err)) {
32
- return textErrorResult(`[missing_api_key] ${MISSING_API_KEY_REMEDIATION}`);
33
- }
34
- return crawlbruleeErrorResult(err);
35
- }
36
- const message = err instanceof Error ? err.message : String(err);
37
- return textErrorResult(`[internal_error] ${message}`);
57
+ if (isCrawlbruleeError(err)) {
58
+ if (isMissingApiKeyError(err)) return textErrorResult(`[missing_api_key] ${MISSING_API_KEY_REMEDIATION}`);
59
+ return crawlbruleeErrorResult(err);
60
+ }
61
+ return textErrorResult(`[internal_error] ${err instanceof Error ? err.message : String(err)}`);
38
62
  }
39
63
  function isMissingApiKeyError(err) {
40
- return err.status === 0 && err.errorName === null && err.message.includes(ENV_API_KEY);
64
+ return err.status === 0 && err.errorName === null && err.message.includes(ENV_API_KEY);
41
65
  }
42
66
  function crawlbruleeErrorResult(err) {
43
- const code = err.errorName ?? "crawlbrulee_error";
44
- const httpPart = err.status > 0 ? ` (HTTP ${err.status})` : "";
45
- return textErrorResult(`[${code}] ${err.message}${httpPart}`);
67
+ const code = err.errorName ?? "crawlbrulee_error";
68
+ const httpPart = err.status > 0 ? ` (HTTP ${err.status})` : "";
69
+ return textErrorResult(`[${code}] ${err.message}${httpPart}`);
46
70
  }
47
71
  function textErrorResult(text) {
48
- return { isError: true, content: [{ type: "text", text }] };
72
+ return {
73
+ isError: true,
74
+ content: [{
75
+ type: "text",
76
+ text
77
+ }]
78
+ };
49
79
  }
50
80
 
51
- // src/schemas/ScrapeScreenshotRules.ts
52
- var MAX_SCRAPE_SCREENSHOT_ACTIONS_BEFORE = 5;
53
- var MAX_SCRAPE_SCREENSHOT_TOTAL_WAIT_MS = 2e4;
54
- var MAX_SCRAPE_SCREENSHOT_TOTAL_SCROLL_PIXELS = 5e4;
55
- var DEFAULT_SCRAPE_SCREENSHOT_DEVICE_MODE = "desktop";
56
- var DEFAULT_SCRAPE_SCREENSHOT_CLEANUP = {
57
- ads_and_popups: true
58
- };
81
+ //#endregion
82
+ //#region src/schemas/ScrapeScreenshotRules.ts
83
+ const MAX_SCRAPE_SCREENSHOT_TOTAL_WAIT_MS = 2e4;
84
+ const MAX_SCRAPE_SCREENSHOT_TOTAL_SCROLL_PIXELS = 5e4;
85
+ const DEFAULT_SCRAPE_SCREENSHOT_DEVICE_MODE = "desktop";
86
+ const DEFAULT_SCRAPE_SCREENSHOT_CLEANUP = { ads_and_popups: true };
59
87
  function getScrapeScreenshotBeforeActionTotals(actions) {
60
- let totalWaitMs = 0;
61
- let totalAbsoluteScrollPixels = 0;
62
- for (const action of actions ?? []) {
63
- if (action.type === "wait") {
64
- totalWaitMs += action.ms;
65
- continue;
66
- }
67
- totalAbsoluteScrollPixels += Math.abs(action.pixels);
68
- }
69
- return { totalWaitMs, totalAbsoluteScrollPixels };
88
+ let totalWaitMs = 0;
89
+ let totalAbsoluteScrollPixels = 0;
90
+ for (const action of actions ?? []) {
91
+ if (action.type === "wait") {
92
+ totalWaitMs += action.ms;
93
+ continue;
94
+ }
95
+ totalAbsoluteScrollPixels += Math.abs(action.pixels);
96
+ }
97
+ return {
98
+ totalWaitMs,
99
+ totalAbsoluteScrollPixels
100
+ };
70
101
  }
71
- var Schema_ApiScrapeScreenshotType = z.enum(["viewport", "full_page"]).describe("Screenshot mode: viewport (visible area) or full_page (entire page)");
72
- var Schema_ScrapeScreenshotDeviceMode = z.enum(["desktop", "mobile"]).describe("Device mode to emulate for viewport sizing");
73
- var Schema_ScrapeScreenshotCleanup = z.object({
74
- ads_and_popups: z.boolean().default(DEFAULT_SCRAPE_SCREENSHOT_CLEANUP.ads_and_popups).describe("Remove ads, cookie banners, and popups before capturing")
75
- }).strict().describe("Page cleanup options applied before screenshot capture");
76
- var Schema_ScrapeScreenshotBeforeAction = z.discriminatedUnion("type", [
77
- z.object({
78
- type: z.literal("wait").describe("Wait for a duration before capturing"),
79
- ms: z.number().int().nonnegative().describe("Milliseconds to wait")
80
- }),
81
- z.object({
82
- type: z.literal("scroll").describe("Scroll the page before capturing"),
83
- pixels: z.number().int().describe("Pixels to scroll (positive = down, negative = up)")
84
- })
85
- ]);
86
- var Schema_ScrapeScreenshotAfterAction = z.object({
87
- type: z.literal("slice").describe("Slice the screenshot into horizontal tiles"),
88
- height: z.number().int().min(500).describe("Height of each tile in pixels (minimum 500)")
102
+
103
+ //#endregion
104
+ //#region src/schemas/ScrapeScreenshotSchemas.ts
105
+ const Schema_ApiScrapeScreenshotType = z.enum(["viewport", "full_page"]).describe("Screenshot mode: viewport (visible area) or full_page (entire page)");
106
+ const Schema_ScrapeScreenshotDeviceMode = z.enum(["desktop", "mobile"]).describe("Device mode to emulate for viewport sizing");
107
+ const Schema_ScrapeScreenshotCleanup = z.object({ ads_and_popups: z.boolean().default(DEFAULT_SCRAPE_SCREENSHOT_CLEANUP.ads_and_popups).describe("Remove ads, cookie banners, and popups before capturing") }).strict().describe("Page cleanup options applied before screenshot capture");
108
+ const Schema_ScrapeScreenshotBeforeAction = z.discriminatedUnion("type", [z.object({
109
+ type: z.literal("wait").describe("Wait for a duration before capturing"),
110
+ ms: z.number().int().nonnegative().describe("Milliseconds to wait")
111
+ }), z.object({
112
+ type: z.literal("scroll").describe("Scroll the page before capturing"),
113
+ pixels: z.number().int().describe("Pixels to scroll (positive = down, negative = up)")
114
+ })]);
115
+ const Schema_ScrapeScreenshotAfterAction = z.object({
116
+ type: z.literal("slice").describe("Slice the screenshot into horizontal tiles"),
117
+ height: z.number().int().min(500).describe("Height of each tile in pixels (minimum 500)")
89
118
  });
90
119
  function refineScrapeScreenshotActionsBefore(value, ctx) {
91
- const totals = getScrapeScreenshotBeforeActionTotals(value.actions_before);
92
- if (totals.totalWaitMs > MAX_SCRAPE_SCREENSHOT_TOTAL_WAIT_MS) {
93
- ctx.addIssue({
94
- code: "custom",
95
- path: ["actions_before"],
96
- message: `Total wait time cannot exceed ${MAX_SCRAPE_SCREENSHOT_TOTAL_WAIT_MS}ms.`
97
- });
98
- }
99
- if (totals.totalAbsoluteScrollPixels > MAX_SCRAPE_SCREENSHOT_TOTAL_SCROLL_PIXELS) {
100
- ctx.addIssue({
101
- code: "custom",
102
- path: ["actions_before"],
103
- message: `Total absolute scroll distance cannot exceed ${MAX_SCRAPE_SCREENSHOT_TOTAL_SCROLL_PIXELS}px.`
104
- });
105
- }
120
+ const totals = getScrapeScreenshotBeforeActionTotals(value.actions_before);
121
+ if (totals.totalWaitMs > 2e4) ctx.addIssue({
122
+ code: "custom",
123
+ path: ["actions_before"],
124
+ message: `Total wait time cannot exceed ${MAX_SCRAPE_SCREENSHOT_TOTAL_WAIT_MS}ms.`
125
+ });
126
+ if (totals.totalAbsoluteScrollPixels > 5e4) ctx.addIssue({
127
+ code: "custom",
128
+ path: ["actions_before"],
129
+ message: `Total absolute scroll distance cannot exceed ${MAX_SCRAPE_SCREENSHOT_TOTAL_SCROLL_PIXELS}px.`
130
+ });
106
131
  }
107
132
 
108
- // src/schemas/ApiScrapeRequest.ts
109
- var DEFAULT_API_SCRAPE_CACHE_MAX_AGE_SECONDS = 2 * 24 * 60 * 60;
110
- var API_PROXY_TIER_VALUES = ["basic", "advanced", "auto"];
111
- var Schema_ApiProxyType = z.enum(API_PROXY_TIER_VALUES).default("auto").describe(
112
- "Proxy tier: basic, advanced, or auto. Defaults to auto (automatic selection: basic tier first, escalates to advanced on failure)."
113
- );
114
- var Schema_ApiScrapeViewport = z.object({
115
- width: z.number().int().min(16).max(1e4).describe("Viewport width in pixels (16\u201310000)"),
116
- height: z.number().int().min(16).max(1e4).describe("Viewport height in pixels (16\u201310000)"),
117
- device_scale_factor: z.number().min(1).max(4).optional().describe("Device pixel ratio (1\u20134, fractional allowed; e.g. 2 for Retina). Defaults to 1.")
133
+ //#endregion
134
+ //#region src/schemas/ApiScrapeRequest.ts
135
+ const DEFAULT_API_SCRAPE_CACHE_MAX_AGE_SECONDS = 2880 * 60;
136
+ const API_PROXY_TIER_VALUES = [
137
+ "basic",
138
+ "advanced",
139
+ "auto"
140
+ ];
141
+ const Schema_ApiProxyType = z.enum(API_PROXY_TIER_VALUES).default("auto").describe("Proxy tier: basic, advanced, or auto. Defaults to auto (automatic selection: basic tier first, escalates to advanced on failure).");
142
+ const Schema_ApiScrapeViewport = z.object({
143
+ width: z.number().int().min(16).max(1e4).describe("Viewport width in pixels (16–10000)"),
144
+ height: z.number().int().min(16).max(1e4).describe("Viewport height in pixels (16–10000)"),
145
+ device_scale_factor: z.number().min(1).max(4).optional().describe("Device pixel ratio (1–4, fractional allowed; e.g. 2 for Retina). Defaults to 1.")
118
146
  }).strict().describe("Custom browser viewport dimensions");
119
- var Schema_ApiScrapeFormatScreenshot = z.object({
120
- type: Schema_ApiScrapeScreenshotType.describe("Screenshot capture mode"),
121
- viewport: Schema_ApiScrapeViewport.optional().describe(
122
- "Custom viewport dimensions; uses device_mode defaults if omitted"
123
- ),
124
- device_mode: Schema_ScrapeScreenshotDeviceMode.default(
125
- DEFAULT_SCRAPE_SCREENSHOT_DEVICE_MODE
126
- ).describe("Emulate desktop or mobile device viewport"),
127
- cleanup: Schema_ScrapeScreenshotCleanup.default(DEFAULT_SCRAPE_SCREENSHOT_CLEANUP).describe(
128
- "Page cleanup options applied before capturing"
129
- ),
130
- actions_before: z.array(Schema_ScrapeScreenshotBeforeAction).max(MAX_SCRAPE_SCREENSHOT_ACTIONS_BEFORE).default([]).describe("Actions to perform before taking the screenshot (wait, scroll)"),
131
- actions_after: z.array(Schema_ScrapeScreenshotAfterAction).max(1).default([]).describe("Actions to perform after taking the screenshot (e.g. slice into tiles)")
147
+ const Schema_ApiScrapeFormatScreenshot = z.object({
148
+ type: Schema_ApiScrapeScreenshotType.describe("Screenshot capture mode"),
149
+ viewport: Schema_ApiScrapeViewport.optional().describe("Custom viewport dimensions; uses device_mode defaults if omitted"),
150
+ device_mode: Schema_ScrapeScreenshotDeviceMode.default(DEFAULT_SCRAPE_SCREENSHOT_DEVICE_MODE).describe("Emulate desktop or mobile device viewport"),
151
+ cleanup: Schema_ScrapeScreenshotCleanup.default(DEFAULT_SCRAPE_SCREENSHOT_CLEANUP).describe("Page cleanup options applied before capturing"),
152
+ actions_before: z.array(Schema_ScrapeScreenshotBeforeAction).max(5).default([]).describe("Actions to perform before taking the screenshot (wait, scroll)"),
153
+ actions_after: z.array(Schema_ScrapeScreenshotAfterAction).max(1).default([]).describe("Actions to perform after taking the screenshot (e.g. slice into tiles)")
132
154
  }).strict().superRefine(refineScrapeScreenshotActionsBefore).describe("Screenshot capture configuration");
133
- var Schema_ApiScrapeCache = z.object({
134
- 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"),
135
- ignore_query_params: z.boolean().default(false).describe("Treat URLs with different query parameters as the same cache entry")
136
- }).strict().describe("Cache settings for the scrape request");
137
- var Schema_ApiScrapeExtract = z.object({
138
- metadata: z.boolean().default(true).describe("Extract page metadata (title, description, OG tags, etc.)"),
139
- cleaned_html: z.boolean().default(true).describe("Extract cleaned HTML (main content only)"),
140
- markdown: z.boolean().default(false).describe("Extract page content as clean Markdown"),
141
- raw_html: z.boolean().default(false).describe("Return the raw, unprocessed HTML"),
142
- links: z.boolean().default(false).describe("Extract all links found on the page"),
143
- images: z.boolean().default(false).describe("Extract all inline images found on the page"),
144
- screenshot: Schema_ApiScrapeFormatScreenshot.optional().describe(
145
- "Capture a screenshot of the page"
146
- )
155
+ 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");
156
+ const Schema_ApiScrapeExtract = z.object({
157
+ metadata: z.boolean().default(true).describe("Extract page metadata (title, description, OG tags, etc.)"),
158
+ cleaned_html: z.boolean().default(true).describe("Extract cleaned HTML (main content only)"),
159
+ markdown: z.boolean().default(false).describe("Extract page content as clean Markdown"),
160
+ raw_html: z.boolean().default(false).describe("Return the raw, unprocessed HTML"),
161
+ links: z.boolean().default(false).describe("Extract all links found on the page"),
162
+ images: z.boolean().default(false).describe("Extract all inline images found on the page"),
163
+ screenshot: Schema_ApiScrapeFormatScreenshot.optional().describe("Capture a screenshot of the page")
147
164
  }).strict().describe("Which content formats to extract from the scraped page");
148
- var Schema_ApiScrapeLocation = z.object({
149
- locale: z.string().min(2).max(35).optional().describe(
150
- "BCP-47 locale (2-35 chars, e.g. 'en-US', 'de-DE', 'pt-BR') driving Accept-Language and navigator.language"
151
- ),
152
- country: z.string().regex(
153
- /^([a-zA-Z]{2}|europe)$/i,
154
- "country must be a 2-letter ISO 3166-1 alpha-2 code, 'eu', or 'europe'"
155
- ).optional().describe(
156
- "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)."
157
- )
165
+ const Schema_ApiScrapeLocation = z.object({
166
+ 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"),
167
+ 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).")
158
168
  }).strict().describe("Optional locale + country emulation for the scrape");
159
- var Schema_ApiScrapeRequest = z.object({
160
- url: z.string().describe("The URL to scrape"),
161
- extract: Schema_ApiScrapeExtract.prefault({}).describe(
162
- "Which content formats to extract. Defaults to metadata + cleaned_html."
163
- ),
164
- cache: Schema_ApiScrapeCache.optional().describe("Cache settings for this request"),
165
- require_js: z.boolean().default(false).describe("Use a headless browser to render JavaScript before scraping"),
166
- exclude_selectors: z.array(z.string()).optional().describe("CSS selectors to exclude from the extracted content"),
167
- proxy: Schema_ApiProxyType.describe("Proxy tier to use for fetching"),
168
- location: Schema_ApiScrapeLocation.optional()
169
+ const Schema_ApiScrapeRequest = z.object({
170
+ url: z.string().describe("The URL to scrape. Known tracking parameters (utm_*, mtm_*, ga_*, pk_*, gclid, fbclid, msclkid, and others) 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."),
171
+ extract: Schema_ApiScrapeExtract.prefault({}).describe("Which content formats to extract. Defaults to metadata + cleaned_html."),
172
+ cache: Schema_ApiScrapeCache.optional().describe("Cache settings for this request"),
173
+ require_js: z.boolean().default(false).describe("Use a headless browser to render JavaScript before scraping"),
174
+ exclude_selectors: z.array(z.string()).optional().describe("CSS selectors to exclude from the extracted content"),
175
+ proxy: Schema_ApiProxyType.describe("Proxy tier to use for fetching"),
176
+ location: Schema_ApiScrapeLocation.optional()
169
177
  }).strict();
170
178
 
171
- // src/schemas/ApiMapRequest.ts
172
- var Schema_ApiMapLocation = z.object({
173
- country: z.string().regex(
174
- /^([a-zA-Z]{2}|europe)$/i,
175
- "country must be a 2-letter ISO 3166-1 alpha-2 code, 'eu', or 'europe'"
176
- ).optional().describe(
177
- "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)."
178
- )
179
- }).strict().describe("Optional country emulation for the map");
180
- var DEFAULT_API_MAP_CACHE_MAX_AGE_SECONDS = 7 * 24 * 60 * 60;
181
- var DEFAULT_API_MAP_MAX_URLS = 1e5;
182
- var MAX_API_MAP_MAX_URLS = 1e5;
183
- var DEFAULT_API_MAP_PAGE_LIMIT = 1e4;
184
- var MAX_API_MAP_PAGE_LIMIT = 1e4;
185
- var Schema_ApiMapTypes = z.object({
186
- internal: z.boolean().default(true).describe("Include internal links (same domain)"),
187
- internal_subdomains: z.boolean().default(true).describe("Include links to subdomains of the target domain"),
188
- external: z.boolean().default(true).describe("Include external links (different domains)")
179
+ //#endregion
180
+ //#region src/schemas/ApiMapRequest.ts
181
+ 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");
182
+ const DEFAULT_API_MAP_CACHE_MAX_AGE_SECONDS = 10080 * 60;
183
+ const DEFAULT_API_MAP_MAX_URLS = 1e5;
184
+ const MAX_API_MAP_MAX_URLS = 1e5;
185
+ const DEFAULT_API_MAP_PAGE_LIMIT = 1e4;
186
+ const MAX_API_MAP_PAGE_LIMIT = 1e4;
187
+ const Schema_ApiMapTypes = z.object({
188
+ internal: z.boolean().default(true).describe("Include internal links (same domain)"),
189
+ internal_subdomains: z.boolean().default(true).describe("Include links to subdomains of the target domain"),
190
+ external: z.boolean().default(true).describe("Include external links (different domains)")
189
191
  }).describe("Filter which link types to include in the map");
190
- var Schema_ApiMapCache = z.object({
191
- 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")
192
- }).describe("Cache settings for the map request");
193
- var Schema_ApiMapRequest = z.object({
194
- url: z.string().describe("The website URL to map"),
195
- proxy: Schema_ApiProxyType.default("auto").describe("Proxy tier to use for fetching"),
196
- sitemap_only: z.boolean().default(false).describe("Only use sitemap.xml \u2014 skip homepage link extraction"),
197
- types: Schema_ApiMapTypes.optional().describe("Filter which link types to include"),
198
- cache: Schema_ApiMapCache.optional().describe("Cache settings for this request"),
199
- max_urls: z.number().int().positive().max(MAX_API_MAP_MAX_URLS).default(DEFAULT_API_MAP_MAX_URLS).describe("Maximum number of URLs to store in the map"),
200
- page: z.number().int().positive().default(1).describe("Page number for paginated results"),
201
- 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"),
202
- location: Schema_ApiMapLocation.optional()
192
+ 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");
193
+ const Schema_ApiMapRequest = z.object({
194
+ 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 (utm_*, mtm_*, ga_*, pk_*, gclid, fbclid, msclkid, and others) are removed before the request is processed."),
195
+ proxy: Schema_ApiProxyType.default("auto").describe("Proxy tier to use for fetching"),
196
+ sitemap_only: z.boolean().default(false).describe("Only use sitemap.xml — skip homepage link extraction"),
197
+ types: Schema_ApiMapTypes.optional().describe("Filter which link types to include"),
198
+ cache: Schema_ApiMapCache.optional().describe("Cache settings for this request"),
199
+ max_urls: z.number().int().positive().max(MAX_API_MAP_MAX_URLS).default(DEFAULT_API_MAP_MAX_URLS).describe("Maximum number of URLs to store in the map"),
200
+ page: z.number().int().positive().default(1).describe("Page number for paginated results"),
201
+ 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"),
202
+ location: Schema_ApiMapLocation.optional()
203
203
  });
204
- var Schema_ApiViewport = z.object({
205
- width: z.number().describe("Viewport width in pixels"),
206
- height: z.number().describe("Viewport height in pixels"),
207
- device_scale_factor: z.number().describe("Device pixel ratio used for the capture")
208
- });
209
- var Schema_ApiScreenshotProperties = z.object({
210
- file_name: z.string().describe("File name of the screenshot image"),
211
- mime: z.string().describe("MIME type of the screenshot (e.g. image/png)"),
212
- width: z.number().describe("Image width in pixels"),
213
- height: z.number().describe("Image height in pixels"),
214
- viewport: Schema_ApiViewport.describe("Viewport dimensions used during capture")
204
+
205
+ //#endregion
206
+ //#region src/schemas/ApiScrapeResponse.ts
207
+ const Schema_ApiViewport = z.object({
208
+ width: z.number().describe("Viewport width in pixels"),
209
+ height: z.number().describe("Viewport height in pixels"),
210
+ device_scale_factor: z.number().describe("Device pixel ratio used for the capture")
215
211
  });
216
- var Schema_ApiScreenshotSlice = z.object({
217
- row_nr: z.number().describe("Row index of this slice (0-based)"),
218
- url: z.string().describe("URL to download this slice image"),
219
- type: z.literal("slice").describe("Slice type identifier"),
220
- properties: Schema_ApiScreenshotProperties.describe("Image properties for this slice")
212
+ const Schema_ApiScreenshotProperties = z.object({
213
+ file_name: z.string().describe("File name of the screenshot image"),
214
+ mime: z.string().describe("MIME type of the screenshot (e.g. image/png)"),
215
+ width: z.number().describe("Image width in pixels"),
216
+ height: z.number().describe("Image height in pixels"),
217
+ viewport: Schema_ApiViewport.describe("Viewport dimensions used during capture")
221
218
  });
222
- var Schema_ApiScreenshotResponse = z.object({
223
- url: z.string().describe("URL to download the full screenshot image"),
224
- type: Schema_ApiScrapeScreenshotType.describe("Screenshot capture mode that was used"),
225
- properties: Schema_ApiScreenshotProperties.describe("Image properties for the full screenshot"),
226
- slices: z.array(Schema_ApiScreenshotSlice).optional().describe("Individual tile slices (present when slice action_after was requested)")
219
+ const Schema_ApiScreenshotSlice = z.object({
220
+ row_nr: z.number().describe("Row index of this slice (0-based)"),
221
+ url: z.string().describe("URL to download this slice image"),
222
+ type: z.literal("slice").describe("Slice type identifier"),
223
+ properties: Schema_ApiScreenshotProperties.describe("Image properties for this slice")
227
224
  });
228
- var Schema_ApiPageInlineImgItem = z.object({
229
- url: z.string().describe("Absolute URL of the image"),
230
- alt: z.string().nullable().describe("Alt text of the image, or null if not set")
225
+ const Schema_ApiScreenshotResponse = z.object({
226
+ url: z.string().describe("URL to download the full screenshot image"),
227
+ type: Schema_ApiScrapeScreenshotType.describe("Screenshot capture mode that was used"),
228
+ properties: Schema_ApiScreenshotProperties.describe("Image properties for the full screenshot"),
229
+ slices: z.array(Schema_ApiScreenshotSlice).optional().describe("Individual tile slices (present when slice action_after was requested)")
231
230
  });
232
- var Schema_ApiPageLink = z.object({
233
- text: z.string().describe("Anchor text of the link"),
234
- href: z.string().describe("The link URL as it appears on the page (absolute or relative)"),
235
- internal: z.boolean().describe("Whether the link points to the same domain")
231
+ const Schema_ApiPageInlineImgItem = z.object({
232
+ url: z.string().describe("Absolute URL of the image"),
233
+ alt: z.string().nullable().describe("Alt text of the image, or null if not set")
236
234
  });
237
- var API_RESOLVED_PROXY_TIER_VALUES = ["basic", "advanced"];
238
- var Schema_ApiUsageMeta = z.object({
239
- credits: z.number().int().nonnegative().describe("Credits charged for this request. `0` on a cache hit (no fresh fetch was billed)."),
240
- proxy: z.enum(API_RESOLVED_PROXY_TIER_VALUES).describe(
241
- "The proxy tier the request actually ran on (resolved value \u2014 never `auto`; `auto` is resolved server-side to `basic` or `advanced`)."
242
- ),
243
- cache_hit: z.boolean().describe("Whether the result was served from cache (`true`) or freshly fetched (`false`).")
235
+ const Schema_ApiPageLink = z.object({
236
+ text: z.string().describe("Anchor text of the link"),
237
+ href: z.string().describe("The link URL as it appears on the page (absolute or relative)"),
238
+ internal: z.boolean().describe("Whether the link points to the same domain")
244
239
  });
245
- var Schema_ApiResponseMeta = z.object({
246
- usage: Schema_ApiUsageMeta.describe(
247
- "Usage accounting for this request: credits charged, resolved proxy tier, and cache-hit flag."
248
- )
240
+ const API_RESOLVED_PROXY_TIER_VALUES = ["basic", "advanced"];
241
+ const Schema_ApiUsageMeta = z.object({
242
+ credits: z.number().int().nonnegative().describe("Credits charged for this request. `0` on a cache hit (no fresh fetch was billed)."),
243
+ proxy: z.enum(API_RESOLVED_PROXY_TIER_VALUES).describe("The proxy tier the request actually ran on (resolved value — never `auto`; `auto` is resolved server-side to `basic` or `advanced`)."),
244
+ cache_hit: z.boolean().describe("Whether the result was served from cache (`true`) or freshly fetched (`false`).")
249
245
  });
250
- var Schema_ApiScrapeMeta = z.object({
251
- title: z.string().optional().describe("Page title from the <title> tag"),
252
- description: z.string().optional().describe("Meta description"),
253
- keywords: z.array(z.string()).optional().describe("Meta keywords"),
254
- canonical: z.string().optional().describe("Canonical URL specified by the page"),
255
- og_url: z.string().optional().describe("Open Graph URL"),
256
- og_title: z.string().optional().describe("Open Graph title"),
257
- og_description: z.string().optional().describe("Open Graph description"),
258
- og_type: z.string().optional().describe("Open Graph type (e.g. article, website)"),
259
- og_site_name: z.string().optional().describe("Open Graph site name"),
260
- og_locale: z.string().optional().describe("Open Graph locale (e.g. en_US)"),
261
- og_locale_alternate: z.array(z.string()).optional().describe("Alternate Open Graph locales"),
262
- og_image: z.string().optional().describe("Open Graph image URL"),
263
- author: z.string().optional().describe("Article author"),
264
- date_modified: z.string().optional().describe("Article last-modified date"),
265
- date_published: z.string().optional().describe("Article publication date"),
266
- twitter_site: z.string().optional().describe("Twitter @username for the site"),
267
- twitter_card: z.string().optional().describe("Twitter card type (e.g. summary_large_image)"),
268
- twitter_description: z.string().optional().describe("Twitter card description"),
269
- twitter_title: z.string().optional().describe("Twitter card title"),
270
- twitter_image: z.string().optional().describe("Twitter card image URL"),
271
- robots: z.string().optional().describe("Robots meta directive (e.g. noindex, nofollow)"),
272
- favicon_url: z.string().nullish().describe("Resolved favicon URL for the page (best-effort, from <head> icon hints + manifest)")
246
+ const Schema_ApiResponseMeta = z.object({ usage: Schema_ApiUsageMeta.describe("Usage accounting for this request: credits charged, resolved proxy tier, and cache-hit flag.") });
247
+ const Schema_ApiScrapeMeta = z.object({
248
+ title: z.string().optional().describe("Page title from the <title> tag"),
249
+ description: z.string().optional().describe("Meta description"),
250
+ keywords: z.array(z.string()).optional().describe("Meta keywords"),
251
+ canonical: z.string().optional().describe("Canonical URL specified by the page"),
252
+ og_url: z.string().optional().describe("Open Graph URL"),
253
+ og_title: z.string().optional().describe("Open Graph title"),
254
+ og_description: z.string().optional().describe("Open Graph description"),
255
+ og_type: z.string().optional().describe("Open Graph type (e.g. article, website)"),
256
+ og_site_name: z.string().optional().describe("Open Graph site name"),
257
+ og_locale: z.string().optional().describe("Open Graph locale (e.g. en_US)"),
258
+ og_locale_alternate: z.array(z.string()).optional().describe("Alternate Open Graph locales"),
259
+ og_image: z.string().optional().describe("Open Graph image URL"),
260
+ author: z.string().optional().describe("Article author"),
261
+ date_modified: z.string().optional().describe("Article last-modified date"),
262
+ date_published: z.string().optional().describe("Article publication date"),
263
+ twitter_site: z.string().optional().describe("Twitter @username for the site"),
264
+ twitter_card: z.string().optional().describe("Twitter card type (e.g. summary_large_image)"),
265
+ twitter_description: z.string().optional().describe("Twitter card description"),
266
+ twitter_title: z.string().optional().describe("Twitter card title"),
267
+ twitter_image: z.string().optional().describe("Twitter card image URL"),
268
+ robots: z.string().optional().describe("Robots meta directive (e.g. noindex, nofollow)"),
269
+ favicon_url: z.string().nullish().describe("Resolved favicon URL for the page (best-effort, from <head> icon hints + manifest)")
273
270
  });
274
- var Schema_ApiScrapeSuccessResponse = z.object({
275
- url: z.string().describe("The URL that was scraped (after any redirects)"),
276
- content_type: z.string().optional().describe("Content-Type header returned by the server"),
277
- unsupported_fields: z.array(z.string()).optional().describe("Extract fields that were requested but are not supported for this content type"),
278
- markdown: z.string().optional().describe("Page content converted to clean Markdown"),
279
- cleaned_html: z.string().optional().describe("Cleaned HTML of the main page content"),
280
- raw_html: z.string().optional().describe("Raw, unprocessed HTML of the page"),
281
- images: z.array(Schema_ApiPageInlineImgItem).optional().describe("Inline images found on the page"),
282
- links: z.array(Schema_ApiPageLink).optional().describe("Links found on the page"),
283
- screenshot: Schema_ApiScreenshotResponse.optional().describe(
284
- "Screenshot of the page, if requested"
285
- ),
286
- metadata: Schema_ApiScrapeMeta.optional().describe(
287
- "Extracted page metadata (title, OG tags, etc.)"
288
- ),
289
- warnings: z.array(z.string()).optional().describe(
290
- "Non-error notices about the scrape (e.g. `screenshot_truncated` when a long page exceeded the scrolling-screenshot height cap). Stable string codes \u2014 clients can switch on them. Currently surfaced only on fresh scrapes; cache hits omit warnings."
291
- ),
292
- response_meta: Schema_ApiResponseMeta.describe(
293
- "Request-level metadata. `response_meta.usage` reports credits charged (0 on a cache hit), the resolved proxy tier, and the cache-hit flag."
294
- )
271
+ const Schema_ApiScrapeSuccessResponse = z.object({
272
+ url: z.string().describe("The URL that was scraped (after any redirects)"),
273
+ content_type: z.string().optional().describe("Content-Type header returned by the server"),
274
+ unsupported_fields: z.array(z.string()).optional().describe("Extract fields that were requested but are not supported for this content type"),
275
+ markdown: z.string().optional().describe("Page content converted to clean Markdown"),
276
+ cleaned_html: z.string().optional().describe("Cleaned HTML of the main page content"),
277
+ raw_html: z.string().optional().describe("Raw, unprocessed HTML of the page"),
278
+ images: z.array(Schema_ApiPageInlineImgItem).optional().describe("Inline images found on the page"),
279
+ links: z.array(Schema_ApiPageLink).optional().describe("Links found on the page"),
280
+ screenshot: Schema_ApiScreenshotResponse.optional().describe("Screenshot of the page, if requested"),
281
+ metadata: Schema_ApiScrapeMeta.optional().describe("Extracted page metadata (title, OG tags, etc.)"),
282
+ warnings: z.array(z.string()).optional().describe("Non-error notices about the scrape (e.g. `screenshot_truncated` when a long page exceeded the scrolling-screenshot height cap). Stable string codes — clients can switch on them. Currently surfaced only on fresh scrapes; cache hits omit warnings."),
283
+ response_meta: Schema_ApiResponseMeta.describe("Request-level metadata. `response_meta.usage` reports credits charged (0 on a cache hit), the resolved proxy tier, and the cache-hit flag.")
295
284
  });
296
285
 
297
- // src/schemas/ApiMapResponse.ts
298
- var Schema_ApiMapLinkItem = z.object({
299
- url: z.string().describe("The discovered URL")
286
+ //#endregion
287
+ //#region src/schemas/ApiMapResponse.ts
288
+ const Schema_ApiMapLinkItem = z.object({ url: z.string().describe("The discovered URL") });
289
+ const Schema_ApiMapPagination = z.object({
290
+ page: z.number().int().positive().describe("Current page number"),
291
+ limit: z.number().int().positive().describe("Number of items per page"),
292
+ total: z.number().int().nonnegative().describe("Total number of URLs in the map"),
293
+ total_pages: z.number().int().nonnegative().describe("Total number of pages available"),
294
+ has_more: z.boolean().describe("Whether more pages are available")
300
295
  });
301
- var Schema_ApiMapPagination = z.object({
302
- page: z.number().int().positive().describe("Current page number"),
303
- limit: z.number().int().positive().describe("Number of items per page"),
304
- total: z.number().int().nonnegative().describe("Total number of URLs in the map"),
305
- total_pages: z.number().int().nonnegative().describe("Total number of pages available"),
306
- has_more: z.boolean().describe("Whether more pages are available")
296
+ const Schema_ApiMapTruncation = z.object({
297
+ storage_capped: z.boolean().describe("Whether the stored map was capped by the max_urls limit"),
298
+ response_capped: z.boolean().describe("Whether the response was capped by pagination"),
299
+ total_before_max_urls: z.number().int().nonnegative().describe("Total URLs found before applying the max_urls cap"),
300
+ total_detected_before_storage_cap: z.number().int().nonnegative().describe("Total URLs detected during discovery before the storage cap was applied")
307
301
  });
308
- var Schema_ApiMapTruncation = z.object({
309
- storage_capped: z.boolean().describe("Whether the stored map was capped by the max_urls limit"),
310
- response_capped: z.boolean().describe("Whether the response was capped by pagination"),
311
- total_before_max_urls: z.number().int().nonnegative().describe("Total URLs found before applying the max_urls cap"),
312
- total_detected_before_storage_cap: z.number().int().nonnegative().describe("Total URLs detected during discovery before the storage cap was applied")
313
- });
314
- var Schema_ApiMapResult = z.object({
315
- links: z.array(Schema_ApiMapLinkItem).describe("List of discovered URLs for the current page"),
316
- response_meta: z.object({
317
- pagination: Schema_ApiMapPagination.describe("Pagination details for the result set"),
318
- truncation: Schema_ApiMapTruncation.describe(
319
- "Information about whether the results were truncated"
320
- ),
321
- usage: Schema_ApiUsageMeta.describe(
322
- "Usage accounting for this map request: credits charged (0 on a cache hit), the resolved proxy tier, and the cache-hit flag."
323
- )
324
- }).describe("Response metadata including pagination, truncation, and usage info")
302
+ const Schema_ApiMapResult = z.object({
303
+ links: z.array(Schema_ApiMapLinkItem).describe("List of discovered URLs for the current page"),
304
+ response_meta: z.object({
305
+ pagination: Schema_ApiMapPagination.describe("Pagination details for the result set"),
306
+ truncation: Schema_ApiMapTruncation.describe("Information about whether the results were truncated"),
307
+ usage: Schema_ApiUsageMeta.describe("Usage accounting for this map request: credits charged (0 on a cache hit), the resolved proxy tier, and the cache-hit flag.")
308
+ }).describe("Response metadata including pagination, truncation, and usage info")
325
309
  });
326
310
 
327
- // src/tools/map.ts
328
- var DESCRIPTION = [
329
- "Build (or fetch a cached) link-map for a website by combining sitemap discovery with homepage",
330
- "link extraction. Returns paginated lists of discovered URLs. Filterable by link type",
331
- "(internal / external / subdomain). Use this to enumerate a site before scraping selected pages."
311
+ //#endregion
312
+ //#region src/tools/map.ts
313
+ const DESCRIPTION$6 = [
314
+ "Build (or fetch a cached) link-map for a website by combining sitemap discovery with homepage",
315
+ "link extraction. Returns paginated lists of discovered URLs. Filterable by link type",
316
+ "(internal / external / subdomain). Use this to enumerate a site before scraping selected pages."
332
317
  ].join(" ");
333
318
  function registerMapTool(server, getClient) {
334
- server.registerTool(
335
- "map",
336
- {
337
- title: "Map a website",
338
- description: DESCRIPTION,
339
- inputSchema: Schema_ApiMapRequest.shape,
340
- outputSchema: Schema_ApiMapResult.shape
341
- },
342
- (args) => (
343
- // The vendored response schema tracks the new wire contract: the envelope is
344
- // `response_meta` (with a `usage` block), whereas the published SDK's `MapResponse`
345
- // type still has the older `meta` envelope (no `usage`). The field is both renamed
346
- // and widened, so a plain cast won't type-check — bridge through `unknown` until the
347
- // SDK catches up. The runtime payload already matches the vendored shape.
348
- runTool(async () => await getClient().map(args))
349
- )
350
- );
319
+ server.registerTool("map", {
320
+ title: "Map a website",
321
+ description: DESCRIPTION$6,
322
+ inputSchema: Schema_ApiMapRequest.shape,
323
+ outputSchema: Schema_ApiMapResult.shape
324
+ }, (args) => runTool(async () => await getClient().map(args)));
351
325
  }
352
326
 
353
- // src/tools/scrape.ts
354
- var DESCRIPTION2 = [
355
- "Fetch a single URL via the crawlbrulee scraping API and return the requested content",
356
- "(markdown, cleaned HTML, raw HTML, links, images, screenshot, page metadata in `metadata`).",
357
- "Use this for one-shot page extraction. For full-site discovery use the `map` tool first.",
358
- "Screenshot URLs in the response are signed download links \u2014 the agent can fetch them when needed.",
359
- "The response also carries `response_meta.usage` = { credits (0 on a cache hit), proxy (the resolved",
360
- "tier \u2014 never `auto`), cache_hit } so you can see what the request cost."
327
+ //#endregion
328
+ //#region src/tools/scrape.ts
329
+ const DESCRIPTION$5 = [
330
+ "Fetch a single URL via the crawlbrulee scraping API and return the requested content",
331
+ "(markdown, cleaned HTML, raw HTML, links, images, screenshot, page metadata in `metadata`).",
332
+ "Use this for one-shot page extraction. For full-site discovery use the `map` tool first.",
333
+ "Screenshot URLs in the response are signed download links — the agent can fetch them when needed.",
334
+ "The response also carries `response_meta.usage` = { credits (0 on a cache hit), proxy (the resolved",
335
+ "tier — never `auto`), cache_hit } so you can see what the request cost."
361
336
  ].join(" ");
362
337
  function registerScrapeTool(server, getClient) {
363
- server.registerTool(
364
- "scrape",
365
- {
366
- title: "Scrape a URL",
367
- description: DESCRIPTION2,
368
- inputSchema: Schema_ApiScrapeRequest.shape,
369
- outputSchema: Schema_ApiScrapeSuccessResponse.shape
370
- },
371
- (args) => runTool(async () => await getClient().scrape(args))
372
- );
338
+ server.registerTool("scrape", {
339
+ title: "Scrape a URL",
340
+ description: DESCRIPTION$5,
341
+ inputSchema: Schema_ApiScrapeRequest.shape,
342
+ outputSchema: Schema_ApiScrapeSuccessResponse.shape
343
+ }, (args) => runTool(async () => await getClient().scrape(args)));
373
344
  }
374
- var Schema_AsyncScrapeWebhook = z.object({
375
- url: z.string().url().max(2048).describe(
376
- "Endpoint that receives a single signed POST when the job reaches a terminal state. Must be an http/https URL (HTTPS is required in production) of at most 2048 characters. The body is a `scrape.complete` envelope signed with your organization webhook secret on the X-Cwbl-Signature header."
377
- ),
378
- metadata: z.record(z.string(), z.unknown()).optional().describe(
379
- "Opaque correlation object echoed verbatim in the webhook payload\u2019s data.metadata. Must serialize to at most 2048 bytes (UTF-8 JSON). Use it to route deliveries without keeping your own job_id mapping."
380
- )
345
+
346
+ //#endregion
347
+ //#region src/schemas/ApiScrapeAsyncRequest.ts
348
+ const Schema_AsyncScrapeWebhook = z.object({
349
+ url: z.string().url().max(2048).describe("Endpoint that receives a single signed POST when the job reaches a terminal state. Must be an http/https URL (HTTPS is required in production) of at most 2048 characters. The body is a `scrape.complete` envelope signed with your organization webhook secret on the X-Cwbl-Signature header."),
350
+ metadata: z.record(z.string(), z.unknown()).optional().describe("Opaque correlation object echoed verbatim in the webhook payload’s data.metadata. Must serialize to at most 2048 bytes (UTF-8 JSON). Use it to route deliveries without keeping your own job_id mapping.")
381
351
  }).strict().describe("Optional per-job completion webhook delivered when this async job finishes");
382
- var Schema_ApiScrapeAsyncRequest = Schema_ApiScrapeRequest.extend({
383
- webhook: Schema_AsyncScrapeWebhook.optional().describe(
384
- "Completion webhook delivered when this async job finishes. Async-only: the synchronous `scrape` tool does not accept it."
385
- )
386
- });
387
- var ASYNC_JOB_STATUS_VALUES = ["pending", "running", "done", "failed"];
388
- var Schema_AsyncJobId = z.object({
389
- job_id: z.string().describe("Job identifier returned by the `scrape_async` tool")
390
- });
391
- var Schema_ApiScrapeAsyncResponse = z.object({
392
- job_id: z.string().describe("Job identifier \u2014 pass it to the `scrape_status` / `scrape_result` tools")
393
- });
394
- var Schema_ApiScrapeStatusResponse = z.object({
395
- job_id: z.string().describe("The job identifier"),
396
- status: z.enum(ASYNC_JOB_STATUS_VALUES).describe("Current state of the job (pending, running, done, failed)"),
397
- created_at: z.string().describe("ISO-8601 UTC timestamp when the job was created"),
398
- error: z.string().optional().describe("Error message if the job ended in `failed`"),
399
- response_meta: Schema_ApiResponseMeta.optional().describe(
400
- "Usage accounting for the finished job. Present only once the job is `done`; `response_meta.usage` reports credits charged (0 on a cache hit), the resolved proxy tier, and the cache-hit flag."
401
- )
352
+ const Schema_ApiScrapeAsyncRequest = Schema_ApiScrapeRequest.extend({ webhook: Schema_AsyncScrapeWebhook.optional().describe("Completion webhook delivered when this async job finishes. Async-only: the synchronous `scrape` tool does not accept it.") });
353
+
354
+ //#endregion
355
+ //#region src/schemas/ApiScrapeAsyncResponse.ts
356
+ const ASYNC_JOB_STATUS_VALUES = [
357
+ "pending",
358
+ "running",
359
+ "done",
360
+ "failed"
361
+ ];
362
+ const Schema_AsyncJobId = z.object({ job_id: z.string().describe("Job identifier returned by the `scrape_async` tool") });
363
+ const Schema_ApiScrapeAsyncResponse = z.object({ job_id: z.string().describe("Job identifier — pass it to the `scrape_status` / `scrape_result` tools") });
364
+ const Schema_ApiScrapeStatusResponse = z.object({
365
+ job_id: z.string().describe("The job identifier"),
366
+ status: z.enum(ASYNC_JOB_STATUS_VALUES).describe("Current state of the job (pending, running, done, failed)"),
367
+ created_at: z.string().describe("ISO-8601 UTC timestamp when the job was created"),
368
+ error: z.string().optional().describe("Error message if the job ended in `failed`"),
369
+ response_meta: Schema_ApiResponseMeta.optional().describe("Usage accounting for the finished job. Present only once the job is `done`; `response_meta.usage` reports credits charged (0 on a cache hit), the resolved proxy tier, and the cache-hit flag.")
402
370
  });
403
371
 
404
- // src/tools/scrapeAsync.ts
405
- var DESCRIPTION3 = [
406
- "Submit a scrape job to run ASYNCHRONOUSLY and return a `job_id` immediately,",
407
- "instead of holding the connection open. Use this for long-running scrapes",
408
- "(heavy JS rendering, full-page screenshots of long pages) \u2014 for a quick one-shot",
409
- "fetch prefer the synchronous `scrape` tool, which blocks and returns the page directly.",
410
- "Poll the job with `scrape_status` and fetch the page with `scrape_result` once done.",
411
- "Optionally attach a per-job completion `webhook`: we deliver a single",
412
- "signed `scrape.complete` POST to your endpoint when the job finishes (HTTPS required",
413
- "in production), and echoes your opaque `webhook.metadata` back in the delivery",
414
- "(under `data.metadata`, alongside `data.response_meta.usage`)."
372
+ //#endregion
373
+ //#region src/tools/scrapeAsync.ts
374
+ const DESCRIPTION$4 = [
375
+ "Submit a scrape job to run ASYNCHRONOUSLY and return a `job_id` immediately,",
376
+ "instead of holding the connection open. Use this for long-running scrapes",
377
+ "(heavy JS rendering, full-page screenshots of long pages) — for a quick one-shot",
378
+ "fetch prefer the synchronous `scrape` tool, which blocks and returns the page directly.",
379
+ "Poll the job with `scrape_status` and fetch the page with `scrape_result` once done.",
380
+ "Optionally attach a per-job completion `webhook`: we deliver a single",
381
+ "signed `scrape.complete` POST to your endpoint when the job finishes (HTTPS required",
382
+ "in production), and echoes your opaque `webhook.metadata` back in the delivery",
383
+ "(under `data.metadata`, alongside `data.response_meta.usage`)."
415
384
  ].join(" ");
416
385
  function registerScrapeAsyncTool(server, getClient) {
417
- server.registerTool(
418
- "scrape_async",
419
- {
420
- title: "Scrape a URL asynchronously",
421
- description: DESCRIPTION3,
422
- inputSchema: Schema_ApiScrapeAsyncRequest.shape,
423
- outputSchema: Schema_ApiScrapeAsyncResponse.shape
424
- },
425
- (args) => runTool(
426
- async () => await getClient().scrapeAsync(args)
427
- )
428
- );
386
+ server.registerTool("scrape_async", {
387
+ title: "Scrape a URL asynchronously",
388
+ description: DESCRIPTION$4,
389
+ inputSchema: Schema_ApiScrapeAsyncRequest.shape,
390
+ outputSchema: Schema_ApiScrapeAsyncResponse.shape
391
+ }, (args) => runTool(async () => await getClient().scrapeAsync(args)));
429
392
  }
430
393
 
431
- // src/tools/scrapeResult.ts
432
- var DESCRIPTION4 = [
433
- "Fetch the extracted content of a completed async scrape job (the same result shape as the",
434
- "synchronous `scrape` tool: markdown, cleaned HTML, raw HTML, links, images, screenshot,",
435
- "page metadata in `metadata`, and `response_meta.usage`). Errors if the job is still",
436
- "`pending`/`running` \u2014 check `scrape_status` first (status `done`) before calling this.",
437
- "Screenshot URLs are signed download links."
394
+ //#endregion
395
+ //#region src/tools/scrapeResult.ts
396
+ const DESCRIPTION$3 = [
397
+ "Fetch the extracted content of a completed async scrape job (the same result shape as the",
398
+ "synchronous `scrape` tool: markdown, cleaned HTML, raw HTML, links, images, screenshot,",
399
+ "page metadata in `metadata`, and `response_meta.usage`). Errors if the job is still",
400
+ "`pending`/`running` — check `scrape_status` first (status `done`) before calling this.",
401
+ "Screenshot URLs are signed download links."
438
402
  ].join(" ");
439
403
  function registerScrapeResultTool(server, getClient) {
440
- server.registerTool(
441
- "scrape_result",
442
- {
443
- title: "Get an async scrape job result",
444
- description: DESCRIPTION4,
445
- inputSchema: Schema_AsyncJobId.shape,
446
- outputSchema: Schema_ApiScrapeSuccessResponse.shape
447
- },
448
- (args) => runTool(
449
- async () => await getClient().getScrapeResult(args.job_id)
450
- )
451
- );
404
+ server.registerTool("scrape_result", {
405
+ title: "Get an async scrape job result",
406
+ description: DESCRIPTION$3,
407
+ inputSchema: Schema_AsyncJobId.shape,
408
+ outputSchema: Schema_ApiScrapeSuccessResponse.shape
409
+ }, (args) => runTool(async () => await getClient().getScrapeResult(args.job_id)));
452
410
  }
453
411
 
454
- // src/tools/scrapeStatus.ts
455
- var DESCRIPTION5 = [
456
- "Look up the current lifecycle status of an async scrape job submitted via `scrape_async`.",
457
- "Returns the job state (`pending`, `running`, `done`, `failed`), with an `error` message",
458
- "when it failed and a `response_meta.usage` block (credits, resolved proxy tier, cache_hit) once it is",
459
- "`done`. Poll this until the status is `done`, then call `scrape_result` to fetch",
460
- "the page. If you registered a completion webhook on submit you can skip polling and react",
461
- "to the delivery instead."
412
+ //#endregion
413
+ //#region src/tools/scrapeStatus.ts
414
+ const DESCRIPTION$2 = [
415
+ "Look up the current lifecycle status of an async scrape job submitted via `scrape_async`.",
416
+ "Returns the job state (`pending`, `running`, `done`, `failed`), with an `error` message",
417
+ "when it failed and a `response_meta.usage` block (credits, resolved proxy tier, cache_hit) once it is",
418
+ "`done`. Poll this until the status is `done`, then call `scrape_result` to fetch",
419
+ "the page. If you registered a completion webhook on submit you can skip polling and react",
420
+ "to the delivery instead."
462
421
  ].join(" ");
463
422
  function registerScrapeStatusTool(server, getClient) {
464
- server.registerTool(
465
- "scrape_status",
466
- {
467
- title: "Check an async scrape job status",
468
- description: DESCRIPTION5,
469
- inputSchema: Schema_AsyncJobId.shape,
470
- outputSchema: Schema_ApiScrapeStatusResponse.shape
471
- },
472
- (args) => (
473
- // The SDK's `AsyncJobStatusResponse` is snake_case (job_id, created_at),
474
- // matching the vendored status schema 1:1, so a direct cast lines the SDK
475
- // return type up with the tool's output schema.
476
- runTool(
477
- async () => await getClient().getScrapeStatus(args.job_id)
478
- )
479
- )
480
- );
423
+ server.registerTool("scrape_status", {
424
+ title: "Check an async scrape job status",
425
+ description: DESCRIPTION$2,
426
+ inputSchema: Schema_AsyncJobId.shape,
427
+ outputSchema: Schema_ApiScrapeStatusResponse.shape
428
+ }, (args) => runTool(async () => await getClient().getScrapeStatus(args.job_id)));
481
429
  }
482
- var Schema_ApiUsageResponse = z.object({
483
- total_credits: z.number().int().nonnegative().describe(
484
- "Total credits available for the current billing cycle (plan base + purchased + gifted)."
485
- ),
486
- used_credits: z.number().int().nonnegative().describe(
487
- "Credits spent so far in the current billing cycle. May exceed total_credits on plans that allow overages."
488
- ),
489
- available_credits: z.number().int().nonnegative().describe(
490
- "Remaining credits (max(0, total_credits - used_credits)). Clamped to 0 when in overage."
491
- ),
492
- used_quota_percent: z.number().nonnegative().describe(
493
- "Percentage of total_credits used in the current cycle, rounded to 1 decimal. Not capped \u2014 values >100 indicate overage."
494
- ),
495
- max_concurrency: z.number().int().nonnegative().describe(
496
- "Maximum number of concurrent jobs allowed for this organization (plan base + purchased + gifted extras)."
497
- ),
498
- usage_reset: z.string().datetime().describe(
499
- "ISO 8601 UTC timestamp when the current billing cycle ends and used_credits resets."
500
- )
430
+
431
+ //#endregion
432
+ //#region src/schemas/ApiUsageResponse.ts
433
+ const Schema_ApiUsageResponse = z.object({
434
+ total_credits: z.number().int().nonnegative().describe("Total credits available for the current billing cycle (plan base + purchased + gifted)."),
435
+ used_credits: z.number().int().nonnegative().describe("Credits spent so far in the current billing cycle. May exceed total_credits on plans that allow overages."),
436
+ available_credits: z.number().int().nonnegative().describe("Remaining credits (max(0, total_credits - used_credits)). Clamped to 0 when in overage."),
437
+ used_quota_percent: z.number().nonnegative().describe("Percentage of total_credits used in the current cycle, rounded to 1 decimal. Not capped — values >100 indicate overage."),
438
+ max_concurrency: z.number().int().nonnegative().describe("Maximum number of concurrent jobs allowed for this organization (plan base + purchased + gifted extras)."),
439
+ usage_reset: z.string().datetime().describe("ISO 8601 UTC timestamp when the current billing cycle ends and used_credits resets.")
501
440
  });
502
441
 
503
- // src/tools/usage.ts
504
- var DESCRIPTION6 = [
505
- "Return the current billing-cycle usage for the authenticated organization:",
506
- "total / used / available credits, used quota percent, max concurrency, and cycle reset time.",
507
- "Call this before launching large scrape jobs to confirm available credit."
442
+ //#endregion
443
+ //#region src/tools/usage.ts
444
+ const DESCRIPTION$1 = [
445
+ "Return the current billing-cycle usage for the authenticated organization:",
446
+ "total / used / available credits, used quota percent, max concurrency, and cycle reset time.",
447
+ "Call this before launching large scrape jobs to confirm available credit."
508
448
  ].join(" ");
509
449
  function registerUsageTool(server, getClient) {
510
- server.registerTool(
511
- "usage",
512
- {
513
- title: "Get current usage",
514
- description: DESCRIPTION6,
515
- inputSchema: {},
516
- outputSchema: Schema_ApiUsageResponse.shape
517
- },
518
- () => runTool(async () => await getClient().usage())
519
- );
450
+ server.registerTool("usage", {
451
+ title: "Get current usage",
452
+ description: DESCRIPTION$1,
453
+ inputSchema: {},
454
+ outputSchema: Schema_ApiUsageResponse.shape
455
+ }, () => runTool(async () => await getClient().usage()));
520
456
  }
521
- var Schema_ApiWhoamiResponse = z.object({
522
- organization_name: z.string().describe("Display name of the organization that owns the token."),
523
- token_name: z.string().describe("User-assigned name of the API token authenticating the request."),
524
- token_preview: z.string().describe(
525
- "Truncated preview of the API token (e.g. `cwbl_\u2026xyz`). Safe to display; does not authenticate."
526
- )
457
+
458
+ //#endregion
459
+ //#region src/schemas/ApiWhoamiResponse.ts
460
+ const Schema_ApiWhoamiResponse = z.object({
461
+ organization_name: z.string().describe("Display name of the organization that owns the token."),
462
+ token_name: z.string().describe("User-assigned name of the API token authenticating the request."),
463
+ token_preview: z.string().describe("Truncated preview of the API token (e.g. `cwbl_…xyz`). Safe to display; does not authenticate.")
527
464
  });
528
465
 
529
- // src/tools/whoami.ts
530
- var DESCRIPTION7 = [
531
- "Return the organization name, token name, and truncated token preview for the API key",
532
- "currently configured on the MCP server. Useful for confirming which account is in use",
533
- "before performing credit-consuming operations."
466
+ //#endregion
467
+ //#region src/tools/whoami.ts
468
+ const DESCRIPTION = [
469
+ "Return the organization name, token name, and truncated token preview for the API key",
470
+ "currently configured on the MCP server. Useful for confirming which account is in use",
471
+ "before performing credit-consuming operations."
534
472
  ].join(" ");
535
473
  function registerWhoamiTool(server, getClient) {
536
- server.registerTool(
537
- "whoami",
538
- {
539
- title: "Identify the API token",
540
- description: DESCRIPTION7,
541
- inputSchema: {},
542
- outputSchema: Schema_ApiWhoamiResponse.shape
543
- },
544
- () => runTool(async () => await getClient().whoami())
545
- );
474
+ server.registerTool("whoami", {
475
+ title: "Identify the API token",
476
+ description: DESCRIPTION,
477
+ inputSchema: {},
478
+ outputSchema: Schema_ApiWhoamiResponse.shape
479
+ }, () => runTool(async () => await getClient().whoami()));
546
480
  }
547
481
 
548
- // src/version.ts
549
- var SERVER_NAME = "crawlbrulee";
550
- var SERVER_VERSION = "0.5.0";
482
+ //#endregion
483
+ //#region src/version.ts
484
+ const SERVER_NAME = "crawlbrulee";
485
+ const SERVER_VERSION = "0.5.0";
551
486
 
552
- // src/server.ts
487
+ //#endregion
488
+ //#region src/server.ts
489
+ /**
490
+ * Build a configured `McpServer` instance with all crawlbrulee tools
491
+ * registered. Pure factory — no I/O — so it can be reused under different
492
+ * transports (currently only stdio).
493
+ *
494
+ * Pass `clientFactory` from tests to inject a stubbed SDK client.
495
+ */
553
496
  function buildServer(clientFactory = createDefaultClientFactory()) {
554
- const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION });
555
- registerScrapeTool(server, clientFactory);
556
- registerScrapeAsyncTool(server, clientFactory);
557
- registerScrapeStatusTool(server, clientFactory);
558
- registerScrapeResultTool(server, clientFactory);
559
- registerMapTool(server, clientFactory);
560
- registerUsageTool(server, clientFactory);
561
- registerWhoamiTool(server, clientFactory);
562
- return server;
497
+ const server = new McpServer({
498
+ name: SERVER_NAME,
499
+ version: SERVER_VERSION
500
+ });
501
+ registerScrapeTool(server, clientFactory);
502
+ registerScrapeAsyncTool(server, clientFactory);
503
+ registerScrapeStatusTool(server, clientFactory);
504
+ registerScrapeResultTool(server, clientFactory);
505
+ registerMapTool(server, clientFactory);
506
+ registerUsageTool(server, clientFactory);
507
+ registerWhoamiTool(server, clientFactory);
508
+ return server;
563
509
  }
564
510
 
565
- // src/index.ts
511
+ //#endregion
512
+ //#region src/index.ts
566
513
  async function main() {
567
- const server = buildServer();
568
- const transport = new StdioServerTransport();
569
- await server.connect(transport);
514
+ const server = buildServer();
515
+ const transport = new StdioServerTransport();
516
+ await server.connect(transport);
570
517
  }
571
518
  main().catch((err) => {
572
- const message = err instanceof Error ? err.message : String(err);
573
- process.stderr.write(`crawlbrulee-mcp: fatal: ${message}
574
- `);
575
- process.exit(1);
519
+ const message = err instanceof Error ? err.message : String(err);
520
+ process.stderr.write(`crawlbrulee-mcp: fatal: ${message}\n`);
521
+ process.exit(1);
576
522
  });
523
+
524
+ //#endregion
525
+ export { };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlbrulee/mcp",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Official MCP server for the crawlbrulee API — scrape and map URLs from MCP-aware agents (Claude Code, Codex, Cursor).",
5
5
  "keywords": [
6
6
  "crawlbrulee",
@@ -42,8 +42,8 @@
42
42
  "access": "public"
43
43
  },
44
44
  "scripts": {
45
- "build": "tsup",
46
- "dev": "tsup --watch",
45
+ "build": "tsdown",
46
+ "dev": "tsdown --watch",
47
47
  "test": "vitest run",
48
48
  "test:watch": "vitest",
49
49
  "typecheck": "tsc --noEmit",
@@ -64,9 +64,9 @@
64
64
  "@types/node": "^22.10.0",
65
65
  "eslint": "^9.18.0",
66
66
  "prettier": "^3.4.0",
67
- "tsup": "^8.3.0",
68
- "typescript": "^5.7.0",
69
- "typescript-eslint": "^8.20.0",
67
+ "tsdown": "^0.22.11",
68
+ "typescript": "^6.0.3",
69
+ "typescript-eslint": "^8.64.0",
70
70
  "vitest": "^3.2.6"
71
71
  }
72
72
  }