searchfetch 3.3.3 → 4.0.0

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/src/compose.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Render extracted sections as Markdown and paginate tool output.
3
+ *
4
+ * Mirrors `searchfetch/compose.py`; `tests/fixtures/composition.json` keeps them in sync.
5
+ */
6
+ export const NO_CONTENT = "(No content extracted from this page.)";
7
+
8
+ const SECTION_SEPARATOR = "\n\n---\n\n";
9
+
10
+ /** Case-insensitive lookup of the first non-empty field among `keys`. */
11
+ export function field(record, ...keys) {
12
+ const wanted = keys.map((key) => key.toLowerCase());
13
+ for (const key of wanted) {
14
+ for (const [name, value] of Object.entries(record)) {
15
+ if (name.toLowerCase() === key && String(value ?? "").trim()) return String(value).trim();
16
+ }
17
+ }
18
+ return "";
19
+ }
20
+
21
+ /** Records whose first item has an author/user and a comment/body render as a thread. */
22
+ function isThread(items) {
23
+ return Boolean(
24
+ items.length && field(items[0], "author", "user") && field(items[0], "comment", "body"),
25
+ );
26
+ }
27
+
28
+ function renderRecords({ name, items }) {
29
+ if (isThread(items)) {
30
+ const comments = items
31
+ .map((item) => {
32
+ const author = field(item, "author", "user");
33
+ const comment = field(item, "comment", "body");
34
+ return author ? `**${author}:**\n\n${comment}` : comment;
35
+ })
36
+ .filter(Boolean);
37
+ return comments.length ? `## ${name}\n\n${comments.join(SECTION_SEPARATOR)}` : "";
38
+ }
39
+ const records = items
40
+ .map((item) =>
41
+ Object.entries(item)
42
+ .map(([key, value]) => [key, String(value ?? "").trim()])
43
+ .filter(([, value]) => value)
44
+ .map(([key, value]) => ` ${key}: ${value}`)
45
+ .join("\n"),
46
+ )
47
+ .filter(Boolean);
48
+ return records.length ? `## ${name}\n\n${records.join("\n\n")}` : "";
49
+ }
50
+
51
+ function renderSection(section) {
52
+ switch (section.type) {
53
+ case "value": {
54
+ const value = String(section.value ?? "").trim();
55
+ return value ? `## ${section.name}\n\n${value}` : "";
56
+ }
57
+ case "list": {
58
+ const items = section.items.map((item) => String(item).trim()).filter(Boolean);
59
+ return items.length ? `## ${section.name}\n\n${items.map((i) => `- ${i}`).join("\n")}` : "";
60
+ }
61
+ case "group":
62
+ return Object.entries(section.fields)
63
+ .map(([name, value]) => [name, String(value ?? "").trim()])
64
+ .filter(([, value]) => value)
65
+ .map(([name, value]) => `## ${name}\n\n${value}`)
66
+ .join(SECTION_SEPARATOR);
67
+ case "records":
68
+ return renderRecords(section);
69
+ default:
70
+ throw new Error(`Unknown section type '${section.type}'.`);
71
+ }
72
+ }
73
+
74
+ /** Render `webfetch` sections; empty sections are skipped. */
75
+ export function composeSections(sections) {
76
+ const parts = sections.map(renderSection).filter(Boolean);
77
+ return parts.length ? parts.join(SECTION_SEPARATOR) : NO_CONTENT;
78
+ }
79
+
80
+ function cleanResultUrl(value) {
81
+ let url;
82
+ try {
83
+ url = new URL(value);
84
+ } catch {
85
+ return "";
86
+ }
87
+ const isGoogleInternal =
88
+ url.hostname === "support.google.com" ||
89
+ (["google.com", "www.google.com"].includes(url.hostname) && url.pathname === "/search");
90
+ return ["http:", "https:"].includes(url.protocol) && !isGoogleInternal ? value : "";
91
+ }
92
+
93
+ /**
94
+ * Render a search-results records section as a numbered list. Untitled results are skipped;
95
+ * non-web and search-engine-internal URLs are dropped.
96
+ */
97
+ export function composeSearchResults({ name, items }) {
98
+ const results = [];
99
+ for (const item of items) {
100
+ const title = field(item, "title");
101
+ if (!title) continue;
102
+ const lines = [`[${results.length + 1}] ${title}`];
103
+ const url = cleanResultUrl(field(item, "url"));
104
+ const snippet = field(item, "snippet");
105
+ if (url) lines.push(` URL: ${url}`);
106
+ if (snippet) lines.push(` Snippet: ${snippet}`);
107
+ results.push(lines.join("\n"));
108
+ }
109
+ return results.length ? `## ${name}\n\n${results.join("\n\n")}` : NO_CONTENT;
110
+ }
111
+
112
+ /**
113
+ * Return one page of `text`, counted in Unicode code points so offsets agree with Python and
114
+ * never split a surrogate pair, followed by a footer describing the window.
115
+ */
116
+ export function paginate(text, templateName, startIndex, maxLength) {
117
+ const characters = Array.from(text);
118
+ const start = Math.min(startIndex, characters.length);
119
+ const end = Math.min(start + maxLength, characters.length);
120
+ const more = end < characters.length ? ` Use start_index=${end} to read more.` : "";
121
+ return (
122
+ `${characters.slice(start, end).join("")}\n\n---\n` +
123
+ `[webfetch: template="${templateName}", showing characters ${start} to ${end} ` +
124
+ `of ${characters.length} total.${more}]`
125
+ );
126
+ }
package/src/extract.js ADDED
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Template-driven extraction from a parsed HTML document (cheerio).
3
+ *
4
+ * Mirrors `searchfetch/extract.py`; shared fixtures in `tests/fixtures/` keep them in sync.
5
+ */
6
+ import { htmlToMarkdown } from "./markdown.js";
7
+
8
+ /** Removed before extraction when a template does not declare its own `remove` list. */
9
+ export const DEFAULT_REMOVE = [
10
+ "script",
11
+ "style",
12
+ "svg",
13
+ "nav",
14
+ "footer",
15
+ "noscript",
16
+ "iframe",
17
+ ".advertisement",
18
+ ];
19
+
20
+ /** Removed before converting a page that matched no template. */
21
+ export const FALLBACK_REMOVE = [
22
+ ...DEFAULT_REMOVE,
23
+ "header",
24
+ "aside",
25
+ "img",
26
+ "picture",
27
+ "video",
28
+ "audio",
29
+ "canvas",
30
+ "map",
31
+ "area",
32
+ "dialog",
33
+ ];
34
+
35
+ /**
36
+ * Split a selector list into ordered fallbacks on top-level commas, preserving commas inside
37
+ * CSS functions, attribute brackets, quoted strings, and escapes.
38
+ */
39
+ export function splitSelectors(value = "") {
40
+ const selectors = [];
41
+ let start = 0;
42
+ let depth = 0;
43
+ let quote = null;
44
+ for (let i = 0; i < value.length; i++) {
45
+ const char = value[i];
46
+ if (char === "\\") {
47
+ i++;
48
+ } else if (quote) {
49
+ if (char === quote) quote = null;
50
+ } else if (char === '"' || char === "'") {
51
+ quote = char;
52
+ } else if (char === "(" || char === "[") {
53
+ depth++;
54
+ } else if (char === ")" || char === "]") {
55
+ depth--;
56
+ } else if (char === "," && depth === 0) {
57
+ selectors.push(value.slice(start, i).trim());
58
+ start = i + 1;
59
+ }
60
+ }
61
+ selectors.push(value.slice(start).trim());
62
+ return selectors;
63
+ }
64
+
65
+ /** Remove noise elements, inline styles, and embedded images from the document in place. */
66
+ export function cleanDocument($, removeSelectors = DEFAULT_REMOVE) {
67
+ for (const selector of removeSelectors) {
68
+ try {
69
+ $(selector).remove();
70
+ } catch {
71
+ // Selector support differs between runtimes; an unsupported cleanup rule is skipped.
72
+ }
73
+ }
74
+ $("[style]").removeAttr("style");
75
+ $("[src^='data:']").removeAttr("src");
76
+ }
77
+
78
+ /** First fallback that matches anywhere in the document; an empty fallback selects `<body>`. */
79
+ function selectInDocument($, selectorList) {
80
+ for (const selector of splitSelectors(selectorList)) {
81
+ const matches = selector ? $(selector) : $("body");
82
+ if (matches.length) return matches;
83
+ }
84
+ return $([]);
85
+ }
86
+
87
+ /**
88
+ * First fallback that matches inside `$scope` or on `$scope`/its ancestors. Never searches
89
+ * sibling subtrees, so a record cannot borrow a field from its neighbor. An empty fallback
90
+ * selects `$scope` itself.
91
+ */
92
+ export function selectInScope($scope, selectorList) {
93
+ for (const selector of splitSelectors(selectorList)) {
94
+ if (!selector) return $scope;
95
+ const descendants = $scope.find(selector);
96
+ if (descendants.length) return descendants;
97
+ const ancestor = $scope.closest(selector);
98
+ if (ancestor.length) return ancestor;
99
+ }
100
+ return $scope.slice(0, 0);
101
+ }
102
+
103
+ export function applyTransforms(value, transform, pageUrl) {
104
+ let result = value;
105
+ for (const name of [transform ?? []].flat()) {
106
+ if (!result) break;
107
+ result = TRANSFORM_FUNCTIONS[name](result, pageUrl);
108
+ }
109
+ return result;
110
+ }
111
+
112
+ const TRANSFORM_FUNCTIONS = {
113
+ strip: (value) => value.trim(),
114
+ decode_google_url(value) {
115
+ if (!value.startsWith("/url?")) return value;
116
+ return new URLSearchParams(value.slice("/url?".length)).get("q") ?? value;
117
+ },
118
+ decode_ddg_url(value) {
119
+ if (!value.includes("/l/?")) return value;
120
+ return new URLSearchParams(value.slice(value.indexOf("?") + 1)).get("uddg") ?? value;
121
+ },
122
+ json_parse(value) {
123
+ try {
124
+ return JSON.stringify(JSON.parse(value), null, 2);
125
+ } catch {
126
+ return value;
127
+ }
128
+ },
129
+ resolve_href(value, pageUrl) {
130
+ try {
131
+ return pageUrl ? new URL(value, pageUrl).href : value;
132
+ } catch {
133
+ return value;
134
+ }
135
+ },
136
+ };
137
+
138
+ const collapseWhitespace = (text) => text.replace(/\s+/g, " ").trim();
139
+
140
+ /** Extract one field value from the first element of `$element`. */
141
+ export function extractValue($element, section, pageUrl) {
142
+ let value;
143
+ switch (section.format ?? "text") {
144
+ case "markdown":
145
+ value = htmlToMarkdown($element.html() ?? "");
146
+ break;
147
+ case "attribute":
148
+ value = $element.attr(section.attribute) ?? "";
149
+ break;
150
+ case "html":
151
+ value = ($element.html() ?? "").trim();
152
+ break;
153
+ default:
154
+ value = collapseWhitespace($element.text());
155
+ }
156
+ return applyTransforms(value, section.transform, pageUrl);
157
+ }
158
+
159
+ /** Extract child fields from one record element; empty fields are omitted. */
160
+ function extractFields($scope, section, pageUrl) {
161
+ const fields = {};
162
+ for (const child of section.children) {
163
+ const matches = selectInScope($scope, child.selector);
164
+ if (!matches.length) {
165
+ if (child.required) {
166
+ throw new Error(`Required field '${child.name}' not found in section '${section.name}'.`);
167
+ }
168
+ continue;
169
+ }
170
+ const value = extractValue(matches.first(), child, pageUrl);
171
+ if (value) fields[child.name] = value;
172
+ }
173
+ return fields;
174
+ }
175
+
176
+ /**
177
+ * Extract one top-level section. Result shapes:
178
+ * - `{ name, type: "value", value }` — single element, no children
179
+ * - `{ name, type: "list", items: string[] }` — `multiple`, no children
180
+ * - `{ name, type: "group", fields: {} }` — single element with children
181
+ * - `{ name, type: "records", items: {}[] }` — `multiple` with children
182
+ */
183
+ export function extractSection($, section, { pageUrl = "", limit } = {}) {
184
+ const { name } = section;
185
+ const hasChildren = Boolean(section.children?.length);
186
+ const matches = selectInDocument($, section.selector ?? "");
187
+ if (!matches.length && section.required) {
188
+ throw new Error(`Required section '${name}' not found on page.`);
189
+ }
190
+
191
+ if (!section.multiple) {
192
+ const $first = matches.first();
193
+ if (hasChildren) {
194
+ return {
195
+ name,
196
+ type: "group",
197
+ fields: matches.length ? extractFields($first, section, pageUrl) : {},
198
+ };
199
+ }
200
+ return {
201
+ name,
202
+ type: "value",
203
+ value: matches.length ? extractValue($first, section, pageUrl) : "",
204
+ };
205
+ }
206
+
207
+ const elements = matches.toArray().slice(0, limit ?? section.max_items ?? Infinity);
208
+ if (hasChildren) {
209
+ const items = elements
210
+ .map((element) => extractFields($(element), section, pageUrl))
211
+ .filter((fields) => Object.keys(fields).length > 0);
212
+ return { name, type: "records", items };
213
+ }
214
+ const items = elements
215
+ .map((element) => extractValue($(element), section, pageUrl).trim())
216
+ .filter(Boolean);
217
+ return { name, type: "list", items };
218
+ }
219
+
220
+ /**
221
+ * Clean the document and extract every template section. `maxResults` overrides `max_items`
222
+ * of the first records section (the search results of a search template).
223
+ */
224
+ export function extractTemplate($, template, { pageUrl = "", maxResults } = {}) {
225
+ cleanDocument($, template.remove ?? DEFAULT_REMOVE);
226
+ let limitPending = maxResults != null;
227
+ return template.sections.map((section) => {
228
+ const isRecords = Boolean(section.multiple && section.children?.length);
229
+ const limit = limitPending && isRecords ? maxResults : undefined;
230
+ if (limit !== undefined) limitPending = false;
231
+ return extractSection($, section, { pageUrl, limit });
232
+ });
233
+ }
package/src/index.js ADDED
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env node
2
+ /** Command-line entry point: serve searchfetch over MCP stdio. */
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { ensureBinary } from "cloakbrowser";
5
+ import { BrowserManager } from "./browser.js";
6
+ import { createServer } from "./server.js";
7
+
8
+ /** stdout carries the MCP protocol, so route anything printed during setup to stderr. */
9
+ async function withStdoutOnStderr(task) {
10
+ const { write } = process.stdout;
11
+ const { log, info } = console;
12
+ process.stdout.write = process.stderr.write.bind(process.stderr);
13
+ console.log = console.info = console.error;
14
+ try {
15
+ return await task();
16
+ } finally {
17
+ process.stdout.write = write;
18
+ Object.assign(console, { log, info });
19
+ }
20
+ }
21
+
22
+ const browser = new BrowserManager();
23
+ let shuttingDown = false;
24
+
25
+ async function shutdown(code = 0) {
26
+ if (shuttingDown) return;
27
+ shuttingDown = true;
28
+ try {
29
+ await browser.close();
30
+ } finally {
31
+ process.exit(code);
32
+ }
33
+ }
34
+
35
+ process.on("SIGINT", () => shutdown());
36
+ process.on("SIGTERM", () => shutdown());
37
+
38
+ try {
39
+ await withStdoutOnStderr(() => ensureBinary());
40
+ await createServer(browser).connect(new StdioServerTransport());
41
+ process.stdin.once("end", () => shutdown());
42
+ } catch (err) {
43
+ console.error(err);
44
+ await shutdown(1);
45
+ }
@@ -0,0 +1,50 @@
1
+ /** HTML-to-Markdown conversion and detection of raw Markdown sources. */
2
+ import TurndownService from "turndown";
3
+
4
+ const turndown = new TurndownService({
5
+ headingStyle: "atx",
6
+ codeBlockStyle: "fenced",
7
+ bulletListMarker: "-",
8
+ emDelimiter: "*",
9
+ });
10
+
11
+ export const collapseBlankLines = (text) => text.replace(/\n{3,}/g, "\n\n").trim();
12
+
13
+ export function htmlToMarkdown(html) {
14
+ return collapseBlankLines(turndown.turndown(html));
15
+ }
16
+
17
+ const HTML_TAG = /<\w+[^>]*>/g;
18
+ const MARKDOWN_SIGNALS = [
19
+ /^#{1,6}\s+\S/m,
20
+ /\[.+?\]\(.+?\)/,
21
+ /```\w*\n/,
22
+ /^\s*[-*+]\s+\S/m,
23
+ /\*\*[^*]+\*\*/,
24
+ /^>\s+\S/m,
25
+ ];
26
+
27
+ /** Heuristic: text with Markdown syntax and at most three HTML tags. */
28
+ export function isMarkdown(text) {
29
+ if (!text || (text.match(HTML_TAG) ?? []).length > 3) return false;
30
+ return MARKDOWN_SIGNALS.some((pattern) => pattern.test(text));
31
+ }
32
+
33
+ /** Drop build-tool artifacts (e.g. Twoslash caches) and redundant blank lines. */
34
+ export function cleanSourceMarkdown(text) {
35
+ return collapseBlankLines(text.replace(/^@twoslash-cache:.*$/gm, ""));
36
+ }
37
+
38
+ /**
39
+ * Resolve a template `source_url`. `{url}.md` appends `.md` to the path (keeping the query and
40
+ * dropping the fragment); any other `{url}` placeholder is replaced verbatim.
41
+ */
42
+ export function resolveSourceUrl(sourceTemplate, url) {
43
+ if (sourceTemplate === "{url}.md") {
44
+ const parsed = new URL(url);
45
+ parsed.pathname = `${parsed.pathname.replace(/\/+$/, "")}.md`;
46
+ parsed.hash = "";
47
+ return parsed.href;
48
+ }
49
+ return sourceTemplate.replaceAll("{url}", url);
50
+ }
package/src/server.js ADDED
@@ -0,0 +1,174 @@
1
+ /** MCP server exposing the `websearch` and `webfetch` tools. Mirrors `searchfetch/server.py`. */
2
+ import { readFileSync } from "node:fs";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import * as cheerio from "cheerio";
5
+ import { z } from "zod";
6
+ import { BrowserManager, fetchHtml, fetchSourceMarkdown } from "./browser.js";
7
+ import { NO_CONTENT, composeSearchResults, composeSections, paginate } from "./compose.js";
8
+ import { FALLBACK_REMOVE, cleanDocument, extractTemplate } from "./extract.js";
9
+ import { htmlToMarkdown, resolveSourceUrl } from "./markdown.js";
10
+ import { BUILTIN_TEMPLATES, resolvePageTemplate, resolveSearchCandidates } from "./templates.js";
11
+
12
+ export const VERSION = JSON.parse(
13
+ readFileSync(new URL("../package.json", import.meta.url), "utf8"),
14
+ ).version;
15
+
16
+ const PAGE_TEMPLATES = [...BUILTIN_TEMPLATES.values()]
17
+ .filter((template) => !template.url_template)
18
+ .map((template) => template.name);
19
+
20
+ const TOOL_ANNOTATIONS = { readOnlyHint: true, openWorldHint: true };
21
+
22
+ const blockMediaSchema = z
23
+ .boolean()
24
+ .default(true)
25
+ .describe("Block images, media and fonts at the network layer. Default: true.");
26
+
27
+ const websearchSchema = z.object({
28
+ query: z.string().trim().min(1).describe("The search query."),
29
+ engine: z
30
+ .string()
31
+ .default("duckduckgo")
32
+ .describe(
33
+ "'duckduckgo' (default), 'google', a search template name, or an inline JSON search " +
34
+ "template. Built-in engines fall back to DuckDuckGo when unavailable.",
35
+ ),
36
+ region: z
37
+ .string()
38
+ .nullable()
39
+ .default(null)
40
+ .describe(
41
+ "Region-language code such as 'us-en' or 'de-de'. DuckDuckGo uses it as-is; Google maps " +
42
+ "it to country (gl) and language (hl). Default: engine default.",
43
+ ),
44
+ safe_search: z
45
+ .boolean()
46
+ .nullable()
47
+ .default(null)
48
+ .describe("Enable (true) or disable (false) safe search. Default: engine default."),
49
+ max_results: z.int().positive().default(10).describe("Maximum results to return. Default: 10."),
50
+ block_media: blockMediaSchema,
51
+ });
52
+
53
+ const webfetchSchema = z.object({
54
+ url: z
55
+ .url({ protocol: /^https?$/, hostname: z.regexes.hostname })
56
+ .describe("Absolute http(s) URL of the page to fetch."),
57
+ template: z
58
+ .string()
59
+ .default("auto")
60
+ .describe(
61
+ `'auto' (detect from the URL), a template name (${PAGE_TEMPLATES.join(", ")}), or an ` +
62
+ "inline JSON template. 'raw' converts the whole page with minimal filtering.",
63
+ ),
64
+ start_index: z
65
+ .int()
66
+ .nonnegative()
67
+ .default(0)
68
+ .describe("Offset in characters (Unicode code points) for pagination. Default: 0."),
69
+ max_length: z
70
+ .int()
71
+ .positive()
72
+ .default(10_000)
73
+ .describe("Maximum characters to return. Default: 10000."),
74
+ block_media: blockMediaSchema,
75
+ });
76
+
77
+ const text = (value) => ({ content: [{ type: "text", text: value }] });
78
+ const failure = (prefix, err) => ({ ...text(`${prefix}: ${err.message}`), isError: true });
79
+
80
+ export async function websearch(browser, args) {
81
+ const { query, engine, region, safe_search, max_results, block_media } =
82
+ websearchSchema.parse(args);
83
+ const failures = [];
84
+ for (const { template, url } of resolveSearchCandidates(engine, query, region, safe_search)) {
85
+ try {
86
+ const html = await fetchHtml(browser, url, template, block_media);
87
+ const sections = extractTemplate(cheerio.load(html), template, {
88
+ pageUrl: url,
89
+ maxResults: max_results,
90
+ });
91
+ const results = sections.find((section) => section.type === "records");
92
+ const output = results ? composeSearchResults(results) : NO_CONTENT;
93
+ if (output === NO_CONTENT) throw new Error("no results extracted");
94
+ if (failures.length === 0) return output;
95
+ return `[websearch: ${failures.join("; ")}. Results are from ${template.name}.]\n\n${output}`;
96
+ } catch (err) {
97
+ failures.push(`${template.name} failed: ${err.message}`);
98
+ }
99
+ }
100
+ throw new Error(failures.join("; "));
101
+ }
102
+
103
+ export async function webfetch(browser, args) {
104
+ const {
105
+ url,
106
+ template: templateArg,
107
+ start_index,
108
+ max_length,
109
+ block_media,
110
+ } = webfetchSchema.parse(args);
111
+ const template = resolvePageTemplate(url, templateArg);
112
+ const templateName = template?.name ?? "auto (fallback)";
113
+
114
+ if (template?.source_url) {
115
+ const sourceUrl = resolveSourceUrl(template.source_url, url);
116
+ const markdown = await fetchSourceMarkdown(browser, sourceUrl, template, block_media);
117
+ if (markdown !== null) return paginate(markdown, templateName, start_index, max_length);
118
+ }
119
+
120
+ const $ = cheerio.load(await fetchHtml(browser, url, template, block_media));
121
+ let output;
122
+ if (template) {
123
+ output = composeSections(extractTemplate($, template, { pageUrl: url }));
124
+ } else {
125
+ cleanDocument($, FALLBACK_REMOVE);
126
+ output = htmlToMarkdown($("body").html() ?? $.html()) || NO_CONTENT;
127
+ }
128
+ return paginate(output, templateName, start_index, max_length);
129
+ }
130
+
131
+ /** Create the MCP server. The caller owns `browser` and must close it on shutdown. */
132
+ export function createServer(browser = new BrowserManager()) {
133
+ const server = new McpServer({ name: "searchfetch", version: VERSION });
134
+
135
+ server.registerTool(
136
+ "websearch",
137
+ {
138
+ title: "Web Search",
139
+ description:
140
+ "Search the web with DuckDuckGo or Google and return numbered results with titles, " +
141
+ "URLs and snippets.",
142
+ inputSchema: websearchSchema,
143
+ annotations: TOOL_ANNOTATIONS,
144
+ },
145
+ async (args) => {
146
+ try {
147
+ return text(await websearch(browser, args));
148
+ } catch (err) {
149
+ return failure("Search Error", err);
150
+ }
151
+ },
152
+ );
153
+
154
+ server.registerTool(
155
+ "webfetch",
156
+ {
157
+ title: "Web Fetch",
158
+ description:
159
+ "Fetch a web page in a JavaScript-capable stealth browser and return its main content " +
160
+ "as Markdown, with images, scripts and styles stripped. Long output is paginated.",
161
+ inputSchema: webfetchSchema,
162
+ annotations: TOOL_ANNOTATIONS,
163
+ },
164
+ async (args) => {
165
+ try {
166
+ return text(await webfetch(browser, args));
167
+ } catch (err) {
168
+ return failure("Fetch Error", err);
169
+ }
170
+ },
171
+ );
172
+
173
+ return server;
174
+ }