Add webfetch and websearch tools

This commit is contained in:
Alex Gleason committed 2026-01-21 23:25:29 -06:00
1 parent 79b336f967
commit 87956df961
10 files changed
+499 -429

No files matched your search

+3 -2
View File
@@ -41,7 +41,8 @@ Shakespeare provides AI agents with specialized tools for project development (n
- **NpmAddPackageTool**: Add npm packages to projects
- **NpmRemovePackageTool**: Remove npm packages from projects
- **GitCommitTool**: Commit changes to Git repositories
- **ReadWebpageTool**: Fetch and read web pages
- **WebFetchTool**: Fetch and read web pages with support for markdown, text, and HTML formats
- **WebSearchTool**: Search the web using Exa AI for real-time web searches
- **NostrReadNipTool**: Read Nostr protocol NIP documents
- **NostrReadKindTool**: Read Nostr event kind documentation
- **NostrReadTagTool**: Read Nostr tag documentation
@@ -232,7 +233,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
- Git integration: `GitCommitTool`
- Shell access: `ShellTool`
- Web access: `ReadWebpageTool`
- Web access: `WebFetchTool`, `WebSearchTool`
- Nostr tools: `NostrReadNipTool`, `NostrFetchEventTool`, `NostrGenerateKindTool`, etc.
- `/src/contexts/`: React context providers
- `AppContext`: Global app configuration and theme
+4
View File
@@ -41,6 +41,8 @@ import { SkillTool } from '@/lib/tools/SkillTool';
import { GenerateImageTool } from '@/lib/tools/GenerateImageTool';
import { ViewAvailableModelsTool } from '@/lib/tools/ViewAvailableModelsTool';
import { ConfigureImageGenerationTool } from '@/lib/tools/ConfigureImageGenerationTool';
import { WebFetchTool } from '@/lib/tools/WebFetchTool';
import { WebSearchTool } from '@/lib/tools/WebSearchTool';
import { createMCPTools } from '@/lib/tools/MCPTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
@@ -199,6 +201,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer),
read_console_messages: new ReadConsoleMessagesTool(),
skill: new SkillTool(fs, pluginsPath, cwd),
webfetch: new WebFetchTool({ corsProxy: config.corsProxy }),
websearch: new WebSearchTool(),
};
// Add generate_image tool if imageModel is configured
+87 -67
View File
@@ -105,9 +105,9 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
case 'shell':
return {
icon: Terminal,
title: args.command ? String(args.command) : 'Shell Command',
callingTitle: args.command ? String(args.command) : 'Running Shell Command',
errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell Command Failed',
title: args.command ? String(args.command) : 'Shell command',
callingTitle: args.command ? String(args.command) : 'Running shell command',
errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell command failed',
};
// New tools (OpenCode-compatible names)
@@ -132,9 +132,9 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: FileText,
title: path ? `Wrote ${path}` : 'Wrote File',
callingTitle: path ? `Writing ${path}` : 'Writing File',
errorTitle: path ? `Failed to write ${path}` : 'Failed to Write File',
title: path ? `Wrote ${path}` : 'Wrote file',
callingTitle: path ? `Writing ${path}` : 'Writing file',
errorTitle: path ? `Failed to write ${path}` : 'Failed to write file',
};
}
@@ -143,26 +143,26 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: Edit,
title: path ? `Edited ${path}` : 'Edited File',
callingTitle: path ? `Editing ${path}` : 'Editing File',
errorTitle: path ? `Failed to edit ${path}` : 'Failed to Edit File',
title: path ? `Edited ${path}` : 'Edited file',
callingTitle: path ? `Editing ${path}` : 'Editing file',
errorTitle: path ? `Failed to edit ${path}` : 'Failed to edit file',
};
}
case 'glob':
return {
icon: Search,
title: args.pattern ? `Searched "${args.pattern}"` : 'File Pattern Search',
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching Files',
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search Failed',
title: args.pattern ? `Searched "${args.pattern}"` : 'File pattern search',
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching files',
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search failed',
};
case 'grep':
return {
icon: Search,
title: args.pattern ? `Searched "${args.pattern}"` : 'Content Search',
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching Content',
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search Failed',
title: args.pattern ? `Searched "${args.pattern}"` : 'Content search',
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching content',
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search failed',
};
// Legacy tools (kept for old chat history)
@@ -186,9 +186,9 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: FileText,
title: path ? `Wrote ${path}` : 'Wrote File',
callingTitle: path ? `Writing ${path}` : 'Writing File',
errorTitle: path ? `Failed to write ${path}` : 'Failed to Write File',
title: path ? `Wrote ${path}` : 'Wrote file',
callingTitle: path ? `Writing ${path}` : 'Writing file',
errorTitle: path ? `Failed to write ${path}` : 'Failed to write file',
};
}
@@ -197,9 +197,9 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: Edit,
title: path ? `Edited ${path}` : 'Edited File',
callingTitle: path ? `Editing ${path}` : 'Editing File',
errorTitle: path ? `Failed to edit ${path}` : 'Failed to Edit File',
title: path ? `Edited ${path}` : 'Edited file',
callingTitle: path ? `Editing ${path}` : 'Editing file',
errorTitle: path ? `Failed to edit ${path}` : 'Failed to edit file',
};
}
@@ -217,25 +217,25 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
case 'npm_remove_package':
return {
icon: PackageMinus,
title: args.name ? `Removed ${args.name}` : 'Removed Package',
callingTitle: args.name ? `Removing ${args.name}` : 'Removing Package',
errorTitle: args.name ? `Failed to remove ${args.name}` : 'Failed to Remove Package',
title: args.name ? `Removed ${args.name}` : 'Removed package',
callingTitle: args.name ? `Removing ${args.name}` : 'Removing package',
errorTitle: args.name ? `Failed to remove ${args.name}` : 'Failed to remove package',
};
case 'git_commit':
return {
icon: GitCommit,
title: args.message ? `Committed: ${args.message}` : 'Committed Changes',
callingTitle: args.message ? `Committing: ${args.message}` : 'Committing Changes',
errorTitle: 'Failed to Commit Changes',
title: args.message ? `Committed: ${args.message}` : 'Committed changes',
callingTitle: args.message ? `Committing: ${args.message}` : 'Committing changes',
errorTitle: 'Failed to commit changes',
};
case 'build_project':
return {
icon: Package,
title: 'Built Project',
callingTitle: 'Building Project',
errorTitle: 'Failed to Build Project',
title: 'Built project',
callingTitle: 'Building project',
errorTitle: 'Failed to build project',
};
case 'nostr_read_nip':
@@ -243,55 +243,55 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
icon: BookOpen,
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP',
callingTitle: args.nip ? `Reading NIP-${args.nip}` : 'Reading NIP',
errorTitle: args.nip ? `Failed to read NIP-${args.nip}` : 'Failed to Read NIP',
errorTitle: args.nip ? `Failed to read NIP-${args.nip}` : 'Failed to read NIP',
};
case 'nostr_fetch_event':
return {
icon: Download,
title: args.identifier ? `Fetched ${String(args.identifier).slice(0, 16)}...` : 'Fetched Event',
callingTitle: args.identifier ? `Fetching ${String(args.identifier).slice(0, 16)}...` : 'Fetching Event',
errorTitle: args.identifier ? `Failed to fetch ${String(args.identifier).slice(0, 16)}...` : 'Failed to Fetch Event',
title: args.identifier ? `Viewed ${String(args.identifier).slice(0, 16)}...` : 'Viewed event',
callingTitle: args.identifier ? `Viewing ${String(args.identifier).slice(0, 16)}...` : 'Viewing event',
errorTitle: args.identifier ? `Failed to view ${String(args.identifier).slice(0, 16)}...` : 'Failed to view event',
};
case 'nostr_read_kind':
return {
icon: Hash,
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind',
callingTitle: args.kind !== undefined ? `Reading Kind ${args.kind}` : 'Reading Kind',
errorTitle: args.kind !== undefined ? `Failed to read Kind ${args.kind}` : 'Failed to Read Kind',
title: args.kind !== undefined ? `Viewed kind ${args.kind}` : 'Viewed kind',
callingTitle: args.kind !== undefined ? `Viewing kind ${args.kind}` : 'Viewing kind',
errorTitle: args.kind !== undefined ? `Failed to view kind ${args.kind}` : 'Failed to view kind',
};
case 'nostr_read_tag':
return {
icon: Tag,
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag',
callingTitle: args.tag ? `Reading Tag "${args.tag}"` : 'Reading Tag',
errorTitle: args.tag ? `Failed to read Tag "${args.tag}"` : 'Failed to Read Tag',
title: args.tag ? `Viewed tag "${args.tag}"` : 'Viewed tag',
callingTitle: args.tag ? `Viewing tag "${args.tag}"` : 'Viewing tag',
errorTitle: args.tag ? `Failed to view tag "${args.tag}"` : 'Failed to view tag',
};
case 'nostr_read_protocol':
return {
icon: Network,
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol',
callingTitle: args.doc ? `Reading Protocol: ${args.doc}` : 'Reading Protocol',
errorTitle: args.doc ? `Failed to read Protocol: ${args.doc}` : 'Failed to Read Protocol',
title: args.doc ? `Viewed protocol ${args.doc}` : 'Viewed protocol',
callingTitle: args.doc ? `Viewing protocol ${args.doc}` : 'Viewing protocol',
errorTitle: args.doc ? `Failed to view protocol ${args.doc}` : 'Failed to view protocol',
};
case 'nostr_read_nips_index':
return {
icon: List,
title: 'Read NIPs Index',
callingTitle: 'Reading NIPs Index',
errorTitle: 'Failed to Read NIPs Index',
title: 'Viewed NIPs index',
callingTitle: 'Viewing NIPs index',
errorTitle: 'Failed to view NIPs index',
};
case 'nostr_generate_kind':
return {
icon: Plus,
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind',
callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating Kind',
errorTitle: args.range ? `Failed to generate ${args.range} kind` : 'Failed to Generate Kind',
title: args.range ? `Generated ${args.range} kind` : 'Generated kind',
callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating kind',
errorTitle: args.range ? `Failed to generate ${args.range} kind` : 'Failed to generate kind',
};
case 'nostr_publish_events': {
@@ -300,56 +300,76 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
icon: Send,
title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event',
callingTitle: eventCount > 1 ? `Publishing ${eventCount} Nostr events` : 'Publishing Nostr event',
errorTitle: eventCount > 1 ? `Failed to publish ${eventCount} Nostr events` : 'Failed to Publish Nostr Event',
errorTitle: eventCount > 1 ? `Failed to publish ${eventCount} Nostr events` : 'Failed to publish Nostr event',
};
}
case 'deploy_project':
return {
icon: Globe,
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project',
callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying Project',
errorTitle: args.deployServer ? `Failed to deploy to ${args.deployServer}` : 'Failed to Deploy Project',
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed project',
callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying project',
errorTitle: args.deployServer ? `Failed to deploy to ${args.deployServer}` : 'Failed to deploy project',
};
case 'read_console_messages':
return {
icon: Logs,
title: 'Read Console',
callingTitle: 'Reading Console',
errorTitle: 'Failed to Read Console',
title: 'Viewed console',
callingTitle: 'Viewing console',
errorTitle: 'Failed to view console',
};
case 'webfetch': {
const url = args.url ? String(args.url) : '';
return {
icon: Globe,
title: url ? `Viewed ${url}` : 'Viewed webpage',
callingTitle: url ? `Viewing ${url}` : 'Viewing webpage',
errorTitle: url ? `Failed to view ${url}` : 'Failed to view webpage',
};
}
case 'websearch': {
const query = args.query ? String(args.query) : '';
return {
icon: Search,
title: query ? `Searched "${query}"` : 'Web search',
callingTitle: query ? `Searching "${query}"` : 'Searching web',
errorTitle: query ? `Failed to search "${query}"` : 'Search failed',
};
}
case 'skill':
return {
icon: Puzzle,
title: args.name ? `Skill: ${args.name}` : 'Skill',
callingTitle: args.name ? `Running Skill: ${args.name}` : 'Running Skill',
errorTitle: args.name ? `Skill Failed: ${args.name}` : 'Skill Failed',
callingTitle: args.name ? `Running skill: ${args.name}` : 'Running skill',
errorTitle: args.name ? `Skill failed: ${args.name}` : 'Skill failed',
};
case 'generate_image':
return {
icon: Image,
title: args.prompt ? String(args.prompt) : 'Generated Image',
callingTitle: args.prompt ? String(args.prompt) : 'Generating Image',
errorTitle: 'Failed to Generate Image',
title: args.prompt ? String(args.prompt) : 'Generated image',
callingTitle: args.prompt ? String(args.prompt) : 'Generating image',
errorTitle: 'Failed to generate image',
};
case 'view_available_models':
return {
icon: Eye,
title: 'Viewed Available Models',
callingTitle: 'Viewing Available Models',
errorTitle: 'Failed to View Available Models',
title: 'Viewed available models',
callingTitle: 'Viewing available models',
errorTitle: 'Failed to view available models',
};
case 'configure_image_generation':
return {
icon: Settings,
title: args.model ? `Configured image model: ${args.model}` : 'Configured Image Generation',
callingTitle: args.model ? `Configuring image model: ${args.model}` : 'Configuring Image Generation',
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to Configure Image Generation',
title: args.model ? `Configured image model: ${args.model}` : 'Configured image generation',
callingTitle: args.model ? `Configuring image model: ${args.model}` : 'Configuring image generation',
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to configure image generation',
};
default: {
+1 -1
View File
@@ -758,7 +758,7 @@ export class SessionManager {
const filepath = await this.saveToTmpFile(projectId, content, toolCallId);
// Create placeholder message
finalContent = `The tool call succeeded but the output was truncated. Full output saved to: ${filepath}\nUse grep to search it for specific content, or text_editor_view with start_line/end_line to view specific sections.`;
finalContent = `The tool call succeeded but the output was truncated. Full output saved to: ${filepath}\nUse \`grep\` to search the full content or \`read\` with offset/limit to view specific sections.`;
}
const toolMessage: AIMessage = {
-236
View File
@@ -1,236 +0,0 @@
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.content).toContain("# Test Article");
expect(result.content).toContain("**Source:** https://example.com/article");
expect(result.content).toContain("Main Article Title");
expect(result.content).toContain("**bold text**");
expect(result.content).toContain("*italic text*");
expect(result.content).toContain("## Subsection");
expect(result.content).toContain("* First item");
expect(result.content).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.content).toContain("# Article with Metadata");
expect(result.content).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.content).toContain("```");
expect(result.content).toContain("function hello()");
expect(result.content).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.content).toContain("# Untitled");
expect(result.content).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
@@ -1,123 +0,0 @@
import { Readability } from "@mozilla/readability";
import TurndownService from "turndown";
import { z } from "zod";
import type { Tool, ToolResult } 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${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<ToolResult> {
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 { content: 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)}`);
}
}
}
+30
View File
@@ -0,0 +1,30 @@
import { describe, it, expect } from "vitest";
import { WebFetchTool } from "./WebFetchTool";
describe("WebFetchTool", () => {
const tool = new WebFetchTool();
it("should have a description", () => {
expect(tool.description).toBeDefined();
expect(tool.description.length).toBeGreaterThan(0);
});
it("should have an input schema", () => {
expect(tool.inputSchema).toBeDefined();
});
it("should validate that URL starts with http:// or https://", async () => {
await expect(
tool.execute({ url: "ftp://example.com" })
).rejects.toThrow("URL must start with http:// or https://");
});
it("should default format to markdown", async () => {
// This test would require mocking fetch, which we'll skip for now
// Just verify the schema allows optional format
const result = tool.inputSchema?.safeParse({
url: "https://example.com",
});
expect(result?.success).toBe(true);
});
});
+183
View File
@@ -0,0 +1,183 @@
import TurndownService from "turndown";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import { proxyUrl } from "../proxyUrl";
interface WebFetchParams {
url: string;
format?: "text" | "markdown" | "html";
timeout?: number;
}
interface WebFetchToolOptions {
maxResponseSize?: number;
defaultTimeout?: number;
maxTimeout?: number;
corsProxy?: string;
}
export class WebFetchTool implements Tool<WebFetchParams> {
private readonly maxResponseSize: number;
private readonly defaultTimeout: number;
private readonly maxTimeout: number;
private readonly corsProxy?: string;
readonly description = `- Fetches content from a specified URL
- Takes a URL and optional format as input
- Fetches the URL content, converts to requested format (markdown by default)
- Returns the content in the specified format
- Use this tool when you need to retrieve and analyze web content
Usage notes:
- IMPORTANT: if another tool is present that offers better web fetching capabilities, is more targeted to the task, or has fewer restrictions, prefer using that tool instead of this one.
- The URL must be a fully-formed valid URL
- HTTP URLs will be automatically upgraded to HTTPS
- Format options: "markdown" (default), "text", or "html"
- This tool is read-only and does not modify any files
- Results may be summarized if the content is very large`;
readonly inputSchema = z.object({
url: z.string().url().describe("The URL to fetch content from"),
format: z
.enum(["text", "markdown", "html"])
.default("markdown")
.describe("The format to return the content in (text, markdown, or html). Defaults to markdown."),
timeout: z.number().optional().describe("Optional timeout in seconds (max 120)"),
});
constructor(options: WebFetchToolOptions = {}) {
this.maxResponseSize = options.maxResponseSize ?? 5 * 1024 * 1024; // 5MB
this.defaultTimeout = options.defaultTimeout ?? 30 * 1000; // 30 seconds
this.maxTimeout = options.maxTimeout ?? 120 * 1000; // 2 minutes
this.corsProxy = options.corsProxy;
}
async execute(args: WebFetchParams): Promise<ToolResult> {
// Validate URL
if (!args.url.startsWith("http://") && !args.url.startsWith("https://")) {
throw new Error("URL must start with http:// or https://");
}
const timeout = Math.min((args.timeout ?? this.defaultTimeout / 1000) * 1000, this.maxTimeout);
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
// Build Accept header based on requested format with q parameters for fallbacks
const format = args.format || "markdown";
let acceptHeader = "*/*";
switch (format) {
case "markdown":
acceptHeader = "text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1";
break;
case "text":
acceptHeader = "text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1";
break;
case "html":
acceptHeader = "text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1";
break;
default:
acceptHeader =
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8";
}
// Use CORS proxy if provided
const fetchUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url: args.url }) : args.url;
const response = await fetch(fetchUrl, {
signal: controller.signal,
headers: {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",
Accept: acceptHeader,
"Accept-Language": "en-US,en;q=0.9",
},
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`Request failed with status code: ${response.status}`);
}
// Check content length
const contentLength = response.headers.get("content-length");
if (contentLength && parseInt(contentLength) > this.maxResponseSize) {
throw new Error(`Response too large (exceeds ${this.maxResponseSize / (1024 * 1024)}MB limit)`);
}
const arrayBuffer = await response.arrayBuffer();
if (arrayBuffer.byteLength > this.maxResponseSize) {
throw new Error(`Response too large (exceeds ${this.maxResponseSize / (1024 * 1024)}MB limit)`);
}
const content = new TextDecoder().decode(arrayBuffer);
const contentType = response.headers.get("content-type") || "";
// Handle content based on requested format and actual content type
let output: string;
switch (format) {
case "markdown":
if (contentType.includes("text/html")) {
output = this.convertHTMLToMarkdown(content);
} else {
output = content;
}
break;
case "text":
if (contentType.includes("text/html")) {
output = this.extractTextFromHTML(content);
} else {
output = content;
}
break;
case "html":
output = content;
break;
default:
output = content;
}
return { content: output };
} catch (error) {
clearTimeout(timeoutId);
if (error instanceof Error && error.name === "AbortError") {
throw new Error("Request timed out");
}
throw new Error(`Failed to fetch webpage: ${error instanceof Error ? error.message : String(error)}`);
}
}
private extractTextFromHTML(html: string): string {
// Create a temporary DOM element to extract text
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
// Remove script, style, and other non-content elements
const elementsToRemove = doc.querySelectorAll("script, style, noscript, iframe, object, embed");
elementsToRemove.forEach(el => el.remove());
// Get text content
return (doc.body?.textContent || "").trim();
}
private convertHTMLToMarkdown(html: string): string {
const turndownService = new TurndownService({
headingStyle: "atx",
hr: "---",
bulletListMarker: "-",
codeBlockStyle: "fenced",
emDelimiter: "*",
});
turndownService.remove(["script", "style", "meta", "link"]);
return turndownService.turndown(html);
}
}
+33
View File
@@ -0,0 +1,33 @@
import { describe, it, expect } from "vitest";
import { WebSearchTool } from "./WebSearchTool";
describe("WebSearchTool", () => {
const tool = new WebSearchTool();
it("should have a description", () => {
expect(tool.description).toBeDefined();
expect(tool.description.length).toBeGreaterThan(0);
});
it("should have an input schema", () => {
expect(tool.inputSchema).toBeDefined();
});
it("should accept a query parameter", () => {
const result = tool.inputSchema?.safeParse({
query: "test query",
});
expect(result?.success).toBe(true);
});
it("should validate optional parameters", () => {
const result = tool.inputSchema?.safeParse({
query: "test query",
numResults: 10,
livecrawl: "preferred",
type: "deep",
contextMaxCharacters: 5000,
});
expect(result?.success).toBe(true);
});
});
+158
View File
@@ -0,0 +1,158 @@
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
interface WebSearchParams {
query: string;
numResults?: number;
livecrawl?: "fallback" | "preferred";
type?: "auto" | "fast" | "deep";
contextMaxCharacters?: number;
}
interface WebSearchToolOptions {
baseUrl?: string;
searchEndpoint?: string;
defaultNumResults?: number;
timeout?: number;
}
interface McpSearchRequest {
jsonrpc: string;
id: number;
method: string;
params: {
name: string;
arguments: {
query: string;
numResults?: number;
livecrawl?: "fallback" | "preferred";
type?: "auto" | "fast" | "deep";
contextMaxCharacters?: number;
};
};
}
interface McpSearchResponse {
jsonrpc: string;
result: {
content: Array<{
type: string;
text: string;
}>;
};
}
export class WebSearchTool implements Tool<WebSearchParams> {
private readonly baseUrl: string;
private readonly searchEndpoint: string;
private readonly defaultNumResults: number;
private readonly timeout: number;
readonly description = `- Search the web using Exa AI - performs real-time web searches and can scrape content from specific URLs
- Provides up-to-date information for current events and recent data
- Supports configurable result counts and returns the content from the most relevant websites
- Use this tool for accessing information beyond knowledge cutoff
- Searches are performed automatically within a single API call
Usage notes:
- Supports live crawling modes: 'fallback' (backup if cached unavailable) or 'preferred' (prioritize live crawling)
- Search types: 'auto' (balanced), 'fast' (quick results), 'deep' (comprehensive search)
- Configurable context length for optimal LLM integration
- Domain filtering and advanced search options available`;
readonly inputSchema = z.object({
query: z.string().describe("Websearch query"),
numResults: z.number().optional().describe("Number of search results to return (default: 8)"),
livecrawl: z
.enum(["fallback", "preferred"])
.optional()
.describe(
"Live crawl mode - 'fallback': use live crawling as backup if cached content unavailable, 'preferred': prioritize live crawling (default: 'fallback')"
),
type: z
.enum(["auto", "fast", "deep"])
.optional()
.describe("Search type - 'auto': balanced search (default), 'fast': quick results, 'deep': comprehensive search"),
contextMaxCharacters: z
.number()
.optional()
.describe("Maximum characters for context string optimized for LLMs (default: 10000)"),
});
constructor(options: WebSearchToolOptions = {}) {
this.baseUrl = options.baseUrl ?? "https://mcp.exa.ai";
this.searchEndpoint = options.searchEndpoint ?? "/mcp";
this.defaultNumResults = options.defaultNumResults ?? 8;
this.timeout = options.timeout ?? 25000;
}
async execute(args: WebSearchParams): Promise<ToolResult> {
const searchRequest: McpSearchRequest = {
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: {
name: "web_search_exa",
arguments: {
query: args.query,
type: args.type || "auto",
numResults: args.numResults || this.defaultNumResults,
livecrawl: args.livecrawl || "fallback",
contextMaxCharacters: args.contextMaxCharacters,
},
},
};
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
try {
const headers: Record<string, string> = {
accept: "application/json, text/event-stream",
"content-type": "application/json",
};
const response = await fetch(`${this.baseUrl}${this.searchEndpoint}`, {
method: "POST",
headers,
body: JSON.stringify(searchRequest),
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Search error (${response.status}): ${errorText}`);
}
const responseText = await response.text();
// Parse SSE response
const lines = responseText.split("\n");
for (const line of lines) {
if (line.startsWith("data: ")) {
const data: McpSearchResponse = JSON.parse(line.substring(6));
if (data.result && data.result.content && data.result.content.length > 0) {
return {
content: data.result.content[0].text,
};
}
}
}
return {
content: "No search results found. Please try a different query.",
};
} catch (error) {
clearTimeout(timeoutId);
if (error instanceof Error && error.name === "AbortError") {
throw new Error("Search request timed out");
}
throw error;
}
}
}