@hunt-labs/bytekit-mcp 0.1.3 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -12,6 +12,101 @@ 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
+ // ============================================================
56
+ // Per-request timeout budget (#2568)
57
+ // ============================================================
58
+ /** Default per-request budget (ms) covering fetch + retry sleep + retry fetch + body read. */
59
+ const DEFAULT_TIMEOUT_MS = 120_000;
60
+ /**
61
+ * Upper bound accepted by `AbortSignal.timeout` without `ERR_OUT_OF_RANGE`. A caller
62
+ * value above this is clamped rather than allowed to crash the constructor.
63
+ */
64
+ const MAX_TIMEOUT_MS = 2_147_483_647;
65
+ /**
66
+ * Settle with `promise`, or reject with the signal's abort reason the moment it aborts --
67
+ * whichever happens first.
68
+ *
69
+ * Adds an abort listener and NO timers, so it is invisible to vitest fake timers and
70
+ * cannot perturb the exact-equality `Retry-After` assertions in `client.test.ts`.
71
+ *
72
+ * The race (rather than relying on `init.signal` passthrough alone) is what makes a
73
+ * custom `fetch` that ignores the signal and never resolves still reject within budget --
74
+ * and it is the only way a `response.json()` on a hand-built `Response`, which is
75
+ * attached to no signal at all, can be interrupted.
76
+ */
77
+ function withAbort(promise, signal) {
78
+ if (signal === undefined)
79
+ return promise;
80
+ if (signal.aborted) {
81
+ // The abandoned promise may still reject later; absorb it so it cannot surface as
82
+ // an unhandled rejection.
83
+ promise.catch(() => { });
84
+ return Promise.reject(abortReason(signal));
85
+ }
86
+ return new Promise((resolve, reject) => {
87
+ const onAbort = () => {
88
+ reject(abortReason(signal));
89
+ };
90
+ signal.addEventListener('abort', onAbort, { once: true });
91
+ // Forwarding BOTH settlements up front means a late rejection from the raced-away
92
+ // promise is still handled after the abort already won -- otherwise a slow fetch
93
+ // that eventually fails would surface as an unhandled rejection. The `finally`
94
+ // drops the listener on every path, so a long-lived signal accrues none.
95
+ void promise.then(resolve, reject).finally(() => {
96
+ signal.removeEventListener('abort', onAbort);
97
+ });
98
+ });
99
+ }
100
+ /**
101
+ * Narrow `AbortSignal.reason` -- typed `any` by lib.dom -- to a real `Error`. A timeout
102
+ * signal's reason is a `DOMException` named `TimeoutError`, which already extends `Error`;
103
+ * the fallback only covers a signal carrying some other reason.
104
+ */
105
+ function abortReason(signal) {
106
+ const reason = signal.reason;
107
+ return reason instanceof Error ? reason : new Error(String(reason));
108
+ }
109
+ // ============================================================
15
110
  // Client
16
111
  // ============================================================
