@hunt-labs/bytekit-mcp 0.2.1 → 0.2.2

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.
@@ -61,6 +61,22 @@ export declare function slugToUrlPath(slug: string[]): string;
61
61
  * (the docs index, which keeps its HTML URL and has an empty slug), are ignored.
62
62
  */
63
63
  export declare function parseLlmsTxt(text: string): Array<string[]>;
64
+ /**
65
+ * Returns a new bundle object whose keys are sorted lexicographically.
66
+ *
67
+ * Page-slug discovery order comes from `/docs/llms.txt`, which reflects
68
+ * fumadocs-mdx's file-discovery order in the generated `.source/index.ts` manifest.
69
+ * That order is NOT guaranteed stable across independent `next build` invocations —
70
+ * two regenerations from byte-identical docs content can (and empirically do, issue
71
+ * #2590 DoD-2) produce a differently-ORDERED but content-identical bundle, because
72
+ * nothing in the assembly step normalizes insertion order before `JSON.stringify`
73
+ * freezes it into the artifact.
74
+ *
75
+ * Sorting is a pure function of the key SET, independent of discovery order, so this
76
+ * fixes the actual root cause (the generator's un-normalized assembly step) rather than
77
+ * papering over one observed reordering.
78
+ */
79
+ export declare function sortBundleKeys<T>(bundle: Record<string, T>): Record<string, T>;
64
80
  /**
65
81
  * Extracts the page title from the rendered markdown.
66
82
  *
@@ -113,6 +113,28 @@ export function parseLlmsTxt(text) {
113
113
  }
114
114
  return slugs;
115
115
  }
116
+ /**
117
+ * Returns a new bundle object whose keys are sorted lexicographically.
118
+ *
119
+ * Page-slug discovery order comes from `/docs/llms.txt`, which reflects
120
+ * fumadocs-mdx's file-discovery order in the generated `.source/index.ts` manifest.
121
+ * That order is NOT guaranteed stable across independent `next build` invocations —
122
+ * two regenerations from byte-identical docs content can (and empirically do, issue
123
+ * #2590 DoD-2) produce a differently-ORDERED but content-identical bundle, because
124
+ * nothing in the assembly step normalizes insertion order before `JSON.stringify`
125
+ * freezes it into the artifact.
126
+ *
127
+ * Sorting is a pure function of the key SET, independent of discovery order, so this
128
+ * fixes the actual root cause (the generator's un-normalized assembly step) rather than
129
+ * papering over one observed reordering.
130
+ */
131
+ export function sortBundleKeys(bundle) {
132
+ const sorted = {};
133
+ for (const key of Object.keys(bundle).sort()) {
134
+ sorted[key] = bundle[key];
135
+ }
136
+ return sorted;
137
+ }
116
138
  /**
117
139
  * Extracts the page title from the rendered markdown.
118
140
  *
@@ -15,8 +15,15 @@ import type { ScrapeResult } from '../client.js';
15
15
  * routes/scrape.ts `handleGetScrapeById`). Non-error: the agent should poll, not fail.
16
16
  * - failed: `{ status:'failed', id, error:{ code, message, ... } }` — flagged as a tool
17
17
  * error, rendering the public error code + message only.
18
- * - success: full envelope; primary content prefers markdown → html → raw_html, with
19
- * optional links/images blocks appended.
18
+ * - success: full envelope; every textual format present (markdown, html, raw_html) is
19
+ * rendered, in that fixed canonical order — the first present format is the
20
+ * unlabeled primary, each remaining one follows under its own
21
+ * `--- format: <name> ---` delimiter — plus optional links/images blocks, all inside
22
+ * ONE truncation budget (issue #2589; previously only one format was shown, and
23
+ * links/images were appended AFTER truncation). The links/images block is passed to
24
+ * the truncator as a RESERVED trailing block (capped at half the budget) so it
25
+ * always gets its own slice of the budget instead of being the first thing
26
+ * discarded when the textual formats alone already fill it (cr-1/cr-4 hardening).
20
27
  *
21
28
  * Every optional line is omitted when absent, so no `undefined`/`null` literal is ever
22
29
  * emitted (issue #2419).
@@ -9,6 +9,14 @@ function renderImages(images) {
9
9
  .map((image) => typeof image === 'string' ? image : `${image.url}${image.alt ? ` — ${image.alt}` : ''}`)
10
10
  .join('\n');
11
11
  }
12
+ // Textual formats in canonical render order. The first one present in the envelope is
13
+ // the unlabeled primary (today's position); every other one present follows under its
14
+ // own delimiter. Module-local: nothing outside this file needs it (issue #2589).
15
+ const TEXTUAL_FORMATS = ['markdown', 'html', 'raw_html'];
16
+ // Full delimiter templates for every possible secondary textual format, used only to
17
+ // detect and strip a DANGLING partial delimiter left by a byte-boundary truncation
18
+ // cut (issue #2589 cr-8) — never to detect a complete, legitimately-rendered one.
19
+ const FORMAT_DELIMITER_MARKERS = TEXTUAL_FORMATS.map((f) => `\n\n--- format: ${f} ---\n\n`);
12
20
  /**
13
21
  * Renders a scrape envelope (from POST /v1/scrape or GET /v1/scrape/{id}) into
14
22
  * human-readable lines for MCP tool output.
@@ -25,8 +33,15 @@ function renderImages(images) {
25
33
  * routes/scrape.ts `handleGetScrapeById`). Non-error: the agent should poll, not fail.
26
34
  * - failed: `{ status:'failed', id, error:{ code, message, ... } }` — flagged as a tool
27
35
  * error, rendering the public error code + message only.
28
- * - success: full envelope; primary content prefers markdown → html → raw_html, with
29
- * optional links/images blocks appended.
36
+ * - success: full envelope; every textual format present (markdown, html, raw_html) is
37
+ * rendered, in that fixed canonical order — the first present format is the
38
+ * unlabeled primary, each remaining one follows under its own
39
+ * `--- format: <name> ---` delimiter — plus optional links/images blocks, all inside
40
+ * ONE truncation budget (issue #2589; previously only one format was shown, and
41
+ * links/images were appended AFTER truncation). The links/images block is passed to
42
+ * the truncator as a RESERVED trailing block (capped at half the budget) so it
43
+ * always gets its own slice of the budget instead of being the first thing
44
+ * discarded when the textual formats alone already fill it (cr-1/cr-4 hardening).
30
45
  *
31
46
  * Every optional line is omitted when absent, so no `undefined`/`null` literal is ever
32
47
  * emitted (issue #2419).
@@ -44,9 +59,13 @@ export function renderScrapeResult(result) {
44
59
  };
45
60
  }
46
61
  if (result.status === 'failed') {
62
+ // `id` is nullable (issue #2591 item 7; openapi.yaml ScrapeErrorEnvelope.id:
63
+ // `type: ["string", "null"]`) — null when the job was never queued (e.g. a
64
+ // validation failure before a row existed). Render an em-dash rather than the
65
+ // literal "ID: null".
47
66
  return {
48
67
  text: [
49
- `ID: ${result.id}`,
68
+ `ID: ${result.id ?? '—'}`,
50
69
  'Status: failed',
51
70
  `Error: ${result.error.code}`,
52
71
  result.error.message,
@@ -54,9 +73,34 @@ export function renderScrapeResult(result) {
54
73
  isError: true,
55
74
  };
56
75
  }
57
- // Primary content for display: prefer markdown → html → rawHtml
58
- const content = result.formats.markdown ?? result.formats.html ?? result.formats.raw_html ?? '';
59
- const { text, truncated } = truncateContent(content);
76
+ // Every textual format present, in canonical order. Presence is `typeof === 'string'`
77
+ // (not truthiness) so an empty-string format still counts as present — this
78
+ // reproduces the old `??` chain's behavior for the primary slot exactly (`'' ?? …`
79
+ // is not nullish either) while also surfacing a present-but-empty SECONDARY format
80
+ // to the caller instead of silently dropping it.
81
+ const present = TEXTUAL_FORMATS.filter((f) => typeof result.formats[f] === 'string');
82
+ let payload = present.length > 0 ? result.formats[present[0]] : '';
83
+ for (const f of present.slice(1)) {
84
+ payload += `\n\n--- format: ${f} ---\n\n${result.formats[f]}`;
85
+ }
86
+ // Links/images are built as a separate trailing block (not folded into `payload`
87
+ // directly) so they can be passed to truncateContent as a RESERVED block rather
88
+ // than ordinary tail content — see cr-1/cr-4 in the function doc above.
89
+ let trailingBlock = '';
90
+ if (Array.isArray(result.formats.links) && result.formats.links.length > 0) {
91
+ const linkList = renderLinks(result.formats.links);
92
+ trailingBlock += `\n\nLinks (${result.formats.links.length}):\n${linkList}`;
93
+ }
94
+ if (Array.isArray(result.formats.images) && result.formats.images.length > 0) {
95
+ const imgList = renderImages(result.formats.images);
96
+ trailingBlock += `\n\nImages (${result.formats.images.length}):\n${imgList}`;
97
+ }
98
+ // Single truncation site: the WHOLE assembled payload (formats + links + images) is
99
+ // truncated once, then meta lines are prepended (issue #2589 audit L1 — links/images
100
+ // used to be appended AFTER truncation, so the combined output could blow past the
101
+ // budget). `trailingBlock` is passed as a reserved suffix, not concatenated ahead of
102
+ // time, so it survives the cut even when `payload` alone already fills the budget.
103
+ const { text, truncated } = truncateContent(payload, undefined, undefined, trailingBlock, FORMAT_DELIMITER_MARKERS);
60
104
  const metaLines = [
61
105
  `ID: ${result.id}`,
62
106
  `URL: ${result.url}`,
@@ -68,16 +112,5 @@ export function renderScrapeResult(result) {
68
112
  ]
69
113
  .filter(Boolean)
70
114
  .join('\n');
71
- let body = `${metaLines}\n\n---\n\n${text}`;
72
- // Append links block when present
73
- if (Array.isArray(result.formats.links) && result.formats.links.length > 0) {
74
- const linkList = renderLinks(result.formats.links);
75
- body += `\n\nLinks (${result.formats.links.length}):\n${linkList}`;
76
- }
77
- // Append images block when present
78
- if (Array.isArray(result.formats.images) && result.formats.images.length > 0) {
79
- const imgList = renderImages(result.formats.images);
80
- body += `\n\nImages (${result.formats.images.length}):\n${imgList}`;
81
- }
82
- return { text: body, isError: false };
115
+ return { text: `${metaLines}\n\n---\n\n${text}`, isError: false };
83
116
  }
@@ -33,6 +33,12 @@ export function renderScreenshotResult(result) {
33
33
  result.credits_charged !== undefined && result.credits_charged !== null
34
34
  ? `Credits: ${result.credits_charged}`
35
35
  : null,
36
+ // Mirrors screenshot_url's queued-branch hint text exactly (issue #2591 item 4) --
37
+ // an agent that redeems the handle through get_result while it's still pending
38
+ // needs the same "call again later" guidance screenshot_url gives at submit time.
39
+ result.status === 'pending' || result.status === 'processing'
40
+ ? 'Use get_result with this ID to check when it completes.'
41
+ : null,
36
42
  ].filter((line) => line !== null);
37
43
  return { text: lines.join('\n'), isError: false };
38
44
  }
@@ -2,7 +2,7 @@
2
2
  * Truncate text content to a maximum byte size while preserving valid UTF-8.
3
3
  * Returns the truncated text with a suffix indicating truncation + content URL.
4
4
  */
