@hunt-labs/bytekit-mcp 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,100 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@hunt-labs/bytekit-mcp` are documented here.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ This file records only the delta between versions. For how to use the package
9
+ today, see [README.md](./README.md), which remains the authoritative usage guide.
10
+
11
+ ## [0.2.0] - 2026-07-21
12
+
13
+ ### Removed (**BREAKING**)
14
+
15
+ - The legacy `RAPIDCRAWL_API_KEY` environment-variable fallback (kept as a
16
+ one-minor-version bridge in #2421) is removed. Use `BYTEKIT_API_KEY` (or the
17
+ `--api-key` flag). (#2473)
18
+
19
+ ### Fixed
20
+
21
+ - Tool-surface drift against the live API (#2477):
22
+ - `screenshot_url`'s `device` enum is now `desktop` / `mobile` — `tablet` was
23
+ 422-rejected by the API.
24
+ - Screenshot results render the spec field names (`image_width`,
25
+ `image_height`, `file_size_bytes`); the removed `format` field is gone.
26
+ - `get_result` renders a failed job's envelope (`Status: failed` +
27
+ `error.code`/`error.message`) instead of `undefined` lines, and omits
28
+ `Credits: null` for pending rows.
29
+ - `get_account` no longer renders `Account: null` when the account has no
30
+ name.
31
+ - `get_doc`'s description example uses a real bundle key.
32
+ - Server errors now surface diagnostics instead of a generic failure: any
33
+ non-2xx with a parseable API envelope renders its `code` + `message`
34
+ (e.g. 503 `blocked`, 400 `invalid_url`), 422 includes `error.details`, and
35
+ `Retry-After` (including HTTP-date or garbage values) is parsed to a bounded
36
+ retry delay instead of `setTimeout(NaN)`. Specific 401/402/429 mappings still
37
+ win. (#2478)
38
+
39
+ ### Changed
40
+
41
+ - The bundled offline docs (`get_doc`/`list_docs`/`search_docs`) are
42
+ regenerated: 96 pages, now including the TypeScript SDK `usage` and
43
+ `webhooks` reference pages and dropping removed content. (#2469)
44
+
45
+ ## [0.1.3] - 2026-07-16
46
+
47
+ ### Changed (**BREAKING**)
48
+
49
+ - The MCP tool `web-search` is renamed to `web_search` (snake_case, consistent
50
+ with every other tool). MCP clients bound to the old `web-search` name must
51
+ update. (#2421)
52
+
53
+ ### Changed
54
+
55
+ - The 401 error message now references `BYTEKIT_API_KEY`; `--base-url` now falls
56
+ back to the `BYTEKIT_BASE_URL` environment variable when no flag is passed. (#2421)
57
+
58
+ ### Fixed
59
+
60
+ - The bundled offline docs (`get_doc`/`list_docs`/`search_docs`) now teach the
61
+ correct `@hunt-labs/bytekit-sdk` install/import name instead of the dead
62
+ `@bytekit/sdk` scope. (#2449)
63
+
64
+ ## [0.1.2] - 2026-07-15
65
+
66
+ ### Fixed
67
+
68
+ - `scrape_url` now reads the snake_case envelope fields the API actually returns
69
+ (`id`, `final_url`, `status_code`); the published 0.1.1 tarball read the old
70
+ camelCase fields (`scrapeId`, `finalUrl`, `statusCode`), so every metadata line
71
+ rendered `undefined` (#2419).
72
+ - The MCP handshake `serverInfo.version` is now derived from `package.json` instead
73
+ of a hardcoded literal, so it can never drift from the published version (#2419).
74
+
75
+ ### Changed
76
+
77
+ - Compiled test code and fixtures are excluded from the published tarball — only
78
+ runtime `dist/**` (plus `README.md`, `LICENSE`, and now `CHANGELOG.md`) ships (#2419).
79
+
80
+ ## [0.1.1] - 2026-07 [DEPRECATED]
81
+
82
+ ### Note
83
+
84
+ - Superseded by 0.1.2. This release shipped stale `scrape_url` metadata rendering
85
+ (camelCase fields the API no longer returned) and included compiled test code in
86
+ the tarball. Upgrade to 0.1.2 or later.
87
+
88
+ ## [0.1.0] - 2026-07
89
+
90
+ ### Added
91
+
92
+ - Initial release of the ByteKit MCP server, exposing ByteKit web-data tools
93
+ (scrape, screenshot, search, docs) to AI agents over the Model Context Protocol,
94
+ as a local stdio server or hosted.
95
+
96
+ [0.2.0]: https://github.com/Hunt-Labs-Inc/ByteKit/tree/main/packages/mcp-server
97
+ [0.1.3]: https://github.com/Hunt-Labs-Inc/ByteKit/tree/main/packages/mcp-server
98
+ [0.1.2]: https://github.com/Hunt-Labs-Inc/ByteKit/tree/main/packages/mcp-server
99
+ [0.1.1]: https://github.com/Hunt-Labs-Inc/ByteKit/tree/main/packages/mcp-server
100
+ [0.1.0]: https://github.com/Hunt-Labs-Inc/ByteKit/tree/main/packages/mcp-server
package/README.md CHANGED
@@ -84,12 +84,10 @@ Client config for a stdio server (`claude_desktop_config.json` and equivalents):
84
84
 
85
85
  ### API-key resolution order
86
86
 
87
- The local server resolves the key in this order, so a legacy setup keeps
88
- working:
87
+ The local server resolves the key in this order:
89
88
 
90
89
  1. `--api-key <key>` flag
91
90
  2. `BYTEKIT_API_KEY` environment variable
92
- 3. `RAPIDCRAWL_API_KEY` environment variable (legacy fallback)
93
91
 
94
92
  ## Tool inventory
95
93
 
package/dist/cli.d.ts CHANGED
@@ -9,10 +9,9 @@
9
9
  /**
10
10
  * Resolve the API key from, in precedence order:
11
11
  * 1. the `--api-key` flag
12
- * 2. the `BYTEKIT_API_KEY` env var (the current signal)
13
- * 3. the `RAPIDCRAWL_API_KEY` env var (legacy fallback, kept working)
12
+ * 2. the `BYTEKIT_API_KEY` env var
14
13
  *
15
- * An empty-string / absent flag falls through to the env vars. Returns
14
+ * An empty-string / absent flag falls through to the env var. Returns
16
15
  * `undefined` when no usable key is present.
17
16
  *
18
17
  * Exported (and factored out of the CLI bootstrap) so the precedence contract
@@ -24,7 +23,23 @@ export declare function resolveApiKey(opts: {
24
23
  env: Record<string, string | undefined>;
25
24
  }): string | undefined;
26
25
  export declare const API_KEY_REQUIRED_MESSAGE = "Error: API key required. Use --api-key or set the BYTEKIT_API_KEY environment variable.\n";
27
- export declare const HELP_TEXT = "ByteKit MCP Server\n\nUsage:\n bytekit-mcp --api-key <key> [--base-url <url>] [--verbose]\n\nOptions:\n --api-key ByteKit API key. Resolution order: --api-key flag, then\n BYTEKIT_API_KEY, then RAPIDCRAWL_API_KEY (legacy fallback).\n --base-url API base URL (default: https://api.bytekit.com)\n --verbose Log requests to stderr\n --help Show this help message\n";
26
+ /** The API host the server defaults to when no flag and no env var resolve a base URL. */
27
+ export declare const DEFAULT_BASE_URL = "https://api.bytekit.com";
28
+ /**
29
+ * Resolve the API base URL from, in precedence order:
30
+ * 1. the `--base-url` flag
31
+ * 2. the `BYTEKIT_BASE_URL` env var
32
+ * 3. the built-in {@link DEFAULT_BASE_URL}
33
+ *
34
+ * Mirrors {@link resolveApiKey}'s shape (empty/absent flag falls through). This is the single
35
+ * base-URL resolution site for the binary; the `parseArgs` option deliberately carries NO
36
+ * `default:` so an absent flag yields `undefined` here rather than shadowing the env fallback.
37
+ */
38
+ export declare function resolveBaseUrl(opts: {
39
+ flag?: string | undefined;
40
+ env: Record<string, string | undefined>;
41
+ }): string;
42
+ export declare const HELP_TEXT = "ByteKit MCP Server\n\nUsage:\n bytekit-mcp --api-key <key> [--base-url <url>] [--verbose]\n\nOptions:\n --api-key ByteKit API key. Resolution order: --api-key flag, then\n BYTEKIT_API_KEY.\n --base-url API base URL. Resolution order: --base-url flag, then\n BYTEKIT_BASE_URL (default: https://api.bytekit.com)\n --verbose Log requests to stderr\n --help Show this help message\n";
28
43
  /**
29
44
  * True when this module is the process entrypoint (run directly or via its bin),
30
45
  * false when it is merely imported (e.g. the test suite exercising resolveApiKey).
package/dist/cli.js CHANGED
@@ -14,10 +14,9 @@ import { createServer, BytekitClient } from './index.js';
14
14
  /**
15
15
  * Resolve the API key from, in precedence order:
16
16
  * 1. the `--api-key` flag
17
- * 2. the `BYTEKIT_API_KEY` env var (the current signal)
18
- * 3. the `RAPIDCRAWL_API_KEY` env var (legacy fallback, kept working)
17
+ * 2. the `BYTEKIT_API_KEY` env var
19
18
  *
20
- * An empty-string / absent flag falls through to the env vars. Returns
19
+ * An empty-string / absent flag falls through to the env var. Returns
21
20
  * `undefined` when no usable key is present.
22
21
  *
23
22
  * Exported (and factored out of the CLI bootstrap) so the precedence contract
@@ -26,9 +25,25 @@ import { createServer, BytekitClient } from './index.js';
26
25
  */
