@crawlbrulee/mcp 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +442 -490
  2. package/package.json +6 -6
package/dist/index.js CHANGED
@@ -1,576 +1,528 @@
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")
155
+ const Schema_ApiScrapeCache = z.object({
156
+ 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"),
157
+ ignore_query_params: z.boolean().default(false).describe("Treat URLs with different query parameters as the same cache entry")
136
158
  }).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
- )
159
+ const Schema_ApiScrapeExtract = z.object({
160
+ metadata: z.boolean().default(true).describe("Extract page metadata (title, description, OG tags, etc.)"),
161
+ cleaned_html: z.boolean().default(true).describe("Extract cleaned HTML (main content only)"),
162
+ markdown: z.boolean().default(false).describe("Extract page content as clean Markdown"),
163
+ raw_html: z.boolean().default(false).describe("Return the raw, unprocessed HTML"),
164
+ links: z.boolean().default(false).describe("Extract all links found on the page"),
165
+ images: z.boolean().default(false).describe("Extract all inline images found on the page"),
166
+ screenshot: Schema_ApiScrapeFormatScreenshot.optional().describe("Capture a screenshot of the page")
147
167
  }).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
- )
168
+ const Schema_ApiScrapeLocation = z.object({
169
+ 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"),
170
+ 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
171
  }).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()
172
+ const Schema_ApiScrapeRequest = z.object({
173
+ url: z.string().describe("The URL to scrape"),
174
+ extract: Schema_ApiScrapeExtract.prefault({}).describe("Which content formats to extract. Defaults to metadata + cleaned_html."),
175
+ cache: Schema_ApiScrapeCache.optional().describe("Cache settings for this request"),
176
+ require_js: z.boolean().default(false).describe("Use a headless browser to render JavaScript before scraping"),
177
+ exclude_selectors: z.array(z.string()).optional().describe("CSS selectors to exclude from the extracted content"),
178
+ proxy: Schema_ApiProxyType.describe("Proxy tier to use for fetching"),
179
+ location: Schema_ApiScrapeLocation.optional()
169
180
  }).strict();
170
181
 
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)")
182
+ //#endregion
183
+ //#region src/schemas/ApiMapRequest.ts
184
+ 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");
185
+ const DEFAULT_API_MAP_CACHE_MAX_AGE_SECONDS = 10080 * 60;
186
+ const DEFAULT_API_MAP_MAX_URLS = 1e5;
187
+ const MAX_API_MAP_MAX_URLS = 1e5;
188
+ const DEFAULT_API_MAP_PAGE_LIMIT = 1e4;
189
+ const MAX_API_MAP_PAGE_LIMIT = 1e4;
190
+ const Schema_ApiMapTypes = z.object({
191
+ internal: z.boolean().default(true).describe("Include internal links (same domain)"),
192
+ internal_subdomains: z.boolean().default(true).describe("Include links to subdomains of the target domain"),
193
+ external: z.boolean().default(true).describe("Include external links (different domains)")
189
194
  }).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()
