@hunt-labs/bytekit-mcp 0.2.2 → 0.2.3

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.
@@ -58,20 +58,109 @@ function stripDanglingMarker(text, markers) {
58
58
  }
59
59
  return bestLen > 0 ? text.slice(0, text.length - bestLen) : text;
60
60
  }
61
+ const byteLen = (value) => Buffer.byteLength(value, 'utf8');
62
+ /** `\n\nLinks (42):` — the section header, identical in shape to the pre-#2687 render. */
63
+ function sectionHeader(section) {
64
+ return `\n\n${section.label} (${section.entries.length}):`;
65
+ }
66
+ /** The per-section cut announcement, carrying the REAL kept count (issue #2687 item 6). */
67
+ function sectionMarker(label, shown, total) {
68
+ return `\n[${label} truncated: ${shown} of ${total} entries shown]`;
69
+ }
70
+ /**
71
+ * Renders `sections` into the reserve block, emitting only WHOLE entries and announcing
72
+ * any cut per section (issue #2687 item 6).
73
+ *
74
+ * Budget policy, in order:
75
+ * 1. Every section header is emitted if it fits — a section the agent asked for must be
76
+ * named even when the budget leaves no room for its entries, otherwise the render is
77
+ * indistinguishable from "you did not request it" (the same signal item 1 restores).
78
+ * 2. Entries are then filled in section order. An entry is taken only if it fits WHOLE,
79
+ * and — unless it is the section's last — only if room for that section's marker
80
+ * survives it. That reservation is what guarantees a cut is always announceable.
81
+ * 3. A section that lost entries gets its marker with the count actually emitted.
82
+ *
83
+ * Filling sequentially (rather than pro-rating across sections) means a later section can
84
+ * end up with a `0 of N` marker. That is deliberate: it reports honestly which entries the
85
+ * caller is not seeing, instead of silently rebalancing which content gets dropped.
86
+ *
87
+ * Degenerate budgets (smaller than the headers plus one marker) degrade to headers alone,
88
+ * or to the empty string. No signal is lost there either: the header still carries the
89
+ * real total, and `truncateContent` only reaches this path when it is about to append its
90
+ * own global truncation suffix.
91
+ */
92
+ export function renderReserveSections(sections, maxBytes) {
93
+ const full = sections
94
+ .map((s) => s.entries.length > 0 ? `${sectionHeader(s)}\n${s.entries.join('\n')}` : sectionHeader(s))
95
+ .join('');
96
+ if (byteLen(full) <= maxBytes)
97
+ return full;
98
+ let remaining = maxBytes;
99
+ const headerEmitted = sections.map((s) => {
100
+ const cost = byteLen(sectionHeader(s));
101
+ if (cost > remaining)
102
+ return false;
103
+ remaining -= cost;
104
+ return true;
105
+ });
106
+ const kept = sections.map(() => []);
107
+ const cut = sections.map(() => false);
108
+ for (let i = 0; i < sections.length; i++) {
109
+ const section = sections[i];
110
+ if (!headerEmitted[i])
111
+ continue;
112
+ // Upper bound on this section's marker: `shown` can never have more digits than
113
+ // `total`, so the all-shown spelling is the longest the marker can ever be.
114
+ const markerReserve = byteLen(sectionMarker(section.label, section.entries.length, section.entries.length));
115
+ for (let j = 0; j < section.entries.length; j++) {
116
+ const cost = byteLen(`\n${section.entries[j]}`);
117
+ const isLast = j === section.entries.length - 1;
118
+ if (cost + (isLast ? 0 : markerReserve) > remaining)
119
+ break;
120
+ kept[i].push(section.entries[j]);
121
+ remaining -= cost;
122
+ }
123
+ if (kept[i].length < section.entries.length) {
124
+ const marker = sectionMarker(section.label, kept[i].length, section.entries.length);
125
+ if (byteLen(marker) <= remaining) {
126
+ remaining -= byteLen(marker);
127
+ cut[i] = true;
128
+ }
129
+ }
130
+ }
131
+ let out = '';
132
+ for (let i = 0; i < sections.length; i++) {
133
+ const section = sections[i];
134
+ if (!headerEmitted[i])
135
+ continue;
136
+ out += sectionHeader(section);
137
+ for (const entry of kept[i])
138
+ out += `\n${entry}`;
139
+ if (cut[i])
140
+ out += sectionMarker(section.label, kept[i].length, section.entries.length);
141
+ }
142
+ return out;
143
+ }
61
144
  export function truncateContent(text, maxBytes = MAX_BYTES, contentUrl,
62
145
  // `reserve`: content appended immediately after `text`, budgeted SEPARATELY from
63
146
  // `text` (capped at MAX_RESERVE_FRACTION of maxBytes) so it survives even when
64
147
  // `text` alone already fills the whole budget - e.g. render-scrape.ts's
65
148
  // links/images blocks, which used to be appended into the same tail-truncated
66
149
  // string and were the first thing discarded (issue #2589 cr-1/cr-4).
150
+ //
151
+ // A {@link ReserveSection} array additionally gets entry-boundary cuts and per-section
152
+ // markers (issue #2687 item 6); a plain string keeps the byte-slice behavior verbatim,
153
+ // for callers with no entry structure to preserve.
67
154
  reserve = '',
68
155
  // Full delimiter templates (not just markers) whose trailing partial occurrence in
69
156
  // the truncated `text` should be stripped rather than left dangling (cr-8).
70
157
  dangleMarkers = []) {
158
+ const sections = typeof reserve === 'string' ? null : reserve;
159
+ const reserveText = typeof reserve === 'string' ? reserve : renderReserveSections(reserve, Infinity);
71
160
  const textBytes = Buffer.byteLength(text, 'utf8');
72
- const reserveBytes = Buffer.byteLength(reserve, 'utf8');
161
+ const reserveBytes = Buffer.byteLength(reserveText, 'utf8');
73
162
  if (textBytes + reserveBytes <= maxBytes) {
74
- return { text: text + reserve, truncated: false };
163
+ return { text: text + reserveText, truncated: false };
75
164
  }
76
165
  // Give the reserve block first claim on its own (capped) share of the budget, then
77
166
  // whatever remains to the primary text - the inverse of "reserve competes in the
@@ -91,7 +180,13 @@ dangleMarkers = []) {
91
180
  if (textBytes > textBudget) {
92
181
  slicedText = stripDanglingMarker(slicedText, dangleMarkers);
93
182
  }
94
- const slicedReserve = reserveBytes > reserveBudget ? sliceToBytes(reserve, reserveBudget) : reserve;
183
+ // A structured reserve re-renders under the budget (whole entries + per-section
184
+ // markers, issue #2687 item 6); a string reserve falls back to the raw byte slice.
185
+ const slicedReserve = reserveBytes > reserveBudget
186
+ ? sections === null
187
+ ? sliceToBytes(reserveText, reserveBudget)
188
+ : renderReserveSections(sections, reserveBudget)
189
+ : reserveText;
95
190
  const suffix = contentUrl
96
191
  ? `\n\n---\n[Content truncated. Full content available at: ${contentUrl}]`
97
192
  : '\n\n---\n[Content truncated at 100KB]';
@@ -1,6 +1,12 @@
1
1
  export function accountResource(server, client) {
2
2
  server.resource('account', 'bytekit://account', { description: 'Current ByteKit account details and usage' }, async () => {
3
- const [account, usage] = await Promise.all([client.getAccount(), client.getUsage()]);
3
+ // Serialized rather than issued concurrently: firing both requests at once is
4
+ // unkind to 1-rps plans (issue #2687 item 8). `get_account` was serialized for
5
+ // exactly this reason in #2591 item 3; this resource calls the same two endpoints
6
+ // and kept awaiting them together, so reading `bytekit://account` could still burn
7
+ // two requests inside the same second and rate-limit itself.
8
+ const account = await client.getAccount();
9
+ const usage = await client.getUsage();
4
10
  const text = JSON.stringify({ account, usage }, null, 2);
5
11
  return {
6
12
  contents: [
@@ -5,4 +5,14 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
5
  * stamps onto bundle entries (issue #2570).
6
6
  */
7
7
  export declare const SECTION_FILTER_DESCRIPTION: string;
8
+ /**
9
+ * The rejection text for a `section` value outside the taxonomy (issue #2687 item 9).
10
+ *
11
+ * A typo'd or invented section used to filter every entry away and return a bare `[]`,
12
+ * which is exactly what a correctly-spelled but empty section returns — so the agent
13
+ * could not tell a mistake from an honest absence, and had no route to the set that
14
+ * would have worked. Built from `DOC_SECTIONS`, like the filter description above, so
15
+ * the hint can never name a section the bundle cannot contain.
16
+ */
17
+ export declare function unknownSectionMessage(section: string): string;
8
18
  export declare function listDocsTool(server: McpServer): void;
@@ -7,6 +7,18 @@ import { DOC_SECTIONS } from '../docs-bundle/helpers.js';
7
7
  * stamps onto bundle entries (issue #2570).
8
8
  */
9
9
  export const SECTION_FILTER_DESCRIPTION = `Optional section filter. One of: ${DOC_SECTIONS.map((section) => `"${section}"`).join(', ')}`;
10
+ /**
11
+ * The rejection text for a `section` value outside the taxonomy (issue #2687 item 9).
12
+ *
13
+ * A typo'd or invented section used to filter every entry away and return a bare `[]`,
14
+ * which is exactly what a correctly-spelled but empty section returns — so the agent
15
+ * could not tell a mistake from an honest absence, and had no route to the set that
16
+ * would have worked. Built from `DOC_SECTIONS`, like the filter description above, so
17
+ * the hint can never name a section the bundle cannot contain.
18
+ */
19
+ export function unknownSectionMessage(section) {
20
+ return `Unknown section "${section}". Valid sections: ${DOC_SECTIONS.map((s) => `"${s}"`).join(', ')}. Omit the filter to list every page.`;
21
+ }
10
22
  export function listDocsTool(server) {
11
23
  server.tool('list_docs', 'List all pages in the ByteKit documentation bundle. Returns a section tree of { title, section, path } for every bundled page. Use the optional section filter to narrow results.', {
12
24
  section: z.string().optional().describe(SECTION_FILTER_DESCRIPTION),
@@ -19,6 +31,15 @@ export function listDocsTool(server) {
19
31
  path,
20
32
  }));
21
33
  if (params.section !== undefined) {
34
+ // Reject a section outside the taxonomy loudly (issue #2687 item 9) — the
35
+ // silent `[]` it used to produce is the same answer a legitimately-empty
36
+ // section gives, so a typo was unrecoverable from the tool output alone.
37
+ if (!DOC_SECTIONS.includes(params.section)) {
38
+ return {
39
+ isError: true,
40
+ content: [{ type: 'text', text: unknownSectionMessage(params.section) }],
41
+ };
42
+ }
22
43
  entries = entries.filter((e) => e.section === params.section);
23
44
  }
24
45
  return {
@@ -1,3 +1,28 @@
1
1
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import type { BytekitClient } from '../client.js';
3
+ /**
4
+ * Issue #2687 item 11 — EXCLUDE side of the unexposed-option decision table.
5
+ *
6
+ * These three `ScrapeRequest` options (docs/api/openapi.yaml) are deliberately absent
7
+ * from the schema below. Each exclusion is a decision with a reason, recorded here rather
8
+ * than only in the pull request, so a future re-exposure is a deliberate edit against a
9
+ * stated rationale instead of a silent drift. `unexposed-option decision (#2687 item 11)`
10
+ * in tools.test.ts pins the absence.
11
+ *
12
+ * - `clean_markdown` — billed at 3x credits AND 3x bytes on a successful clean
13
+ * (CLEAN_MARKDOWN_BILLING_MULTIPLIER, issue #1371). An MCP agent sets tool arguments
14
+ * with no confirmation step and no in-band cost signal, so a boolean that silently
15
+ * triples the operator's bill is not the agent's to flip.
16
+ * - `cache_ttl` — an operator/cost knob, not an agent one. A cache hit bills at 0.5x,
17
+ * so the only agent-visible effect of lowering the TTL is a higher bill, and the 48h
18
+ * default already suits read-mostly agent traffic.
19
+ * - `token_budget` — would create a SECOND truncation authority. This server already
20
+ * caps the rendered output at 100KB and says so in the render; the server-side token
21
+ * cut is reported only through the envelope's `markdown_tokens`, which this render
22
+ * does not surface. Two independent cuts with one visible signal is worse for the
23
+ * agent than one cut it can see. Reconsider once `markdown_tokens` is rendered.
24
+ *
25
+ * The EXPOSE side of the same table (screenshot `quality`/`dark_mode`/`country`/
26
+ * `language`) lives in screenshot-url.ts.
27
+ */
3
28
  export declare function scrapeUrlTool(server: McpServer, client: BytekitClient): void;
@@ -17,6 +17,31 @@ const PUBLIC_TO_INTERNAL_FORMAT = {
17
17
  function toInternalFormat(value) {
18
18
  return (PUBLIC_TO_INTERNAL_FORMAT[value] ?? value);
19
19
  }
20
+ /**
21
+ * Issue #2687 item 11 — EXCLUDE side of the unexposed-option decision table.
22
+ *
23
+ * These three `ScrapeRequest` options (docs/api/openapi.yaml) are deliberately absent
24
+ * from the schema below. Each exclusion is a decision with a reason, recorded here rather
25
+ * than only in the pull request, so a future re-exposure is a deliberate edit against a
26
+ * stated rationale instead of a silent drift. `unexposed-option decision (#2687 item 11)`
27
+ * in tools.test.ts pins the absence.
28
+ *
29
+ * - `clean_markdown` — billed at 3x credits AND 3x bytes on a successful clean
30
+ * (CLEAN_MARKDOWN_BILLING_MULTIPLIER, issue #1371). An MCP agent sets tool arguments
31
+ * with no confirmation step and no in-band cost signal, so a boolean that silently
32
+ * triples the operator's bill is not the agent's to flip.
33
+ * - `cache_ttl` — an operator/cost knob, not an agent one. A cache hit bills at 0.5x,
34
+ * so the only agent-visible effect of lowering the TTL is a higher bill, and the 48h
35
+ * default already suits read-mostly agent traffic.
36
+ * - `token_budget` — would create a SECOND truncation authority. This server already
37
+ * caps the rendered output at 100KB and says so in the render; the server-side token
38
+ * cut is reported only through the envelope's `markdown_tokens`, which this render
39
+ * does not surface. Two independent cuts with one visible signal is worse for the
40
+ * agent than one cut it can see. Reconsider once `markdown_tokens` is rendered.
41
+ *
42
+ * The EXPOSE side of the same table (screenshot `quality`/`dark_mode`/`country`/
43
+ * `language`) lives in screenshot-url.ts.
44
+ */
20
45
  export function scrapeUrlTool(server, client) {
21
46
  server.tool('scrape_url',
22
47
  // Deliberately keeps the description capability-derived (#2589 E3): this input
@@ -25,12 +50,20 @@ export function scrapeUrlTool(server, client) {
25
50
  // advertised here — it would be unreachable from this tool. Add a queue-reaching
26
51
  // field (e.g. `delay_ms`) or `async` to the schema below and update this
27
52
  // 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.', {
53
+ '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. Problems the API reports about the capture come back as warnings, rendered under a `Warnings (N):` section as one `code: message (element)` line each; `artifact_unavailable` there means a format you requested and were billed for is missing from this response, which is a different answer from the page having none of it.', {
29
54
  url: z.string().url().describe('The URL to scrape'),
55
+ // `.min(1)` mirrors docs/api/openapi.yaml ScrapeRequest.formats (`minItems: 1`)
56
+ // exactly (issue #2687 item 3). Before it, `params.formats ?? ['markdown']` only
57
+ // caught `undefined`, so an explicit `[]` travelled to the API and came back a
58
+ // 422. Option (b) of the ticket's Open Question was taken over remapping `[]` to
59
+ // the markdown default: an agent that sent `[]` asked for nothing, and a schema
60
+ // error at the boundary teaches it faster than a format it never requested. An
61
+ // ABSENT array is untouched by this and still falls through to the default below.
30
62
  formats: z
31
63
  .array(z.enum(['raw_html', 'rawHtml', 'html', 'markdown', 'links', 'images']))
64
+ .min(1, 'formats must list at least one format; omit it entirely for the markdown default')
32
65
  .optional()
33
- .describe('Content formats to return. Default: ["markdown"]. Options: markdown, raw_html (also accepts rawHtml), html, links, images.'),
66
+ .describe('Content formats to return. Default: ["markdown"]. Options: markdown, raw_html (also accepts rawHtml), html, links, images. Omit the parameter for the default; an empty array is rejected.'),
34
67
  country: z.string().optional().describe('Two-letter country code for geo-targeted scraping'),
35
68
  }, async (params) => {
36
69
  try {
@@ -6,6 +6,42 @@ export function screenshotUrlTool(server, client) {
6
6
  full_page: z.boolean().optional().describe('Capture the full scrollable page'),
7
7
  device: z.enum(['desktop', 'mobile']).optional().describe('Device type for rendering'),
8
8
  format: z.enum(['png', 'jpeg']).optional().describe('Image format'),
9
+ // ── Issue #2687 item 11, EXPOSE side of the decision table ──
10
+ // None of these is a field packages/gateway/src/scrape-core/can-fast-path.ts gates
11
+ // on, so exposing them cannot make the queued outcome reachable (E3).
12
+ //
13
+ // `quality` and `dark_mode` are cost-neutral: a screenshot bills on the phase-1
14
+ // HTML fetch's wire bytes x 1.5, never on the artifact's size, and neither option
15
+ // changes WHICH bytes are fetched. `country` and `language` are NOT cost-neutral —
16
+ // they change which page the origin serves, and therefore its phase-1 wire bytes.
17
+ // They are exposed anyway because `scrape_url` already exposes `country`, so the
18
+ // asymmetry (not the exposure) was the wart, and geo-targeting is unreachable from
19
+ // this tool otherwise.
20
+ //
21
+ // `quality`'s range is transcribed from docs/api/openapi.yaml ScreenshotRequest.
22
+ // `country` is a bare `z.string()` rather than the spec's `^[A-Z]{2}$` pattern,
23
+ // deliberately matching `scrape_url`'s existing convention of letting the API own
24
+ // the authoritative validation; a malformed code surfaces as the API's own 422.
25
+ // The EXCLUDE side of the table lives in scrape-url.ts.
26
+ quality: z
27
+ .number()
28
+ .int()
29
+ .min(1)
30
+ .max(100)
31
+ .optional()
32
+ .describe('JPEG quality 1-100 (default 80). Only affects format: "jpeg".'),
33
+ dark_mode: z
34
+ .boolean()
35
+ .optional()
36
+ .describe('Render the page in dark mode (prefers-color-scheme: dark)'),
37
+ country: z
38
+ .string()
39
+ .optional()
40
+ .describe('Uppercase two-letter country code for the proxy exit (e.g. US, DE)'),
41
+ language: z
42
+ .string()
43
+ .optional()
44
+ .describe('Two-letter language code for the page request (e.g. en, de)'),
9
45
  }, async (params) => {
10
46
  try {
11
47
  const result = await client.screenshot({
@@ -13,6 +49,10 @@ export function screenshotUrlTool(server, client) {
13
49
  full_page: params.full_page,
14
50
  device: params.device,
15
51
  format: params.format,
52
+ quality: params.quality,
53
+ dark_mode: params.dark_mode,
54
+ country: params.country,
55
+ language: params.language,
16
56
  });
17
57
  // If async (202), give polling instructions
18
58
  if (result.status === 'pending' || result.status === 'processing') {
@@ -78,8 +78,17 @@ export function webSearchTool(server, client) {
78
78
  // branch parses into errorCode, issue #2541) without exposing any
79
79
  // underlying provider name: the gateway's 502 body is a fixed constant, so
80
80
  // the client error message is already vendor-free.
81
+ //
82
+ // Append the code ONLY when the message does not already carry it (issue #2687
83
+ // item 2). client.ts's generic-envelope branch builds its message as
84
+ // `${code}: ${message}`, so the unconditional append produced the live
85
+ // `validation_error: … (validation_error)` — the same token twice, which reads
86
+ // like two distinct failures. The containment check keeps the code present
87
+ // exactly once whichever branch of handleErrorResponse produced the message.
81
88
  let message = error instanceof Error ? error.message : 'Unknown error';
82
- if (error instanceof BytekitApiError && error.errorCode) {
89
+ if (error instanceof BytekitApiError &&
90
+ error.errorCode &&
91
+ !message.includes(error.errorCode)) {
83
92
  message = `${message} (${error.errorCode})`;
84
93
  }
85
94
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hunt-labs/bytekit-mcp",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
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",