Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@
# Get yours at: https://api.search.brave.com
BRAVE_API_KEY=

# Tavily Search API — Free: 1000 credits/month
# Get yours at: https://app.tavily.com
TAVILY_API_KEY=

# Search provider selection: 'brave' (default) or 'tavily'
# SEARCH_PROVIDER=brave

# GetXAPI — For X/Twitter search, threads, user posts ($0.001/call)
# Get yours at: https://getxapi.com
GETXAPI_KEY=
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ node_modules/
.env
dist/
*.log
package-lock.json
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"@mozilla/readability": "^0.5.0",
"@tavily/core": "^0.6.0",
"linkedom": "^0.18.0"
}
}
85 changes: 75 additions & 10 deletions tools/web-search/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
import { z } from "zod";
import { tavily } from "@tavily/core";
import type { ToolDefinition } from "../../lib/tool-registry.js";
import { requireEnv } from "../../lib/rapidapi.js";

interface BraveResult {
interface SearchResult {
title: string;
url: string;
description: string;
}

async function execute({ query, count }: { query: string; count: number }): Promise<string> {
function formatResults(results: SearchResult[], query: string): string {
if (results.length === 0) return `No results found for: "${query}"`;
return results
.map((r, i) => `${i + 1}. **${r.title}**\n ${r.url}\n ${r.description}`)
.join("\n\n");
}

async function searchBrave(query: string, count: number): Promise<SearchResult[]> {
const apiKey = requireEnv("BRAVE_API_KEY");

const url = new URL("https://api.search.brave.com/res/v1/web/search");
Expand All @@ -25,22 +33,79 @@ async function execute({ query, count }: { query: string; count: number }): Prom
});

if (!response.ok) {
return `Brave Search error: ${response.status} ${response.statusText}`;
throw new Error(`Brave Search error: ${response.status} ${response.statusText}`);
}

const data = (await response.json()) as { web?: { results?: BraveResult[] } };
const results = data.web?.results ?? [];
const data = (await response.json()) as { web?: { results?: SearchResult[] } };
return (data.web?.results ?? []).map((r) => ({
title: r.title,
url: r.url,
description: r.description,
}));
}

if (results.length === 0) return `No results found for: "${query}"`;
async function searchTavily(query: string, count: number): Promise<SearchResult[]> {
const apiKey = requireEnv("TAVILY_API_KEY");
const client = tavily({ apiKey });

return results
.map((r, i) => `${i + 1}. **${r.title}**\n ${r.url}\n ${r.description}`)
.join("\n\n");
const response = await client.search(query, {
maxResults: Math.min(Math.max(count, 1), 20),
});

return (response.results ?? []).map((r) => ({
title: r.title,
url: r.url,
description: r.content,
}));
}

function getSearchProvider(): "brave" | "tavily" {
const provider = process.env.SEARCH_PROVIDER?.toLowerCase();
if (provider === "tavily") return "tavily";
return "brave";
}

async function execute({ query, count }: { query: string; count: number }): Promise<string> {
const provider = getSearchProvider();

if (provider === "tavily") {
try {
const results = await searchTavily(query, count);
return formatResults(results, query);
} catch (err) {
// Fall back to Brave if Tavily fails and BRAVE_API_KEY is available
if (process.env.BRAVE_API_KEY) {
try {
const results = await searchBrave(query, count);
return formatResults(results, query);
} catch {
// Both providers failed; return original Tavily error
}
}
return `Tavily Search error: ${err instanceof Error ? err.message : String(err)}`;
}
}

try {
const results = await searchBrave(query, count);
return formatResults(results, query);
} catch (err) {
// Fall back to Tavily if Brave fails and TAVILY_API_KEY is available
if (process.env.TAVILY_API_KEY) {
try {
const results = await searchTavily(query, count);
return formatResults(results, query);
} catch {
// Both providers failed; return original Brave error
}
}
return err instanceof Error ? err.message : String(err);
}
}

export const definition: ToolDefinition = {
name: "web_search",
description: "Search the web using Brave Search. Returns titles, URLs, and descriptions.",
description: "Search the web using Brave Search or Tavily. Returns titles, URLs, and descriptions.",
params: {
query: z.string().describe("Search query"),
count: z.number().min(1).max(20).default(5).describe("Number of results (1-20)"),
Expand Down