Add ReadWebpageTool

This commit is contained in:
Alex Gleason committed 2025-08-21 13:12:30 -05:00
1 parent a0c3bf02ec
commit 69453350a2
4 files changed
+396

No files matched your search

+34
View File
@@ -12,6 +12,7 @@
"@fontsource-variable/inter": "^5.2.6",
"@hookform/resolvers": "^3.9.0",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@radix-ui/react-accordion": "^1.2.0",
@@ -75,6 +76,7 @@
"sonner": "^1.5.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"turndown": "^7.2.1",
"use-stick-to-bottom": "^1.1.1",
"vaul": "^0.9.3",
"zod": "^3.25.76"
@@ -92,6 +94,7 @@
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/turndown": "^5.0.5",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.9.0",
@@ -1325,6 +1328,21 @@
"resolved": "https://npm.jsr.io/~/11/@jsr/std__internal/1.0.9.tgz",
"integrity": "sha512-s+f4qrJzZgPAy7XuFOtgaSaxyPLnnEmAfXGLvRXGxPTL76URLVHkF+hOzqXz+bmk8/awybF6BRsasxtAQOV23Q=="
},
"node_modules/@mixmark-io/domino": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@mixmark-io/domino/-/domino-2.2.0.tgz",
"integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==",
"license": "BSD-2-Clause"
},
"node_modules/@mozilla/readability": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.6.0.tgz",
"integrity": "sha512-juG5VWh4qAivzTAeMzvY9xs9HY5rAcr2E4I7tiSSCokRFi7XIZCAu92ZkSTsIj1OPceCifL3cpfteP3pDT9/QQ==",
"license": "Apache-2.0",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/@noble/ciphers": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-0.5.3.tgz",
@@ -3901,6 +3919,13 @@
"@types/react": "*"
}
},
"node_modules/@types/turndown": {
"version": "5.0.5",
"resolved": "https://registry.npmjs.org/@types/turndown/-/turndown-5.0.5.tgz",
"integrity": "sha512-TL2IgGgc7B5j78rIccBtlYAnkuv8nUQqhQc+DSYV5j9Be9XOcm/SKOVRuA47xAVI3680Tk9B1d8flK2GWT2+4w==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/unist": {
"version": "2.0.11",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",
@@ -10805,6 +10830,15 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/turndown": {
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/turndown/-/turndown-7.2.1.tgz",
"integrity": "sha512-7YiPJw6rLClQL3oUKN3KgMaXeJJ2lAyZItclgKDurqnH61so4k4IH/qwmMva0zpuJc/FhRExBBnk7EbeFANlgQ==",
"license": "MIT",
"dependencies": {
"@mixmark-io/domino": "^2.2.0"
}
},
"node_modules/type-check": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
+3
View File
@@ -14,6 +14,7 @@
"@fontsource-variable/inter": "^5.2.6",
"@hookform/resolvers": "^3.9.0",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@radix-ui/react-accordion": "^1.2.0",
@@ -77,6 +78,7 @@
"sonner": "^1.5.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"turndown": "^7.2.1",
"use-stick-to-bottom": "^1.1.1",
"vaul": "^0.9.3",
"zod": "^3.25.76"
@@ -94,6 +96,7 @@
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/turndown": "^5.0.5",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.9.0",
+236
View File
@@ -0,0 +1,236 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { JSDOM } from "jsdom";
import { ReadWebpageTool } from "./ReadWebpageTool";
// Mock fetch globally
const mockFetch = vi.fn();
global.fetch = mockFetch;
describe("ReadWebpageTool", () => {
let tool: ReadWebpageTool;
let domParser: DOMParser;
beforeEach(() => {
// Create a JSDOM instance for testing
const jsdom = new JSDOM();
domParser = new jsdom.window.DOMParser();
tool = new ReadWebpageTool(domParser);
mockFetch.mockClear();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("inputSchema", () => {
it("should validate valid URL", () => {
const result = tool.inputSchema.safeParse({
url: "https://example.com",
});
expect(result.success).toBe(true);
});
it("should reject invalid URL", () => {
const result = tool.inputSchema.safeParse({
url: "not-a-url",
});
expect(result.success).toBe(false);
});
});
describe("execute", () => {
it("should extract and convert article content to markdown", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<head>
<title>Test Article</title>
</head>
<body>
<article>
<h1>Main Article Title</h1>
<p>This is the main content of the article.</p>
<p>It has multiple paragraphs with <strong>bold text</strong> and <em>italic text</em>.</p>
<h2>Subsection</h2>
<ul>
<li>First item</li>
<li>Second item</li>
</ul>
</article>
<div class="sidebar">
<p>This is sidebar content that should be ignored.</p>
</div>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html; charset=utf-8"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/article",
});
expect(result).toContain("# Test Article");
expect(result).toContain("**Source:** https://example.com/article");
expect(result).toContain("Main Article Title");
expect(result).toContain("**bold text**");
expect(result).toContain("*italic text*");
expect(result).toContain("## Subsection");
expect(result).toContain("* First item");
expect(result).toContain("* Second item");
});
it("should handle articles with metadata", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<head>
<title>Article with Metadata</title>
<meta name="author" content="John Doe">
<meta name="description" content="This is a test article description">
</head>
<body>
<article>
<header>
<h1>Article with Metadata</h1>
<p class="byline">By John Doe</p>
<time datetime="2023-01-01">January 1, 2023</time>
</header>
<p>Main article content goes here.</p>
</article>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/article-with-metadata",
});
expect(result).toContain("# Article with Metadata");
expect(result).toContain("**Source:** https://example.com/article-with-metadata");
});
it("should handle code blocks properly", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<body>
<article>
<h1>Code Example</h1>
<p>Here's some code:</p>
<pre><code class="language-javascript">
function hello() {
console.log("Hello, world!");
}
</code></pre>
<p>And some inline <code>code</code> too.</p>
</article>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/code-example",
});
expect(result).toContain("```");
expect(result).toContain("function hello()");
expect(result).toContain("`code`");
});
it("should handle HTTP errors", async () => {
const mockResponse = {
ok: false,
status: 404,
statusText: "Not Found",
};
mockFetch.mockResolvedValue(mockResponse);
await expect(tool.execute({
url: "https://example.com/not-found",
})).rejects.toThrow("HTTP 404: Not Found");
});
it("should handle non-HTML content", async () => {
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("application/json"),
},
text: vi.fn().mockResolvedValue('{"data": "json"}'),
};
mockFetch.mockResolvedValue(mockResponse);
await expect(tool.execute({
url: "https://api.example.com/data.json",
})).rejects.toThrow("Expected HTML content, but received: application/json");
});
it("should handle network errors", async () => {
mockFetch.mockRejectedValue(new TypeError("Failed to fetch"));
await expect(tool.execute({
url: "https://example.com",
})).rejects.toThrow("Network error: Unable to fetch https://example.com");
});
it("should handle pages with minimal content", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<body>
<div class="navigation">Nav content</div>
<div class="footer">Footer content</div>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/minimal-content",
});
expect(result).toContain("# Untitled");
expect(result).toContain("**Source:** https://example.com/minimal-content");
});
it("should handle invalid URLs", async () => {
await expect(tool.execute({
url: "invalid-url",
})).rejects.toThrow("Failed to read webpage invalid-url");
});
});
});
+123
View File
@@ -0,0 +1,123 @@
import { Readability } from "@mozilla/readability";
import TurndownService from "turndown";
import { z } from "zod";
import type { Tool } from "./Tool";
interface ReadWebpageParams {
url: string;
}
export class ReadWebpageTool implements Tool<ReadWebpageParams> {
private domParser: DOMParser;
private turndownService: TurndownService;
readonly description = "Read and extract the main content from a webpage, converting it to markdown";
readonly inputSchema = z.object({
url: z.string().url().describe(
"The URL of the webpage to read and extract content from"
),
});
constructor(domParser: DOMParser) {
this.domParser = domParser;
this.turndownService = new TurndownService({
headingStyle: "atx",
codeBlockStyle: "fenced",
fence: "```",
emDelimiter: "*",
strongDelimiter: "**",
linkStyle: "inlined",
linkReferenceStyle: "full",
});
// Configure turndown to preserve code blocks and improve formatting
this.turndownService.addRule("preserveCodeBlocks", {
filter: ["pre"],
replacement: (content, node) => {
const codeElement = node.querySelector("code");
if (codeElement) {
const language = codeElement.className.match(/language-(\w+)/)?.[1] || "";
return `\n\n\`\`\`${language}\n${codeElement.textContent || content}\n\`\`\`\n\n`;
}
return `\n\n\`\`\`\n${content}\n\`\`\`\n\n`;
},
});
// Improve table handling
this.turndownService.addRule("tables", {
filter: "table",
replacement: (content) => {
return `\n\n${content}\n\n`;
},
});
}
async execute(args: ReadWebpageParams): Promise<string> {
const { url } = args;
try {
// Validate URL format
new URL(url);
// Fetch the webpage
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const contentType = response.headers.get("content-type") || "";
if (!contentType.includes("text/html")) {
throw new Error(`Expected HTML content, but received: ${contentType}`);
}
const html = await response.text();
// Parse the HTML
const doc = this.domParser.parseFromString(html, "text/html");
// Use Readability to extract the main content
const reader = new Readability(doc, {
debug: false,
maxElemsToParse: 0, // No limit
nbTopCandidates: 5,
charThreshold: 500,
classesToPreserve: ["highlight", "code", "pre"],
});
const article = reader.parse();
if (!article) {
throw new Error("Could not extract readable content from the webpage");
}
// Convert the extracted HTML content to markdown
const markdown = this.turndownService.turndown(article.content || "");
// Create a formatted result with metadata
const result = [
`# ${article.title || "Untitled"}`,
"",
article.excerpt ? `${article.excerpt}` : "",
article.excerpt ? "" : "",
`**Source:** ${url}`,
article.byline ? `**Author:** ${article.byline}` : "",
article.publishedTime ? `**Published:** ${article.publishedTime}` : "",
"",
"---",
"",
markdown,
].filter(Boolean).join("\n");
return result;
} catch (error) {
if (error instanceof TypeError && error.message.includes("fetch")) {
throw new Error(`Network error: Unable to fetch ${url}. ${error.message}`);
}
throw new Error(`Failed to read webpage ${url}: ${error instanceof Error ? error.message : String(error)}`);
}
}
}