17
112
  export class BytekitClient {
@@ -25,19 +120,54 @@ export class BytekitClient {
25
120
  * call time so tests can stub `globalThis.fetch` without constructing a new client.
26
121
  */
27
122
  fetchFn;
123
+ /**
124
+ * Normalized per-request budget in milliseconds; `0` means disabled. Resolved once
125
+ * here so every `request()` reads a value already known to be safe to hand to
126
+ * `AbortSignal.timeout`.
127
+ */
128
+ timeoutMs;
28
129
  constructor(options) {
29
130
  this.apiKey = options.apiKey;
30
131
  this.baseUrl = (options.baseUrl ?? 'https://api.bytekit.com').replace(/\/+$/, '');
31
132
  this.verbose = options.verbose === true;
133
+ const rawTimeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
134
+ this.timeoutMs =
135
+ Number.isFinite(rawTimeoutMs) && rawTimeoutMs > 0
136
+ ? Math.min(Math.floor(rawTimeoutMs), MAX_TIMEOUT_MS)
137
+ : 0;
32
138
  // Store only when explicitly provided; otherwise resolve globalThis.fetch at
33
139
  // call time so test stubs on globalThis.fetch take effect without rebuilding
34
140
  // the client.
35
141
  this.fetchFn = options.fetch;
36
142
  }
143
+ /**
144
+ * The distinct error a budget exhaustion produces. `statusCode: 0` mirrors the
145
+ * existing `network_error` convention for failures that never produced an HTTP
146
+ * status, and `timeout` keeps the two classes distinguishable to callers.
147
+ *
148
+ * The message interpolates only the numeric budget -- no URL, header, body, or API
149
+ * key -- because every tool's catch block renders this text straight to the agent.
150
+ */
151
+ timeoutError() {
152
+ return new BytekitApiError(`ByteKit API request timed out after ${this.timeoutMs}ms.`, 0, 'timeout');
153
+ }
37
154
  // ── Public API ──
38
155
  async scrape(params) {
39
156
  return this.post('/v1/scrape', params);
40
157
  }
158
+ /**
159
+ * Retrieve a previously created scrape by its `sc_` id
160
+ * (openapi.yaml `GET /v1/scrape/{id}`, operationId `getScrape`).
161
+ *
162
+ * Always answers HTTP 200 on an existing job — the `status` discriminator carries the
163
+ * state, so a still-running scrape arrives as a {@link ScrapeQueuedEnvelope} rather than
164
+ * a non-2xx. This is the redemption half of the async `scrape` handle: POST /v1/scrape
165
+ * may answer 202 with a queued envelope, and without this method that `sc_` id had no
166
+ * MCP-side retrieval path at all (issue #2538).
167
+ */
168
+ async getScrape(id) {
169
+ return this.get(`/v1/scrape/${encodeURIComponent(id)}`);
170
+ }
41
171
  async search(params) {
42
172
  // Build the request body with only the fields the caller supplied, so the
43
173
  // wire payload stays minimal and matches the API's optional-field contract.
@@ -80,15 +210,28 @@ export class BytekitClient {
80
210
  }
81
211
  const start = Date.now();
82
212
  const doFetch = this.fetchFn ?? fetch;
213
+ // ONE signal for the whole call, created before any await, so the budget covers the
214
+ // fetch + retry sleep + retry fetch + body read taken together rather than resetting
215
+ // per await. `AbortSignal.timeout` is deliberate over a manual controller plus a
216
+ // `setTimeout`: the latter leaves a pending fake-timer-visible timer that breaks the
217
+ // exact-equality `Retry-After` assertions in client.test.ts (#2568).
218
+ const signal = this.timeoutMs > 0 ? AbortSignal.timeout(this.timeoutMs) : undefined;
83
219
  let response;
84
220
  try {
85
221
  const init = { method, headers };
86
222
  if (body !== undefined) {
87
223
  init.body = JSON.stringify(body);
88
224
  }
89
- response = await doFetch(url, init);
225
+ // Assigned conditionally: `exactOptionalPropertyTypes` forbids writing `undefined`
226
+ // into an optional property.
227
+ if (signal !== undefined) {
228
+ init.signal = signal;
229
+ }
230
+ response = await withAbort(doFetch(url, init), signal);
90
231
  }
91
232
  catch {
233
+ if (signal?.aborted)
234
+ throw this.timeoutError();
92
235
  throw new BytekitApiError('Could not reach ByteKit API. Check your connection and base URL.', 0, 'network_error');
93
236
  }
94
237
  if (this.verbose) {
@@ -98,20 +241,41 @@ export class BytekitClient {
98
241
  // 429: retry once with Retry-After
99
242
  if (response.status === 429) {
100
243
  const retryAfter = response.headers.get('Retry-After');
101
- const waitMs = retryAfter ? Math.min(parseInt(retryAfter, 10) * 1000, 30_000) : 1000;
244
+ const waitMs = parseRetryAfterMs(retryAfter);
102
245
  if (this.verbose) {
103
246
  process.stderr.write(`[mcp] Rate limited, retrying after ${waitMs}ms\n`);
104
247
  }
105
- await new Promise((resolve) => setTimeout(resolve, waitMs));
248
+ try {
249
+ await withAbort(new Promise((resolve) => {
250
+ // Exactly one timer, with the delay `parseRetryAfterMs` computed and nothing
251
+ // else -- the fake-timer HTTP-date test asserts the clock advances by exactly
252
+ // that amount, so a second or rescaled timer here would break it.
253
+ const timer = setTimeout(resolve, waitMs);
254
+ // Release the pending sleep as soon as the budget expires; a raced-away timer
255
+ // would otherwise hold the event loop open for the whole `Retry-After`.
256
+ signal?.addEventListener('abort', () => clearTimeout(timer), { once: true });
257
+ }), signal);
258
+ }
259
+ catch (err) {
260
+ // The sleep promise itself never rejects, so only the abort race can land here.
261
+ if (signal?.aborted)
262
+ throw this.timeoutError();
263
+ throw err;
264
+ }
106
265
  let retryResponse;
107
266
  try {
108
267
  const retryInit = { method, headers };
109
268
  if (body !== undefined) {
110
269
  retryInit.body = JSON.stringify(body);
111
270
  }
112
- retryResponse = await doFetch(url, retryInit);
271
+ if (signal !== undefined) {
272
+ retryInit.signal = signal;
273
+ }
274
+ retryResponse = await withAbort(doFetch(url, retryInit), signal);
113
275
  }
114
276
  catch {
277
+ if (signal?.aborted)
278
+ throw this.timeoutError();
115
279
  throw new BytekitApiError('Could not reach ByteKit API. Check your connection and base URL.', 0, 'network_error');
116
280
  }
117
281
  if (retryResponse.status === 429) {
@@ -120,9 +284,20 @@ export class BytekitClient {
120
284
  response = retryResponse;
121
285
  }
122
286
  if (!response.ok) {
123
- await this.handleErrorResponse(response);
287
+ await this.handleErrorResponse(response, path, signal);
288
+ }
289
+ try {
290
+ return (await withAbort(response.json(), signal));
291
+ }
292
+ catch (err) {
293
+ if (signal?.aborted)
294
+ throw this.timeoutError();
295
+ // Deliberate (#2568, E4 option b): a malformed 2xx body re-throws its original
296
+ // SyntaxError unchanged. This ticket's surface is the timeout it is named for, and
297
+ // inventing a new error code here would change a pre-existing, user-visible failure
298
+ // mode that nothing in the ticket asks to change.
299
+ throw err;
124
300
  }
125
- return (await response.json());
126
301
  }
127
302
  async post(path, body) {
128
303
  return this.request('POST', path, body);
@@ -130,33 +305,138 @@ export class BytekitClient {
130
305
  async get(path) {
131
306
  return this.request('GET', path);
132
307
  }
133
- async handleErrorResponse(response) {
308
+ /**
309
+ * Map a non-2xx `response` to a {@link BytekitApiError}.
310
+ *
311
+ * `path` is the request path (the caller's second `request` argument). It is threaded in
312
+ * so status mappings can be endpoint-aware: the 402 message differs between the
313
+ * bandwidth-billed capture endpoints and the credit-billed `/v1/search` (issue #2571).
314
+ *
315
+ * `signal` is the per-request timeout signal (#2568); it is forwarded into
316
+ * `parseErrorEnvelope` so an aborted error-body read surfaces as a timeout rather than a
317
+ * misleading status-line message.
318
+ */
319
+ async handleErrorResponse(response, path, signal) {
134
320
  const status = response.status;
321
+ // Parse the body once, tolerating a non-JSON payload (e.g. a load-balancer
322
+ // HTML error page) without crashing. Prefer the canonical unified envelope
323
+ // ({ error: { code, message, details } }, gateway issue #699).
324
+ let envelope;
325
+ try {
326
+ envelope = await parseErrorEnvelope(response, signal);
327
+ }
328
+ catch {
329
+ // Only an abort can reject here -- a genuinely non-JSON body still resolves to
330
+ // { shape: 'none' }. Without this, an error-body read that ran out of budget fell
331
+ // through to a misleading status-line message instead of a timeout (#2568 E3).
332
+ throw this.timeoutError();
333
+ }
334
+ // ── Specific status mappings win over the generic envelope (precedence) ──
335
+ // These carry deliberate, actionable guidance and must beat the raw
336
+ // server-supplied code/message even when an envelope is present (issue #2478).
135
337
  if (status === 401) {
136
338
  throw new BytekitApiError('Invalid API key. Check your BYTEKIT_API_KEY.', 401, 'invalid_api_key');
137
339
  }
138
340
  if (status === 402) {
341
+ // `/v1/search` is billed per credit (1 credit per upstream page), not on bandwidth,
342
+ // so the bandwidth wording is factually wrong for a search 402 — and `get_account`'s
343
+ // usage view does not answer a search-credit question, so that pointer is dropped
344
+ // here (issue #2571). Literal path-prefix match: no other client path starts with
345
+ // `/v1/search`. Every other 402 keeps the original bandwidth message verbatim.
346
+ if (path.startsWith('/v1/search')) {
347
+ throw new BytekitApiError('Search credit quota exhausted. Add credits or upgrade your plan to run more searches.', 402, 'quota_exceeded');
348
+ }
139
349
  throw new BytekitApiError('Bandwidth quota exhausted. Check usage with get_account.', 402, 'quota_exceeded');
140
350
  }
141
351
  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');
352
+ const base = envelope.message ?? 'Validation error.';
353
+ const detail = envelope.details !== undefined ? `${base} (${formatErrorDetails(envelope.details)})` : base;
354
+ throw new BytekitApiError(detail, 422, envelope.code ?? 'validation_error');
355
+ }
356
+ // ── Flat vendor-masked shape: `{ "error": "<code>" }` (e.g. /v1/search 502,
357
+ // docs/api/openapi.yaml §/v1/search 502). The string IS the error code, so
358
+ // surface it — but keep the status line in the text, because a bare code is
359
+ // not a sentence and callers key off the HTTP status (issue #2541).
360
+ // Position is load-bearing: strictly BELOW the 401/402/422 mappings, whose
361
+ // actionable guidance must keep winning (#2478), and strictly ABOVE the
362
+ // generic envelope branch, which is unreachable for flat bodies anyway
363
+ // because the flat parse never populates both `code` and `message`. ──
364
+ if (envelope.shape === 'flat' && envelope.code !== undefined) {
365
+ throw new BytekitApiError(`ByteKit API error (HTTP ${status}): ${envelope.code}`, status, envelope.code);
156
366
  }
367
+ // ── Generic envelope rendering: any other non-2xx that carried a parseable
368
+ // API envelope surfaces the server's own code + message so the agent can act
369
+ // on it (e.g. 503 `blocked`, 400 `invalid_url`, 404 `not_found`). ──
370
+ if (envelope.code !== undefined && envelope.message !== undefined) {
371
+ throw new BytekitApiError(`${envelope.code}: ${envelope.message}`, status, envelope.code);
372
+ }
373
+ // ── Fallbacks: no parseable envelope. Report the status line, never a
374
+ // misleading retry hint (retrying a non-retryable failure won't help). ──
157
375
  if (status >= 500) {
158
- throw new BytekitApiError('ByteKit API error. Try again.', status, 'server_error');
376
+ throw new BytekitApiError(`ByteKit API error (HTTP ${status}).`, status, 'server_error');
159
377
  }
160
378
  throw new BytekitApiError(`Unexpected API error (HTTP ${status}).`, status, 'unknown_error');
161
379
  }
162
380
  }
381
+ /**
382
+ * Read an error response body into a normalized `{ code, message, details }`
383
+ * envelope, tagged with the wire `shape` it came from.
384
+ *
385
+ * - `'envelope'` — the canonical unified shape `{ error: { code, message, details } }`.
386
+ * It always wins: it is matched first and returns before any flat parse runs.
387
+ * - `'flat'` — either a top-level `{ message: '<string>' }`, or the flat
388
+ * vendor-masked `{ error: '<string>' }` form. In the latter the string is the
389
+ * error **CODE**, not a message: `/v1/search` answers a provider outage with
390
+ * `502 {"error":"search_provider_error"}` (docs/api/openapi.yaml §/v1/search
391
+ * 502), a body deliberately outside the unified envelope. An empty string is
392
+ * treated as absent (issue #2541, E8).
393
+ * - `'none'` — non-JSON or non-object body; the caller falls back to a
394
+ * status-line message instead of crashing (issue #2478, E1).
395
+ */
396
+ async function parseErrorEnvelope(response, signal) {
397
+ let body;
398
+ try {
399
+ body = await withAbort(response.json(), signal);
400
+ }
401
+ catch {
402
+ // An aborted/timed-out body read is NOT a "no envelope" outcome. Surfacing it lets
403
+ // the caller report a timeout instead of a misleading status-line message (#2568).
404
+ if (signal?.aborted)
405
+ throw signal.reason;
406
+ return { shape: 'none' };
407
+ }
408
+ if (typeof body !== 'object' || body === null)
409
+ return { shape: 'none' };
410
+ const b = body;
411
+ // Canonical unified envelope: `error` is an object with code/message/details.
412
+ if (typeof b.error === 'object' && b.error !== null) {
413
+ const err = b.error;
414
+ const parsed = { shape: 'envelope' };
415
+ if (typeof err.code === 'string')
416
+ parsed.code = err.code;
417
+ if (typeof err.message === 'string')
418
+ parsed.message = err.message;
419
+ if (err.details !== undefined)
420
+ parsed.details = err.details;
421
+ return parsed;
422
+ }
423
+ // Flat shapes: a top-level `message` (a human sentence), or an `error` string
424
+ // (a machine-readable code). Ordering is preserved from #2478.
425
+ const parsed = { shape: 'flat' };
426
+ if (typeof b.message === 'string')
427
+ parsed.message = b.message;
428
+ else if (typeof b.error === 'string' && b.error.length > 0)
429
+ parsed.code = b.error;
430
+ return parsed;
431
+ }
432
+ /** Render an error `details` value as a compact human-readable string. */
433
+ function formatErrorDetails(details) {
434
+ if (typeof details === 'string')
435
+ return details;
436
+ try {
437
+ return JSON.stringify(details);
438
+ }
439
+ catch {
440
+ return String(details);
441
+ }
442
+ }