195
+ 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");
196
+ const Schema_ApiMapRequest = z.object({
197
+ url: z.string().describe("The website URL to map"),
198
+ proxy: Schema_ApiProxyType.default("auto").describe("Proxy tier to use for fetching"),
199
+ sitemap_only: z.boolean().default(false).describe("Only use sitemap.xml — skip homepage link extraction"),
200
+ types: Schema_ApiMapTypes.optional().describe("Filter which link types to include"),
201
+ cache: Schema_ApiMapCache.optional().describe("Cache settings for this request"),
202
+ 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"),
203
+ page: z.number().int().positive().default(1).describe("Page number for paginated results"),
204
+ 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"),
205
+ location: Schema_ApiMapLocation.optional()
203
206
  });
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")
207
+
208
+ //#endregion
209
+ //#region src/schemas/ApiScrapeResponse.ts
210
+ const Schema_ApiViewport = z.object({
211
+ width: z.number().describe("Viewport width in pixels"),
212
+ height: z.number().describe("Viewport height in pixels"),
213
+ device_scale_factor: z.number().describe("Device pixel ratio used for the capture")
215
214
  });
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")
215
+ const Schema_ApiScreenshotProperties = z.object({
216
+ file_name: z.string().describe("File name of the screenshot image"),
217
+ mime: z.string().describe("MIME type of the screenshot (e.g. image/png)"),
218
+ width: z.number().describe("Image width in pixels"),
219
+ height: z.number().describe("Image height in pixels"),
220
+ viewport: Schema_ApiViewport.describe("Viewport dimensions used during capture")
221
221
  });
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)")
222
+ const Schema_ApiScreenshotSlice = z.object({
223
+ row_nr: z.number().describe("Row index of this slice (0-based)"),
224
+ url: z.string().describe("URL to download this slice image"),
225
+ type: z.literal("slice").describe("Slice type identifier"),
226
+ properties: Schema_ApiScreenshotProperties.describe("Image properties for this slice")
227
227
  });
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")
228
+ const Schema_ApiScreenshotResponse = z.object({
229
+ url: z.string().describe("URL to download the full screenshot image"),
230
+ type: Schema_ApiScrapeScreenshotType.describe("Screenshot capture mode that was used"),
231
+ properties: Schema_ApiScreenshotProperties.describe("Image properties for the full screenshot"),
232
+ slices: z.array(Schema_ApiScreenshotSlice).optional().describe("Individual tile slices (present when slice action_after was requested)")
231
233
  });
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")
234
+ const Schema_ApiPageInlineImgItem = z.object({
235
+ url: z.string().describe("Absolute URL of the image"),
236
+ alt: z.string().nullable().describe("Alt text of the image, or null if not set")
236
237
  });
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`).")
238
+ const Schema_ApiPageLink = z.object({
239
+ text: z.string().describe("Anchor text of the link"),
240
+ href: z.string().describe("The link URL as it appears on the page (absolute or relative)"),
241
+ internal: z.boolean().describe("Whether the link points to the same domain")
244
242
  });
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
- )
243
+ const API_RESOLVED_PROXY_TIER_VALUES = ["basic", "advanced"];
244
+ const Schema_ApiUsageMeta = z.object({
245
+ credits: z.number().int().nonnegative().describe("Credits charged for this request. `0` on a cache hit (no fresh fetch was billed)."),
246
+ 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`)."),
247
+ cache_hit: z.boolean().describe("Whether the result was served from cache (`true`) or freshly fetched (`false`).")
249
248
  });
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)")
249
+ const Schema_ApiResponseMeta = z.object({ usage: Schema_ApiUsageMeta.describe("Usage accounting for this request: credits charged, resolved proxy tier, and cache-hit flag.") });
250
+ const 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)")
273
273
  });
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
- )
274
+ const 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("Screenshot of the page, if requested"),
284
+ metadata: Schema_ApiScrapeMeta.optional().describe("Extracted page metadata (title, OG tags, etc.)"),
285
+ 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."),
286
+ 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
287
  });
296
288
 