27
26
  export function resolveApiKey(opts) {
28
27
  const flag = opts.flag && opts.flag.length > 0 ? opts.flag : undefined;
29
- return flag ?? opts.env['BYTEKIT_API_KEY'] ?? opts.env['RAPIDCRAWL_API_KEY'];
28
+ return flag ?? opts.env['BYTEKIT_API_KEY'];
30
29
  }
31
30
  export const API_KEY_REQUIRED_MESSAGE = 'Error: API key required. Use --api-key or set the BYTEKIT_API_KEY environment variable.\n';
31
+ /** The API host the server defaults to when no flag and no env var resolve a base URL. */
32
+ export const DEFAULT_BASE_URL = 'https://api.bytekit.com';
33
+ /**
34
+ * Resolve the API base URL from, in precedence order:
35
+ * 1. the `--base-url` flag
36
+ * 2. the `BYTEKIT_BASE_URL` env var
37
+ * 3. the built-in {@link DEFAULT_BASE_URL}
38
+ *
39
+ * Mirrors {@link resolveApiKey}'s shape (empty/absent flag falls through). This is the single
40
+ * base-URL resolution site for the binary; the `parseArgs` option deliberately carries NO
41
+ * `default:` so an absent flag yields `undefined` here rather than shadowing the env fallback.
42
+ */
43
+ export function resolveBaseUrl(opts) {
44
+ const flag = opts.flag && opts.flag.length > 0 ? opts.flag : undefined;
45
+ return flag ?? opts.env['BYTEKIT_BASE_URL'] ?? DEFAULT_BASE_URL;
46
+ }
32
47
  export const HELP_TEXT = `ByteKit MCP Server
33
48
 
34
49
  Usage:
@@ -36,8 +51,9 @@ Usage:
36
51
 
37
52
  Options:
38
53
  --api-key ByteKit API key. Resolution order: --api-key flag, then
39
- BYTEKIT_API_KEY, then RAPIDCRAWL_API_KEY (legacy fallback).
40
- --base-url API base URL (default: https://api.bytekit.com)
54
+ BYTEKIT_API_KEY.
55
+ --base-url API base URL. Resolution order: --base-url flag, then
56
+ BYTEKIT_BASE_URL (default: https://api.bytekit.com)
41
57
  --verbose Log requests to stderr
42
58
  --help Show this help message
43
59
  `;
