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

+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)}`);
}
}
}