297
- // src/schemas/ApiMapResponse.ts
298
- var Schema_ApiMapLinkItem = z.object({
299
- url: z.string().describe("The discovered URL")
289
+ //#endregion
290
+ //#region src/schemas/ApiMapResponse.ts
291
+ const Schema_ApiMapLinkItem = z.object({ url: z.string().describe("The discovered URL") });
292
+ const Schema_ApiMapPagination = z.object({
293
+ page: z.number().int().positive().describe("Current page number"),
294
+ limit: z.number().int().positive().describe("Number of items per page"),
295
+ total: z.number().int().nonnegative().describe("Total number of URLs in the map"),
296
+ total_pages: z.number().int().nonnegative().describe("Total number of pages available"),
297
+ has_more: z.boolean().describe("Whether more pages are available")
300
298
  });
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")
299
+ const Schema_ApiMapTruncation = z.object({
300
+ storage_capped: z.boolean().describe("Whether the stored map was capped by the max_urls limit"),
301
+ response_capped: z.boolean().describe("Whether the response was capped by pagination"),
302
+ total_before_max_urls: z.number().int().nonnegative().describe("Total URLs found before applying the max_urls cap"),
303
+ total_detected_before_storage_cap: z.number().int().nonnegative().describe("Total URLs detected during discovery before the storage cap was applied")
307
304
  });
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")
305
+ const Schema_ApiMapResult = z.object({
306
+ links: z.array(Schema_ApiMapLinkItem).describe("List of discovered URLs for the current page"),
307
+ response_meta: z.object({
308
+ pagination: Schema_ApiMapPagination.describe("Pagination details for the result set"),
309
+ truncation: Schema_ApiMapTruncation.describe("Information about whether the results were truncated"),
310
+ 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.")
311
+ }).describe("Response metadata including pagination, truncation, and usage info")
325
312
  });
326
313
 
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."
314
+ //#endregion
315
+ //#region src/tools/map.ts
316
+ const DESCRIPTION$6 = [
317
+ "Build (or fetch a cached) link-map for a website by combining sitemap discovery with homepage",
318
+ "link extraction. Returns paginated lists of discovered URLs. Filterable by link type",
319
+ "(internal / external / subdomain). Use this to enumerate a site before scraping selected pages."
332
320
  ].join(" ");
333
321
  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
- );
322
+ server.registerTool("map", {
323
+ title: "Map a website",
324
+ description: DESCRIPTION$6,
325
+ inputSchema: Schema_ApiMapRequest.shape,
326
+ outputSchema: Schema_ApiMapResult.shape
327
+ }, (args) => runTool(async () => await getClient().map(args)));
351
328
  }
352
329
 
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."
330
+ //#endregion
331
+ //#region src/tools/scrape.ts
332
+ const DESCRIPTION$5 = [
333
+ "Fetch a single URL via the crawlbrulee scraping API and return the requested content",
334
+ "(markdown, cleaned HTML, raw HTML, links, images, screenshot, page metadata in `metadata`).",
335
+ "Use this for one-shot page extraction. For full-site discovery use the `map` tool first.",
336
+ "Screenshot URLs in the response are signed download links — the agent can fetch them when needed.",
337
+ "The response also carries `response_meta.usage` = { credits (0 on a cache hit), proxy (the resolved",
338
+ "tier — never `auto`), cache_hit } so you can see what the request cost."
361
339
  ].join(" ");
362
340
  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
- );
341
+ server.registerTool("scrape", {
342
+ title: "Scrape a URL",
343
+ description: DESCRIPTION$5,
344
+ inputSchema: Schema_ApiScrapeRequest.shape,
345
+ outputSchema: Schema_ApiScrapeSuccessResponse.shape
346
+ }, (args) => runTool(async () => await getClient().scrape(args)));
373
347
  }
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
- )
348
+
349
+ //#endregion
350
+ //#region src/schemas/ApiScrapeAsyncRequest.ts
351
+ const Schema_AsyncScrapeWebhook = z.object({
352
+ 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."),
353
+ 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
354
  }).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
- )
355
+ 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.") });
356
+
357
+ //#endregion
358
+ //#region src/schemas/ApiScrapeAsyncResponse.ts
359
+ const ASYNC_JOB_STATUS_VALUES = [
360
+ "pending",
361
+ "running",
362
+ "done",
363
+ "failed"
364
+ ];
365
+ const Schema_AsyncJobId = z.object({ job_id: z.string().describe("Job identifier returned by the `scrape_async` tool") });
366
+ const Schema_ApiScrapeAsyncResponse = z.object({ job_id: z.string().describe("Job identifier — pass it to the `scrape_status` / `scrape_result` tools") });
367
+ const Schema_ApiScrapeStatusResponse = z.object({
368
+ job_id: z.string().describe("The job identifier"),
369
+ status: z.enum(ASYNC_JOB_STATUS_VALUES).describe("Current state of the job (pending, running, done, failed)"),
370
+ created_at: z.string().describe("ISO-8601 UTC timestamp when the job was created"),
371
+ error: z.string().optional().describe("Error message if the job ended in `failed`"),
372
+ 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
373
  });