@@ -45,7 +61,7 @@ async function main() {
45
61
  const { values } = parseArgs({
46
62
  options: {
47
63
  'api-key': { type: 'string' },
48
- 'base-url': { type: 'string', default: 'https://api.bytekit.com' },
64
+ 'base-url': { type: 'string' },
49
65
  verbose: { type: 'boolean', default: false },
50
66
  help: { type: 'boolean', default: false },
51
67
  },
@@ -62,7 +78,7 @@ async function main() {
62
78
  }
63
79
  const client = new BytekitClient({
64
80
  apiKey,
65
- baseUrl: values['base-url'],
81
+ baseUrl: resolveBaseUrl({ flag: values['base-url'], env: process.env }),
66
82
  verbose: values.verbose,
67
83
  });
68
84
  const server = createServer(client);
package/dist/client.d.ts CHANGED
@@ -55,27 +55,36 @@ export interface SearchResponse {
55
55
  export interface ScreenshotParams {
56
56
  url: string;
57
57
  full_page?: boolean | undefined;
58
- device?: 'desktop' | 'mobile' | 'tablet' | undefined;
58
+ device?: 'desktop' | 'mobile' | undefined;
59
59
  format?: 'png' | 'jpeg' | undefined;
60
60
  }
61
+ /** Nested error shape carried by the #2027 failed-screenshot envelope. */
62
+ export interface ScreenshotError {
63
+ code?: string;
64
+ message?: string;
65
+ http_status?: number;
66
+ failed_at?: string;
67
+ }
61
68
  export interface ScreenshotResult {
62
- id: string;
63
- url: string;
69
+ id?: string;
70
+ url?: string;
64
71
  status: string;
65
- image_url?: string;
66
- width?: number;
67
- height?: number;
68
- format?: string;
69
- file_size?: number;
70
- credits_charged?: number;
72
+ image_url?: string | null;
73
+ page_title?: string | null;
74
+ image_width?: number | null;
75
+ image_height?: number | null;
76
+ file_size_bytes?: number | null;
77
+ credits_charged?: number | null;
78
+ /** Present only on the #2027 failed envelope. */
79
+ error?: ScreenshotError;
71
80
  created_at?: string;
72
- completed_at?: string;
73
- expires_at?: string;
81
+ completed_at?: string | null;
82
+ expires_at?: string | null;
74
83
  }
75
84
  export interface AccountResult {
76
85
  id: string;
77
86
  email: string;
78
- name: string;
87
+ name: string | null;
79
88
  plan: {
80
89
  id: string;
81
90
  slug: string;
@@ -107,6 +116,19 @@ export declare class BytekitApiError extends Error {
107
116
  readonly errorCode?: string | undefined;
108
117
  constructor(message: string, statusCode: number, errorCode?: string | undefined);
109
118
  }
119
+ /**
120
+ * Parse an HTTP `Retry-After` header into a bounded delay in milliseconds.
121
+ *
122
+ * Handles all three real-world forms without ever producing `NaN`:
123
+ * - delta-seconds (e.g. `"120"`) → seconds × 1000
124
+ * - HTTP-date (e.g. `"Wed, 21 Oct 2026 07:28:00 GMT"`) → milliseconds until that instant
125
+ * - absent / garbage → {@link DEFAULT_RETRY_AFTER_MS}
126
+ *
127
+ * The result is always clamped to `[0, MAX_RETRY_AFTER_MS]`. Before this guard,
128
+ * an HTTP-date header flowed through `parseInt` → `NaN` → `setTimeout(NaN)`,
129
+ * collapsing the backoff to an immediate retry (issue #2478).
130
+ */
131
+ export declare function parseRetryAfterMs(headerValue: string | null | undefined): number;
110
132
  export declare class BytekitClient {
111
133
  private readonly baseUrl;
112
134
  private readonly apiKey;
package/dist/client.js CHANGED
@@ -12,6 +12,47 @@ export class BytekitApiError extends Error {
12
12
  }
13
13
  }
14
14
  // ============================================================
15
+ // Retry-After parsing
16
+ // ============================================================
17
+ /** Default retry delay (ms) when Retry-After is absent or unparseable. */
18
+ const DEFAULT_RETRY_AFTER_MS = 1000;
19
+ /** Upper bound (ms) on any computed retry delay, so a hostile/huge header can't stall. */
20
+ const MAX_RETRY_AFTER_MS = 30_000;
21
+ /**
22
+ * Parse an HTTP `Retry-After` header into a bounded delay in milliseconds.
23
+ *
24
+ * Handles all three real-world forms without ever producing `NaN`:
25
+ * - delta-seconds (e.g. `"120"`) → seconds × 1000
26
+ * - HTTP-date (e.g. `"Wed, 21 Oct 2026 07:28:00 GMT"`) → milliseconds until that instant
27
+ * - absent / garbage → {@link DEFAULT_RETRY_AFTER_MS}
28
+ *
29
+ * The result is always clamped to `[0, MAX_RETRY_AFTER_MS]`. Before this guard,
30
+ * an HTTP-date header flowed through `parseInt` → `NaN` → `setTimeout(NaN)`,
31
+ * collapsing the backoff to an immediate retry (issue #2478).
32
+ */
33
+ export function parseRetryAfterMs(headerValue) {
34
+ if (headerValue == null)
35
+ return DEFAULT_RETRY_AFTER_MS;
36
+ const trimmed = headerValue.trim();
37
+ if (trimmed === '')
38
+ return DEFAULT_RETRY_AFTER_MS;
39
+ // delta-seconds: a bare non-negative integer.
40
+ if (/^\d+$/.test(trimmed)) {
41
+ const seconds = Number(trimmed);
42
+ if (!Number.isFinite(seconds))
43
+ return DEFAULT_RETRY_AFTER_MS;
44
+ return Math.min(Math.max(seconds * 1000, 0), MAX_RETRY_AFTER_MS);
45
+ }
46
+ // HTTP-date form.
47
+ const whenMs = Date.parse(trimmed);
48
+ if (!Number.isNaN(whenMs)) {
49
+ const deltaMs = whenMs - Date.now();
50
+ return Math.min(Math.max(deltaMs, 0), MAX_RETRY_AFTER_MS);
51
+ }
52
+ // Unparseable garbage.
53
+ return DEFAULT_RETRY_AFTER_MS;
54
+ }
55
+ // ============================================================
15
56
  // Client
16
57
  // ============================================================
17
58
  export class BytekitClient {
@@ -98,7 +139,7 @@ export class BytekitClient {
98
139
  // 429: retry once with Retry-After
99
140
  if (response.status === 429) {
100
141
  const retryAfter = response.headers.get('Retry-After');
101
- const waitMs = retryAfter ? Math.min(parseInt(retryAfter, 10) * 1000, 30_000) : 1000;
142
+ const waitMs = parseRetryAfterMs(retryAfter);
102
143
  if (this.verbose) {
103
144
  process.stderr.write(`[mcp] Rate limited, retrying after ${waitMs}ms\n`);
104
145
  }
@@ -132,31 +173,85 @@ export class BytekitClient {
132
173
  }
133
174
  async handleErrorResponse(response) {
134
175
  const status = response.status;
176
+ // Parse the body once, tolerating a non-JSON payload (e.g. a load-balancer
177
+ // HTML error page) without crashing. Prefer the canonical unified envelope
178
+ // ({ error: { code, message, details } }, gateway issue #699).
179
+ const envelope = await parseErrorEnvelope(response);
180
+ // ── Specific status mappings win over the generic envelope (precedence) ──
181
+ // These carry deliberate, actionable guidance and must beat the raw
182
+ // server-supplied code/message even when an envelope is present (issue #2478).
135
183
  if (status === 401) {
136
- throw new BytekitApiError('Invalid API key. Check your RAPIDCRAWL_API_KEY.', 401, 'invalid_api_key');
184
+ throw new BytekitApiError('Invalid API key. Check your BYTEKIT_API_KEY.', 401, 'invalid_api_key');
137
185
  }
138
186
  if (status === 402) {
139
187
  throw new BytekitApiError('Bandwidth quota exhausted. Check usage with get_account.', 402, 'quota_exceeded');
140
188
  }
141
189
  if (status === 422) {
142
- let detail = 'Validation error.';
143
- try {
144
- const body = (await response.json());
145
- const envelopeMsg = typeof body.error === 'object' ? body.error?.message : undefined;
146
- detail =
147
- envelopeMsg ??
148
- body.message ??
149
- (typeof body.error === 'string' ? body.error : undefined) ??
150
- detail;
151
- }
152
- catch {
153
- // ignore parse errors
154
- }
155
- throw new BytekitApiError(detail, 422, 'validation_error');
190
+ const base = envelope.message ?? 'Validation error.';
191
+ const detail = envelope.details !== undefined ? `${base} (${formatErrorDetails(envelope.details)})` : base;
192
+ throw new BytekitApiError(detail, 422, envelope.code ?? 'validation_error');
156
193
  }
194
+ // ── Generic envelope rendering: any other non-2xx that carried a parseable
195
+ // API envelope surfaces the server's own code + message so the agent can act
196
+ // on it (e.g. 503 `blocked`, 400 `invalid_url`, 404 `not_found`). ──
197
+ if (envelope.code !== undefined && envelope.message !== undefined) {
198
+ throw new BytekitApiError(`${envelope.code}: ${envelope.message}`, status, envelope.code);
199
+ }
200
+ // ── Fallbacks: no parseable envelope. Report the status line, never a
201
+ // misleading retry hint (retrying a non-retryable failure won't help). ──
157
202
  if (status >= 500) {
158
- throw new BytekitApiError('ByteKit API error. Try again.', status, 'server_error');
203
+ throw new BytekitApiError(`ByteKit API error (HTTP ${status}).`, status, 'server_error');
159
204
  }
160
205
  throw new BytekitApiError(`Unexpected API error (HTTP ${status}).`, status, 'unknown_error');
161
206
  }
162
207
  }
208
+ /**
209
+ * Read an error response body into a normalized `{ code, message, details }`
210
+ * envelope. Recognizes the canonical unified shape
211
+ * (`{ error: { code, message, details } }`) and legacy flat shapes
212
+ * (`{ message }`, `{ error: '<string>' }`). Returns an empty object for a
213
+ * non-JSON or non-object body — the caller then falls back to a status-line
214
+ * message instead of crashing (issue #2478, E1).
215
+ */
216
+ async function parseErrorEnvelope(response) {
217
+ let body;
218
+ try {
219
+ body = await response.json();
220
+ }
221
+ catch {
222
+ return {};
223
+ }
224
+ if (typeof body !== 'object' || body === null)
225
+ return {};
226
+ const b = body;
227
+ // Canonical unified envelope: `error` is an object with code/message/details.
228
+ if (typeof b.error === 'object' && b.error !== null) {
229
+ const err = b.error;
230
+ const parsed = {};
231
+ if (typeof err.code === 'string')
232
+ parsed.code = err.code;
233
+ if (typeof err.message === 'string')
234
+ parsed.message = err.message;
235
+ if (err.details !== undefined)
236
+ parsed.details = err.details;
237
+ return parsed;
238
+ }
239
+ // Legacy flat shapes: a top-level `message`, or an `error` string.
240
+ const parsed = {};
241
+ if (typeof b.message === 'string')
242
+ parsed.message = b.message;
243
+ else if (typeof b.error === 'string')
244
+ parsed.message = b.error;
245
+ return parsed;
246
+ }
247
+ /** Render an error `details` value as a compact human-readable string. */
248
+ function formatErrorDetails(details) {
249
+ if (typeof details === 'string')
250
+ return details;
251
+ try {
252
+ return JSON.stringify(details);
253
+ }
254
+ catch {
255
+ return String(details);
256
+ }
257
+ }