@hunt-labs/bytekit-mcp 0.2.1 → 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.
@@ -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
  };
@@ -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;
@@ -1,16 +1,73 @@
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
+ }
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
+ */
3
45
  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.', {
46
+ server.tool('scrape_url',
47
+ // Deliberately keeps the description capability-derived (#2589 E3): this input
48
+ // schema exposes none of the fields packages/gateway/src/scrape-core/can-fast-path.ts
49
+ // gates on, nor a `body.async` field, so an async/202 slow-path outcome is not
50
+ // advertised here — it would be unreachable from this tool. Add a queue-reaching
51
+ // field (e.g. `delay_ms`) or `async` to the schema below and update this
52
+ // description to match (pinned by scrape-url-description-reachability.test.ts).
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.', {
5
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.
6
62
  formats: z
7
- .array(z.enum(['rawHtml', 'html', 'markdown', 'links', 'images']))
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')
8
65
  .optional()
9
- .describe('Content formats to return. Default: ["markdown"]. Options: markdown, 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.'),
10
67
  country: z.string().optional().describe('Two-letter country code for geo-targeted scraping'),
11
68
  }, async (params) => {
12
69
  try {
13
- const formats = params.formats ?? ['markdown'];
70
+ const formats = (params.formats ?? ['markdown']).map(toInternalFormat);
14
71
  const result = await client.scrape({
15
72
  url: params.url,
16
73
  formats,
@@ -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') {
@@ -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) {
@@ -66,8 +78,17 @@ export function webSearchTool(server, client) {
66
78
  // branch parses into errorCode, issue #2541) without exposing any
67
79
  // underlying provider name: the gateway's 502 body is a fixed constant, so
68
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.
69
88
  let message = error instanceof Error ? error.message : 'Unknown error';
70
- if (error instanceof BytekitApiError && error.errorCode) {
89
+ if (error instanceof BytekitApiError &&
90
+ error.errorCode &&
91
+ !message.includes(error.errorCode)) {
71
92
  message = `${message} (${error.errorCode})`;
72
93
  }
73
94
  return {
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.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",