403
374
 
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`)."
375
+ //#endregion
376
+ //#region src/tools/scrapeAsync.ts
377
+ const DESCRIPTION$4 = [
378
+ "Submit a scrape job to run ASYNCHRONOUSLY and return a `job_id` immediately,",
379
+ "instead of holding the connection open. Use this for long-running scrapes",
380
+ "(heavy JS rendering, full-page screenshots of long pages) — for a quick one-shot",
381
+ "fetch prefer the synchronous `scrape` tool, which blocks and returns the page directly.",
382
+ "Poll the job with `scrape_status` and fetch the page with `scrape_result` once done.",
383
+ "Optionally attach a per-job completion `webhook`: we deliver a single",
384
+ "signed `scrape.complete` POST to your endpoint when the job finishes (HTTPS required",
385
+ "in production), and echoes your opaque `webhook.metadata` back in the delivery",
386
+ "(under `data.metadata`, alongside `data.response_meta.usage`)."
415
387
  ].join(" ");
416
388
  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
- );
389
+ server.registerTool("scrape_async", {
390
+ title: "Scrape a URL asynchronously",
391
+ description: DESCRIPTION$4,
392
+ inputSchema: Schema_ApiScrapeAsyncRequest.shape,
393
+ outputSchema: Schema_ApiScrapeAsyncResponse.shape
394
+ }, (args) => runTool(async () => await getClient().scrapeAsync(args)));
429
395
  }
430
396
 
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."
397
+ //#endregion
398
+ //#region src/tools/scrapeResult.ts
399
+ const DESCRIPTION$3 = [
400
+ "Fetch the extracted content of a completed async scrape job (the same result shape as the",
401
+ "synchronous `scrape` tool: markdown, cleaned HTML, raw HTML, links, images, screenshot,",
402
+ "page metadata in `metadata`, and `response_meta.usage`). Errors if the job is still",
403
+ "`pending`/`running` — check `scrape_status` first (status `done`) before calling this.",
404
+ "Screenshot URLs are signed download links."
438
405
  ].join(" ");
439
406
  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
- );
407
+ server.registerTool("scrape_result", {
408
+ title: "Get an async scrape job result",
409
+ description: DESCRIPTION$3,
410
+ inputSchema: Schema_AsyncJobId.shape,
411
+ outputSchema: Schema_ApiScrapeSuccessResponse.shape
412
+ }, (args) => runTool(async () => await getClient().getScrapeResult(args.job_id)));
452
413
  }
453
414
 
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."
415
+ //#endregion
416
+ //#region src/tools/scrapeStatus.ts
417
+ const DESCRIPTION$2 = [
418
+ "Look up the current lifecycle status of an async scrape job submitted via `scrape_async`.",
419
+ "Returns the job state (`pending`, `running`, `done`, `failed`), with an `error` message",
420
+ "when it failed and a `response_meta.usage` block (credits, resolved proxy tier, cache_hit) once it is",
421
+ "`done`. Poll this until the status is `done`, then call `scrape_result` to fetch",
422
+ "the page. If you registered a completion webhook on submit you can skip polling and react",
423
+ "to the delivery instead."
462
424
  ].join(" ");
463
425
  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
- );
426
+ server.registerTool("scrape_status", {
427
+ title: "Check an async scrape job status",
428
+ description: DESCRIPTION$2,
429
+ inputSchema: Schema_AsyncJobId.shape,
430
+ outputSchema: Schema_ApiScrapeStatusResponse.shape
431
+ }, (args) => runTool(async () => await getClient().getScrapeStatus(args.job_id)));
481
432
  }
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
- )
433
+
434
+ //#endregion
435
+ //#region src/schemas/ApiUsageResponse.ts
436
+ const Schema_ApiUsageResponse = z.object({
437
+ total_credits: z.number().int().nonnegative().describe("Total credits available for the current billing cycle (plan base + purchased + gifted)."),
438
+ 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."),
439
+ available_credits: z.number().int().nonnegative().describe("Remaining credits (max(0, total_credits - used_credits)). Clamped to 0 when in overage."),
440
+ 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."),
441
+ max_concurrency: z.number().int().nonnegative().describe("Maximum number of concurrent jobs allowed for this organization (plan base + purchased + gifted extras)."),
442
+ usage_reset: z.string().datetime().describe("ISO 8601 UTC timestamp when the current billing cycle ends and used_credits resets.")
501
443
  });
502
444
 
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."
445
+ //#endregion
446
+ //#region src/tools/usage.ts
447
+ const DESCRIPTION$1 = [
448
+ "Return the current billing-cycle usage for the authenticated organization:",
449
+ "total / used / available credits, used quota percent, max concurrency, and cycle reset time.",
450
+ "Call this before launching large scrape jobs to confirm available credit."
508
451
  ].join(" ");
509
452
  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
- );
453
+ server.registerTool("usage", {
454
+ title: "Get current usage",
455
+ description: DESCRIPTION$1,
456
+ inputSchema: {},
457
+ outputSchema: Schema_ApiUsageResponse.shape
458
+ }, () => runTool(async () => await getClient().usage()));
520
459
  }
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
- )
460
+
461
+ //#endregion
462
+ //#region src/schemas/ApiWhoamiResponse.ts
463
+ const Schema_ApiWhoamiResponse = z.object({
464
+ organization_name: z.string().describe("Display name of the organization that owns the token."),
465
+ token_name: z.string().describe("User-assigned name of the API token authenticating the request."),
466
+ token_preview: z.string().describe("Truncated preview of the API token (e.g. `cwbl_…xyz`). Safe to display; does not authenticate.")
527
467
  });
528
468
 
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."
469
+ //#endregion
470
+ //#region src/tools/whoami.ts
471
+ const DESCRIPTION = [
472
+ "Return the organization name, token name, and truncated token preview for the API key",
473
+ "currently configured on the MCP server. Useful for confirming which account is in use",
474
+ "before performing credit-consuming operations."
534
475
  ].join(" ");
535
476
  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
- );
477
+ server.registerTool("whoami", {
478
+ title: "Identify the API token",
479
+ description: DESCRIPTION,
480
+ inputSchema: {},
481
+ outputSchema: Schema_ApiWhoamiResponse.shape
482
+ }, () => runTool(async () => await getClient().whoami()));
546
483
  }
547
484
 
548
- // src/version.ts
549
- var SERVER_NAME = "crawlbrulee";
550
- var SERVER_VERSION = "0.5.0";
485
+ //#endregion
486
+ //#region src/version.ts
487
+ const SERVER_NAME = "crawlbrulee";
488
+ const SERVER_VERSION = "0.5.0";
551
489
 
552
- // src/server.ts
490
+ //#endregion
491
+ //#region src/server.ts
492
+ /**
493
+ * Build a configured `McpServer` instance with all crawlbrulee tools
494
+ * registered. Pure factory — no I/O — so it can be reused under different
495
+ * transports (currently only stdio).
496
+ *
497
+ * Pass `clientFactory` from tests to inject a stubbed SDK client.
498
+ */
553
499
  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;
500
+ const server = new McpServer({
501
+ name: SERVER_NAME,
502
+ version: SERVER_VERSION
503
+ });
504
+ registerScrapeTool(server, clientFactory);
505
+ registerScrapeAsyncTool(server, clientFactory);
506
+ registerScrapeStatusTool(server, clientFactory);
507
+ registerScrapeResultTool(server, clientFactory);
508
+ registerMapTool(server, clientFactory);
509
+ registerUsageTool(server, clientFactory);
510
+ registerWhoamiTool(server, clientFactory);
511
+ return server;
563
512
  }
564
513
 
565
- // src/index.ts
514
+ //#endregion
515
+ //#region src/index.ts
566
516
  async function main() {
567
- const server = buildServer();
568
- const transport = new StdioServerTransport();
569
- await server.connect(transport);
517
+ const server = buildServer();
518
+ const transport = new StdioServerTransport();
519
+ await server.connect(transport);
570
520
  }
571
521
  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);
522
+ const message = err instanceof Error ? err.message : String(err);
523
+ process.stderr.write(`crawlbrulee-mcp: fatal: ${message}\n`);
524
+ process.exit(1);
576
525
  });
526
+
527
+ //#endregion
528
+ export { };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlbrulee/mcp",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
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
  }