@hunt-labs/bytekit-mcp 0.2.0 → 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.
- package/CHANGELOG.md +86 -0
- package/README.md +74 -18
- package/dist/cli.d.ts +18 -1
- package/dist/cli.js +54 -7
- package/dist/client.d.ts +45 -0
- package/dist/client.js +225 -22
- package/dist/docs-bundle/docs-bundle.json +220 -210
- package/dist/docs-bundle/helpers.d.ts +33 -1
- package/dist/docs-bundle/helpers.js +47 -0
- package/dist/lib/render-scrape.d.ts +34 -0
- package/dist/lib/render-scrape.js +116 -0
- package/dist/lib/render-screenshot.js +6 -0
- package/dist/lib/truncate.d.ts +1 -1
- package/dist/lib/truncate.js +85 -12
- package/dist/scrape-contract.generated.d.ts +7 -2
- package/dist/tools/get-account.js +11 -3
- package/dist/tools/get-result.js +17 -3
- package/dist/tools/list-docs.d.ts +6 -0
- package/dist/tools/list-docs.js +8 -4
- package/dist/tools/scrape-url.js +31 -71
- package/dist/tools/search-docs.js +15 -1
- package/dist/tools/web-search.js +19 -3
- package/package.json +1 -1
- package/dist/docs-bundle/load-bundle.test.d.ts +0 -9
- package/dist/docs-bundle/load-bundle.test.js +0 -50
|
@@ -5,6 +5,22 @@
|
|
|
5
5
|
* without spinning up the Next.js server. The build script imports them at
|
|
6
6
|
* runtime; the test suite imports them for unit coverage.
|
|
7
7
|
*/
|
|
8
|
+
/**
|
|
9
|
+
* Every section label `slugToSection` can return.
|
|
10
|
+
*
|
|
11
|
+
* This is the single source of truth for the docs taxonomy: the bundle
|
|
12
|
+
* generator stamps `section` from `slugToSection`, and `list_docs` advertises
|
|
13
|
+
* its `section` filter values by joining this tuple. Adding a mapping below
|
|
14
|
+
* without adding its label here (or vice versa) is caught by the bundle
|
|
15
|
+
* invariant test in `src/__tests__/build-docs-bundle.test.ts`.
|
|
16
|
+
*
|
|
17
|
+
* `'General'` is the deliberate fallback for bare top-level pages
|
|
18
|
+
* (`changelog`, `introduction`, `mcp`, `quickstart`) — not a catch-all for
|
|
19
|
+
* unmapped directories (issue #2570).
|
|
20
|
+
*/
|
|
21
|
+
export declare const DOC_SECTIONS: readonly ["Guides", "API Reference", "SDK Reference", "CLI Reference", "Libraries", "General"];
|
|
22
|
+
/** One of the section labels enumerated by {@link DOC_SECTIONS}. */
|
|
23
|
+
export type DocSection = (typeof DOC_SECTIONS)[number];
|
|
8
24
|
/**
|
|
9
25
|
* Maps a page slug (array of path segments) to a human-readable section
|
|
10
26
|
* label for the bundle schema.
|
|
@@ -12,7 +28,7 @@
|
|
|
12
28
|
* Slug segments come from the fumadocs source manifest and mirror the
|
|
13
29
|
* directory structure under `content/docs/`.
|
|
14
30
|
*/
|
|
15
|
-
export declare function slugToSection(slug: string[]):
|
|
31
|
+
export declare function slugToSection(slug: string[]): DocSection;
|
|
16
32
|
/**
|
|
17
33
|
* Returns true for the root landing page, which should be excluded from
|
|
18
34
|
* the bundle (it contains only JSX nav cards, no prose content).
|
|
@@ -45,6 +61,22 @@ export declare function slugToUrlPath(slug: string[]): string;
|
|
|
45
61
|
* (the docs index, which keeps its HTML URL and has an empty slug), are ignored.
|
|
46
62
|
*/
|
|
47
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>;
|
|
48
80
|
/**
|
|
49
81
|
* Extracts the page title from the rendered markdown.
|
|
50
82
|
*
|
|
@@ -5,6 +5,27 @@
|
|
|
5
5
|
* without spinning up the Next.js server. The build script imports them at
|
|
6
6
|
* runtime; the test suite imports them for unit coverage.
|
|
7
7
|
*/
|
|
8
|
+
/**
|
|
9
|
+
* Every section label `slugToSection` can return.
|
|
10
|
+
*
|
|
11
|
+
* This is the single source of truth for the docs taxonomy: the bundle
|
|
12
|
+
* generator stamps `section` from `slugToSection`, and `list_docs` advertises
|
|
13
|
+
* its `section` filter values by joining this tuple. Adding a mapping below
|
|
14
|
+
* without adding its label here (or vice versa) is caught by the bundle
|
|
15
|
+
* invariant test in `src/__tests__/build-docs-bundle.test.ts`.
|
|
16
|
+
*
|
|
17
|
+
* `'General'` is the deliberate fallback for bare top-level pages
|
|
18
|
+
* (`changelog`, `introduction`, `mcp`, `quickstart`) — not a catch-all for
|
|
19
|
+
* unmapped directories (issue #2570).
|
|
20
|
+
*/
|
|
21
|
+
export const DOC_SECTIONS = [
|
|
22
|
+
'Guides',
|
|
23
|
+
'API Reference',
|
|
24
|
+
'SDK Reference',
|
|
25
|
+
'CLI Reference',
|
|
26
|
+
'Libraries',
|
|
27
|
+
'General',
|
|
28
|
+
];
|
|
8
29
|
/**
|
|
9
30
|
* Maps a page slug (array of path segments) to a human-readable section
|
|
10
31
|
* label for the bundle schema.
|
|
@@ -20,6 +41,10 @@ export function slugToSection(slug) {
|
|
|
20
41
|
return 'API Reference';
|
|
21
42
|
if (first === 'sdk')
|
|
22
43
|
return 'SDK Reference';
|
|
44
|
+
if (first === 'cli')
|
|
45
|
+
return 'CLI Reference';
|
|
46
|
+
if (first === 'libraries')
|
|
47
|
+
return 'Libraries';
|
|
23
48
|
return 'General';
|
|
24
49
|
}
|
|
25
50
|
/**
|
|
@@ -88,6 +113,28 @@ export function parseLlmsTxt(text) {
|
|
|
88
113
|
}
|
|
89
114
|
return slugs;
|
|
90
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
|
+
}
|
|
91
138
|
/**
|
|
92
139
|
* Extracts the page title from the rendered markdown.
|
|
93
140
|
*
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { ScrapeResult } from '../client.js';
|
|
2
|
+
/**
|
|
3
|
+
* Renders a scrape envelope (from POST /v1/scrape or GET /v1/scrape/{id}) into
|
|
4
|
+
* human-readable lines for MCP tool output.
|
|
5
|
+
*
|
|
6
|
+
* This is the single scrape formatter (issue #2538, E3). Both `scrape_url` (which
|
|
7
|
+
* produces an envelope) and `get_result` (which redeems an `sc_` handle) render through
|
|
8
|
+
* it, so the two surfaces cannot drift: a render-requiring scrape answered with 202 +
|
|
9
|
+
* queued envelope is described the same way whether the agent saw it at submit time or
|
|
10
|
+
* at poll time.
|
|
11
|
+
*
|
|
12
|
+
* Handles all three envelope shapes the API returns (scrape-contract.generated.ts):
|
|
13
|
+
* - queued: `{ status:'queued', id, url, status_url, queued_at, events }` — the async
|
|
14
|
+
* handle, and also what GET returns while the job is pending/processing (gateway
|
|
15
|
+
* routes/scrape.ts `handleGetScrapeById`). Non-error: the agent should poll, not fail.
|
|
16
|
+
* - failed: `{ status:'failed', id, error:{ code, message, ... } }` — flagged as a tool
|
|
17
|
+
* error, rendering the public error code + message only.
|
|
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).
|
|
27
|
+
*
|
|
28
|
+
* Every optional line is omitted when absent, so no `undefined`/`null` literal is ever
|
|
29
|
+
* emitted (issue #2419).
|
|
30
|
+
*/
|
|
31
|
+
export declare function renderScrapeResult(result: ScrapeResult): {
|
|
32
|
+
text: string;
|
|
33
|
+
isError: boolean;
|
|
34
|
+
};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { truncateContent } from './truncate.js';
|
|
2
|
+
function renderLinks(links) {
|
|
3
|
+
return links
|
|
4
|
+
.map((link) => typeof link === 'string' ? link : `${link.url}${link.text ? ` — ${link.text}` : ''}`)
|
|
5
|
+
.join('\n');
|
|
6
|
+
}
|
|
7
|
+
function renderImages(images) {
|
|
8
|
+
return images
|
|
9
|
+
.map((image) => typeof image === 'string' ? image : `${image.url}${image.alt ? ` — ${image.alt}` : ''}`)
|
|
10
|
+
.join('\n');
|
|
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`);
|
|
20
|
+
/**
|
|
21
|
+
* Renders a scrape envelope (from POST /v1/scrape or GET /v1/scrape/{id}) into
|
|
22
|
+
* human-readable lines for MCP tool output.
|
|
23
|
+
*
|
|
24
|
+
* This is the single scrape formatter (issue #2538, E3). Both `scrape_url` (which
|
|
25
|
+
* produces an envelope) and `get_result` (which redeems an `sc_` handle) render through
|
|
26
|
+
* it, so the two surfaces cannot drift: a render-requiring scrape answered with 202 +
|
|
27
|
+
* queued envelope is described the same way whether the agent saw it at submit time or
|
|
28
|
+
* at poll time.
|
|
29
|
+
*
|
|
30
|
+
* Handles all three envelope shapes the API returns (scrape-contract.generated.ts):
|
|
31
|
+
* - queued: `{ status:'queued', id, url, status_url, queued_at, events }` — the async
|
|
32
|
+
* handle, and also what GET returns while the job is pending/processing (gateway
|
|
33
|
+
* routes/scrape.ts `handleGetScrapeById`). Non-error: the agent should poll, not fail.
|
|
34
|
+
* - failed: `{ status:'failed', id, error:{ code, message, ... } }` — flagged as a tool
|
|
35
|
+
* error, rendering the public error code + message only.
|
|
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).
|
|
45
|
+
*
|
|
46
|
+
* Every optional line is omitted when absent, so no `undefined`/`null` literal is ever
|
|
47
|
+
* emitted (issue #2419).
|
|
48
|
+
*/
|
|
49
|
+
export function renderScrapeResult(result) {
|
|
50
|
+
if (result.status === 'queued') {
|
|
51
|
+
return {
|
|
52
|
+
text: [
|
|
53
|
+
`ID: ${result.id}`,
|
|
54
|
+
'Status: queued',
|
|
55
|
+
`URL: ${result.url}`,
|
|
56
|
+
`Status URL: ${result.status_url}`,
|
|
57
|
+
].join('\n'),
|
|
58
|
+
isError: false,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
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".
|
|
66
|
+
return {
|
|
67
|
+
text: [
|
|
68
|
+
`ID: ${result.id ?? '—'}`,
|
|
69
|
+
'Status: failed',
|
|
70
|
+
`Error: ${result.error.code}`,
|
|
71
|
+
result.error.message,
|
|
72
|
+
].join('\n'),
|
|
73
|
+
isError: true,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
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);
|
|
104
|
+
const metaLines = [
|
|
105
|
+
`ID: ${result.id}`,
|
|
106
|
+
`URL: ${result.url}`,
|
|
107
|
+
result.final_url !== result.url ? `Final URL: ${result.final_url}` : null,
|
|
108
|
+
result.status_code !== null ? `Status Code: ${result.status_code}` : null,
|
|
109
|
+
result.content_type ? `Content-Type: ${result.content_type}` : null,
|
|
110
|
+
result.metadata.title ? `Title: ${result.metadata.title}` : null,
|
|
111
|
+
truncated ? 'Note: Content was truncated to 100KB' : null,
|
|
112
|
+
]
|
|
113
|
+
.filter(Boolean)
|
|
114
|
+
.join('\n');
|
|
115
|
+
return { text: `${metaLines}\n\n---\n\n${text}`, isError: false };
|
|
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
|
}
|
package/dist/lib/truncate.d.ts
CHANGED
|
@@ -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
|
};
|
package/dist/lib/truncate.js
CHANGED
|
@@ -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
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
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
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
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:
|
|
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
|
-
/**
|
|
139
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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})`,
|
package/dist/tools/get-result.js
CHANGED
|
@@ -1,18 +1,32 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
+
import { renderScrapeResult } from '../lib/render-scrape.js';
|
|
2
3
|
import { renderScreenshotResult } from '../lib/render-screenshot.js';
|
|
3
4
|
export function getResultTool(server, client) {
|
|
4
|
-
server.tool('get_result', 'Get the result of a previous
|
|
5
|
-
id: z.string().describe('
|
|
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
|
+
id: z.string().describe('Result ID — ss_... (screenshot) or sc_... (scrape)'),
|
|
6
7
|
}, async (params) => {
|
|
7
8
|
try {
|
|
8
9
|
const id = params.id;
|
|
10
|
+
// Prefix dispatch: the id itself selects the resource, so one tool redeems both
|
|
11
|
+
// handle kinds (issue #2538). A render-requiring scrape answers 202 with an `sc_`
|
|
12
|
+
// id; before this, get_result rejected it outright and the handle was a dead end.
|
|
13
|
+
if (id.startsWith('sc_')) {
|
|
14
|
+
const result = await client.getScrape(id);
|
|
15
|
+
const { text, isError } = renderScrapeResult(result);
|
|
16
|
+
return {
|
|
17
|
+
...(isError ? { isError: true } : {}),
|
|
18
|
+
content: [{ type: 'text', text }],
|
|
19
|
+
};
|
|
20
|
+
}
|
|
9
21
|
if (!id.startsWith('ss_')) {
|
|
10
22
|
return {
|
|
11
23
|
isError: true,
|
|
12
24
|
content: [
|
|
13
25
|
{
|
|
14
26
|
type: 'text',
|
|
15
|
-
|
|
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}`,
|
|
16
30
|
},
|
|
17
31
|
],
|
|
18
32
|
};
|
|
@@ -1,2 +1,8 @@
|
|
|
1
1
|
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
/**
|
|
3
|
+
* The advertised description of the `section` filter, derived from
|
|
4
|
+
* `DOC_SECTIONS` so it can never drift from what `slugToSection` actually
|
|
5
|
+
* stamps onto bundle entries (issue #2570).
|
|
6
|
+
*/
|
|
7
|
+
export declare const SECTION_FILTER_DESCRIPTION: string;
|
|
2
8
|
export declare function listDocsTool(server: McpServer): void;
|
package/dist/tools/list-docs.js
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { loadBundle } from '../docs-bundle/load-bundle.js';
|
|
3
|
+
import { DOC_SECTIONS } from '../docs-bundle/helpers.js';
|
|
4
|
+
/**
|
|
5
|
+
* The advertised description of the `section` filter, derived from
|
|
6
|
+
* `DOC_SECTIONS` so it can never drift from what `slugToSection` actually
|
|
7
|
+
* stamps onto bundle entries (issue #2570).
|
|
8
|
+
*/
|
|
9
|
+
export const SECTION_FILTER_DESCRIPTION = `Optional section filter. One of: ${DOC_SECTIONS.map((section) => `"${section}"`).join(', ')}`;
|
|
3
10
|
export function listDocsTool(server) {
|
|
4
11
|
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.', {
|
|
5
|
-
section: z
|
|
6
|
-
.string()
|
|
7
|
-
.optional()
|
|
8
|
-
.describe('Optional section filter (e.g. "Guides", "API Reference", "SDK Reference")'),
|
|
12
|
+
section: z.string().optional().describe(SECTION_FILTER_DESCRIPTION),
|
|
9
13
|
}, async (params) => {
|
|
10
14
|
try {
|
|
11
15
|
const bundle = await loadBundle();
|
package/dist/tools/scrape-url.js
CHANGED
|
@@ -1,89 +1,49 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
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);
|
|
12
19
|
}
|
|
13
20
|
export function scrapeUrlTool(server, client) {
|
|
14
|
-
server.tool('scrape_url',
|
|
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.', {
|
|
15
29
|
url: z.string().url().describe('The URL to scrape'),
|
|
16
30
|
formats: z
|
|
17
|
-
.array(z.enum(['rawHtml', 'html', 'markdown', 'links', 'images']))
|
|
31
|
+
.array(z.enum(['raw_html', 'rawHtml', 'html', 'markdown', 'links', 'images']))
|
|
18
32
|
.optional()
|
|
19
|
-
.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.'),
|
|
20
34
|
country: z.string().optional().describe('Two-letter country code for geo-targeted scraping'),
|
|
21
35
|
}, async (params) => {
|
|
22
36
|
try {
|
|
23
|
-
const formats = params.formats ?? ['markdown'];
|
|
37
|
+
const formats = (params.formats ?? ['markdown']).map(toInternalFormat);
|
|
24
38
|
const result = await client.scrape({
|
|
25
39
|
url: params.url,
|
|
26
40
|
formats,
|
|
27
41
|
...(params.country !== undefined && { country: params.country }),
|
|
28
42
|
});
|
|
29
|
-
|
|
30
|
-
return {
|
|
31
|
-
content: [
|
|
32
|
-
{
|
|
33
|
-
type: 'text',
|
|
34
|
-
text: [
|
|
35
|
-
`ID: ${result.id}`,
|
|
36
|
-
'Status: queued',
|
|
37
|
-
`URL: ${result.url}`,
|
|
38
|
-
`Status URL: ${result.status_url}`,
|
|
39
|
-
].join('\n'),
|
|
40
|
-
},
|
|
41
|
-
],
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
if (result.status === 'failed') {
|
|
45
|
-
return {
|
|
46
|
-
isError: true,
|
|
47
|
-
content: [
|
|
48
|
-
{
|
|
49
|
-
type: 'text',
|
|
50
|
-
text: [
|
|
51
|
-
`ID: ${result.id}`,
|
|
52
|
-
'Status: failed',
|
|
53
|
-
`Error: ${result.error.code}`,
|
|
54
|
-
result.error.message,
|
|
55
|
-
].join('\n'),
|
|
56
|
-
},
|
|
57
|
-
],
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
// Primary content for display: prefer markdown → html → rawHtml
|
|
61
|
-
const content = result.formats.markdown ?? result.formats.html ?? result.formats.raw_html ?? '';
|
|
62
|
-
const { text, truncated } = truncateContent(content);
|
|
63
|
-
const metaLines = [
|
|
64
|
-
`ID: ${result.id}`,
|
|
65
|
-
`URL: ${result.url}`,
|
|
66
|
-
result.final_url !== result.url ? `Final URL: ${result.final_url}` : null,
|
|
67
|
-
result.status_code !== null ? `Status Code: ${result.status_code}` : null,
|
|
68
|
-
result.content_type ? `Content-Type: ${result.content_type}` : null,
|
|
69
|
-
result.metadata.title ? `Title: ${result.metadata.title}` : null,
|
|
70
|
-
truncated ? 'Note: Content was truncated to 100KB' : null,
|
|
71
|
-
]
|
|
72
|
-
.filter(Boolean)
|
|
73
|
-
.join('\n');
|
|
74
|
-
let body = `${metaLines}\n\n---\n\n${text}`;
|
|
75
|
-
// Append links block when present
|
|
76
|
-
if (Array.isArray(result.formats.links) && result.formats.links.length > 0) {
|
|
77
|
-
const linkList = renderLinks(result.formats.links);
|
|
78
|
-
body += `\n\nLinks (${result.formats.links.length}):\n${linkList}`;
|
|
79
|
-
}
|
|
80
|
-
// Append images block when present
|
|
81
|
-
if (Array.isArray(result.formats.images) && result.formats.images.length > 0) {
|
|
82
|
-
const imgList = renderImages(result.formats.images);
|
|
83
|
-
body += `\n\nImages (${result.formats.images.length}):\n${imgList}`;
|
|
84
|
-
}
|
|
43
|
+
const { text, isError } = renderScrapeResult(result);
|
|
85
44
|
return {
|
|
86
|
-
|
|
45
|
+
...(isError ? { isError: true } : {}),
|
|
46
|
+
content: [{ type: 'text', text }],
|
|
87
47
|
};
|
|
88
48
|
}
|
|
89
49
|
catch (error) {
|