5
- export declare function truncateContent(text: string, maxBytes?: number, contentUrl?: string): {
5
+ export declare function truncateContent(text: string, maxBytes?: number, contentUrl?: string, reserve?: string, dangleMarkers?: readonly string[]): {
6
6
  text: string;
7
7
  truncated: boolean;
8
8
  };
@@ -3,24 +3,97 @@
3
3
  * Returns the truncated text with a suffix indicating truncation + content URL.
4
4
  */
5
5
  const MAX_BYTES = 100 * 1024; // 100KB
6
- export function truncateContent(text, maxBytes = MAX_BYTES, contentUrl) {
7
- const byteLength = Buffer.byteLength(text, 'utf8');
8
- if (byteLength <= maxBytes) {
9
- return { text, truncated: false };
10
- }
11
- // Binary search for the character index that fits within maxBytes
12
- // This handles multi-byte UTF-8 characters correctly
6
+ // The MINIMUM share of `maxBytes` guaranteed to the primary `text` whenever it wants
7
+ // it (issue #2589 cr-1). Without this floor, an oversized reserve block (e.g. a huge
8
+ // links list) could crowd the primary `text` out entirely, just trading which side
9
+ // silently loses everything. It is NOT an unconditional ceiling on `reserve`: when
10
+ // `text` is small and doesn't need its half, the reserve is allowed to claim the
11
+ // leftover instead of that budget going unused (cr2-2) - see the `reserveBudget`
12
+ // computation below.
13
+ const MAX_RESERVE_FRACTION = 0.5;
14
+ /** Slices `text` to at most `maxBytes` UTF-8 bytes, trimming any incomplete trailing
15
+ * multi-byte sequence so the result is always valid UTF-8. */
16
+ function sliceToBytes(text, maxBytes) {
17
+ if (maxBytes <= 0)
18
+ return '';
13
19
  const buf = Buffer.from(text, 'utf8');
14
20
  const sliced = buf.subarray(0, maxBytes);
15
21
  // Decode back to string -- Buffer.toString will handle incomplete multi-byte
16
22
  // sequences at the boundary by replacing them, but we trim to last complete char
17
- let truncated = sliced.toString('utf8');
18
- // Remove any replacement character at the end (from incomplete multi-byte sequence)
19
- while (truncated.endsWith('\uFFFD')) {
20
- truncated = truncated.slice(0, -1);
23
+ let out = sliced.toString('utf8');
24
+ while (out.endsWith('\uFFFD')) {
25
+ out = out.slice(0, -1);
26
+ }
27
+ return out;
28
+ }
29
+ /**
30
+ * Strips a trailing occurrence of any of `markers` from `text` — either a PARTIAL
31
+ * occurrence (issue #2589 cr-8) or, when the cut landed exactly at the end of a
32
+ * COMPLETE delimiter (cr2-6), the whole delimiter.
33
+ *
34
+ * ONLY called when the caller has already confirmed `text` was itself cut (i.e. some
35
+ * of the original content beyond this point was discarded) — see the `textBytes >
36
+ * textBudget` guard at the call site. Under that guard, ANY marker match at the tail
37
+ * — partial or complete — means the section it announces lost 100% of its content to
38
+ * the cut: a partial marker (`\n\n---`) with no closing `format: <name> ---` is an
39
+ * obvious dangling fragment; a COMPLETE marker (`\n\n--- format: html ---\n\n`) with
40
+ * nothing after it is just as misleading, since it announces a section that turns out
41
+ * to be entirely empty, and produces the same forbidden `---\n\n---` collision once
42
+ * the truncation suffix's own leading `\n\n---` is appended right after it. Stripping
43
+ * both cases is safe specifically because of the cut guard: a complete marker that is
44
+ * NOT immediately followed by a cut (i.e. genuinely legitimate, real content or a
45
+ * deliberately-empty format) never reaches this function at all, since
46
+ * `truncateContent` only calls it when `text` was truncated.
47
+ *
48
+ * When multiple markers/lengths match, the longest matching suffix wins.
49
+ */
50
+ function stripDanglingMarker(text, markers) {
51
+ let bestLen = 0;
52
+ for (const marker of markers) {
53
+ for (let len = marker.length; len > 0; len--) {
54
+ if (len > bestLen && text.endsWith(marker.slice(0, len))) {
55
+ bestLen = len;
56
+ }
57
+ }
58
+ }
59
+ return bestLen > 0 ? text.slice(0, text.length - bestLen) : text;
60
+ }
61
+ export function truncateContent(text, maxBytes = MAX_BYTES, contentUrl,
62
+ // `reserve`: content appended immediately after `text`, budgeted SEPARATELY from
63
+ // `text` (capped at MAX_RESERVE_FRACTION of maxBytes) so it survives even when
64
+ // `text` alone already fills the whole budget - e.g. render-scrape.ts's
65
+ // links/images blocks, which used to be appended into the same tail-truncated
66
+ // string and were the first thing discarded (issue #2589 cr-1/cr-4).
67
+ reserve = '',
68
+ // Full delimiter templates (not just markers) whose trailing partial occurrence in
69
+ // the truncated `text` should be stripped rather than left dangling (cr-8).
70
+ dangleMarkers = []) {
71
+ const textBytes = Buffer.byteLength(text, 'utf8');
72
+ const reserveBytes = Buffer.byteLength(reserve, 'utf8');
73
+ if (textBytes + reserveBytes <= maxBytes) {
74
+ return { text: text + reserve, truncated: false };
75
+ }
76
+ // Give the reserve block first claim on its own (capped) share of the budget, then
77
+ // whatever remains to the primary text - the inverse of "reserve competes in the
78
+ // same tail-truncated string" (which is what silently dropped it in full).
79
+ //
80
+ // The cap is a FLOOR guarantee for `text` (text never loses more than half the
81
+ // budget to reserve), not a ceiling on `reserve`: `maxBytes - textBytes` is the
82
+ // budget `text` genuinely has no use for, so when text is small the reserve is
83
+ // allowed to claim that leftover instead of being shaved to 50% unconditionally
84
+ // (issue #2589 cr2-2 - the unconditional cap wasted up to ~50KB of the 100KB
85
+ // budget while still dropping billed links/images content). `maxBytes - textBytes`
86
+ // goes negative whenever text alone already exceeds the budget, in which case
87
+ // `Math.max` falls back to the fixed half-budget floor unchanged from cr-1.
88
+ const reserveBudget = Math.min(reserveBytes, Math.max(Math.floor(maxBytes * MAX_RESERVE_FRACTION), maxBytes - textBytes));
89
+ const textBudget = maxBytes - reserveBudget;
90
+ let slicedText = sliceToBytes(text, textBudget);
91
+ if (textBytes > textBudget) {
92
+ slicedText = stripDanglingMarker(slicedText, dangleMarkers);
21
93
  }
94
+ const slicedReserve = reserveBytes > reserveBudget ? sliceToBytes(reserve, reserveBudget) : reserve;
22
95
  const suffix = contentUrl
23
96
  ? `\n\n---\n[Content truncated. Full content available at: ${contentUrl}]`
24
97
  : '\n\n---\n[Content truncated at 100KB]';
25
- return { text: truncated + suffix, truncated: true };
98
+ return { text: slicedText + slicedReserve + suffix, truncated: true };
26
99
  }
@@ -135,8 +135,13 @@ export interface ScrapeSuccessEnvelope {
135
135
  export interface ScrapeErrorEnvelope {
136
136
  schema_version: ScrapeEnvelopeSchemaVersion;
137
137
  status: 'failed';
138
- /** Stable job identifier (sc_… prefixed). Canonical field (#1232; queued/error migrated #1971). */
139
- id: string;
138
+ /**
139
+ * Stable job identifier (sc_… prefixed). Canonical field (#1232; queued/error migrated
140
+ * #1971). Nullable (issue #2591 item 7, matches docs/api/openapi.yaml
141
+ * ScrapeErrorEnvelope.id: `type: ["string", "null"]`) — null when the job was never
142
+ * queued (e.g. a validation failure before a row existed).
143
+ */
144
+ id: string | null;
140
145
  error: {
141
146
  code: ScrapeEnvelopeErrorCode;
142
147
  message: string;
@@ -1,11 +1,19 @@
1
1
  export function getAccountTool(server, client) {
2
2
  server.tool('get_account', 'Get your ByteKit account details, plan info, and current usage/quota.', {}, async () => {
3
3
  try {
4
- const [account, usage] = await Promise.all([client.getAccount(), client.getUsage()]);
4
+ // Serialized, not Promise.all: firing both requests concurrently is unkind to
5
+ // 1-rps plans (issue #2591 item 3 / DoD bullet 2) — this also keeps `get_account`
6
+ // itself safe to recommend as a quota-check follow-up without risking a second
7
+ // rate-limit hit from its own two sub-requests.
8
+ const account = await client.getAccount();
9
+ const usage = await client.getUsage();
5
10
  // The API may return a null account name (issue #2477) — fall back to the email
6
- // rather than rendering the literal `Account: null`.
11
+ // rather than rendering the literal `Account: null`. When there's no name, show
12
+ // the email once instead of duplicating it in both slots (issue #2591 item 5).
7
13
  const lines = [
8
- `Account: ${account.name ?? account.email} (${account.email})`,
14
+ account.name
15
+ ? `Account: ${account.name} (${account.email})`
16
+ : `Account: ${account.email}`,
9
17
  `Account ID: ${account.id}`,
10
18
  '',
11
19
  `Plan: ${account.plan.name} (${account.plan.slug})`,
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  import { renderScrapeResult } from '../lib/render-scrape.js';
3
3
  import { renderScreenshotResult } from '../lib/render-screenshot.js';
4
4
  export function getResultTool(server, client) {
5
- server.tool('get_result', 'Get the result of a previous capture by ID: a screenshot (ss_ prefix) or a scrape (sc_ prefix, as returned by scrape_url when a page needs rendering).', {
5
+ server.tool('get_result', 'Get the result of a previous capture by ID: a screenshot (ss_ prefix) or a scrape (sc_ prefix, from an async or render-queued scrape submitted through the ByteKit API).', {
6
6
  id: z.string().describe('Result ID — ss_... (screenshot) or sc_... (scrape)'),
7
7
  }, async (params) => {
8
8
  try {
@@ -24,7 +24,9 @@ export function getResultTool(server, client) {
24
24
  content: [
25
25
  {
26
26
  type: 'text',
27
- text: `Invalid ID prefix. Expected ss_ (screenshot) or sc_ (scrape), got: ${id.substring(0, 3)}`,
27
+ // Show the full id, not a 3-char truncation (issue #2591 item 4) — a
28
+ // truncated id gives the agent nothing to compare against.
29
+ text: `Invalid ID prefix. Expected ss_ (screenshot) or sc_ (scrape), got: ${id}`,
28
30
  },
29
31
  ],
30
32
  };
@@ -1,16 +1,40 @@
1
1
  import { z } from 'zod';
2
2
  import { renderScrapeResult } from '../lib/render-scrape.js';
3
+ // Public API spelling (docs/api/openapi.yaml, and every bundled doc page — see
4
+ // sdk/typescript/scrape's `formats` option) → internal wire spelling used by
5
+ // BytekitClient/ScrapeFormat (scrape-contract.generated.ts). Only `raw_html`
6
+ // diverges; the other four format values are identical on both sides (issue #2588).
7
+ //
8
+ // This map lives here, in the hand-written tool file, deliberately — NOT in
9
+ // scrape-contract.generated.ts. That file is overwritten verbatim from
10
+ // packages/scrape-shared/src/envelope-types.ts on every
11
+ // `pnpm generate:scrape-contract` regen, so anything hand-edited into it would be
12
+ // silently wiped on the next regen (see issue #2588 failure mode E2). Keeping the
13
+ // widened vocabulary local to this file means a regen can never touch it.
14
+ const PUBLIC_TO_INTERNAL_FORMAT = {
15
+ raw_html: 'rawHtml',
16
+ };
17
+ function toInternalFormat(value) {
18
+ return (PUBLIC_TO_INTERNAL_FORMAT[value] ?? value);
19
+ }
3
20
  export function scrapeUrlTool(server, client) {
4
- server.tool('scrape_url', 'Scrape a webpage and return its content. Returns markdown by default. Use the formats parameter to request additional representations (rawHtml, html, links, images). A render-requiring page may come back as Status: queued with an sc_ ID — redeem it with get_result.', {
21
+ server.tool('scrape_url',
22
+ // Deliberately keeps the description capability-derived (#2589 E3): this input
23
+ // schema exposes none of the fields packages/gateway/src/scrape-core/can-fast-path.ts
24
+ // gates on, nor a `body.async` field, so an async/202 slow-path outcome is not
25
+ // advertised here — it would be unreachable from this tool. Add a queue-reaching
26
+ // field (e.g. `delay_ms`) or `async` to the schema below and update this
27
+ // description to match (pinned by scrape-url-description-reachability.test.ts).
28
+ 'Scrape a webpage and return its content. Returns markdown by default. Use the formats parameter to request additional representations (raw_html, html, links, images); each secondary textual format (html, raw_html) is included under its own delimiter, and links/images are appended under their own labeled sections. The rendered content (the requested formats plus any links/images) is capped at 100KB — on very large pages a requested format may be truncated or, in extreme cases, omitted to stay within that cap. A few header lines (id, URL, status, page title) are added on top and are not counted against it.', {
5
29
  url: z.string().url().describe('The URL to scrape'),
6
30
  formats: z
7
- .array(z.enum(['rawHtml', 'html', 'markdown', 'links', 'images']))
31
+ .array(z.enum(['raw_html', 'rawHtml', 'html', 'markdown', 'links', 'images']))
8
32
  .optional()
9
- .describe('Content formats to return. Default: ["markdown"]. Options: markdown, rawHtml, html, links, images.'),
33
+ .describe('Content formats to return. Default: ["markdown"]. Options: markdown, raw_html (also accepts rawHtml), html, links, images.'),
10
34
  country: z.string().optional().describe('Two-letter country code for geo-targeted scraping'),
11
35
  }, async (params) => {
12
36
  try {
13
- const formats = params.formats ?? ['markdown'];
37
+ const formats = (params.formats ?? ['markdown']).map(toInternalFormat);
14
38
  const result = await client.scrape({
15
39
  url: params.url,
16
40
  formats,
@@ -28,6 +28,20 @@ function scoreEntry(title, body, tokens) {
28
28
  }
29
29
  return score;
30
30
  }
31
+ /**
32
+ * Strips a leading `# <title>` H1 line from `body`, when present, so callers that
33
+ * already display `title` separately don't duplicate it (issue #2591 item 6). Every
34
+ * bundled doc page's body starts with its own H1 (`scripts/build-docs-bundle.ts`
35
+ * `extractTitle`/bundling), so `${title} ${body}` otherwise reads as
36
+ * "Title # Title\n\n...".
37
+ */
38
+ function stripLeadingTitleHeading(body, title) {
39
+ const newlineIdx = body.indexOf('\n');
40
+ const firstLine = newlineIdx === -1 ? body : body.slice(0, newlineIdx);
41
+ if (firstLine.trim() !== `# ${title}`)
42
+ return body;
43
+ return newlineIdx === -1 ? '' : body.slice(newlineIdx + 1).replace(/^\n+/, '');
44
+ }
31
45
  /**
32
46
  * Extracts a ~200-char snippet around the first occurrence of any query token
33
47
  * in the given text. Returns the full text if no match is found (shouldn't
@@ -72,7 +86,7 @@ export function searchDocsTool(server) {
72
86
  path,
73
87
  title: meta.title,
74
88
  section: meta.section,
75
- snippet: extractSnippet(`${meta.title} ${meta.body}`, tokens),
89
+ snippet: extractSnippet(`${meta.title} ${stripLeadingTitleHeading(meta.body, meta.title)}`, tokens),
76
90
  score,
77
91
  });
78
92
  }
@@ -55,8 +55,20 @@ export function webSearchTool(server, client) {
55
55
  date_range: params.date_range,
56
56
  }),
57
57
  });
58
+ // The results JSON block stays first and untouched (existing consumers key off
59
+ // it) — credits_used/related_searches (both spec-required, openapi.yaml
60
+ // SearchResponse) append after it rather than reordering anything (issue #2591
61
+ // item 1). related_searches is omitted entirely when empty rather than printing
62
+ // a dangling empty line.
63
+ const lines = [
64
+ JSON.stringify(result.results, null, 2),
65
+ `Credits used: ${result.credits_used}`,
66
+ ];
67
+ if (result.related_searches.length > 0) {
68
+ lines.push(`Related searches: ${result.related_searches.join(', ')}`);
69
+ }
58
70
  return {
59
- content: [{ type: 'text', text: JSON.stringify(result.results, null, 2) }],
71
+ content: [{ type: 'text', text: lines.join('\n') }],
60
72
  };
61
73
  }
62
74
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hunt-labs/bytekit-mcp",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "ByteKit MCP server — exposes ByteKit web-data tools (scrape, screenshot, search, docs) to AI agents over the Model Context Protocol, hosted or as a local stdio server.",
5
5
  "license": "MIT",
6
6
  "type": "module",