search
Search the web to get an AI-synthesized answer with cited sources.
Instructions
Search the web using Perplexity.ai and get an AI-synthesized answer with cited sources. Uses default Perplexity settings.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | The search query |
Implementation Reference
- src/search.ts:26-29 (handler)Main handler for the 'search' tool. Accepts a query string and timeout, delegates to runSearch() which automates Perplexity.ai via Playwright to perform the search and return the answer with cited sources.
export async function search(query: string, timeoutMs: number): Promise<SearchResult> { log(`Search: "${query}" (timeout: ${timeoutMs}ms)`); return runSearch(query, timeoutMs, null); } - src/search.ts:36-84 (handler)Core implementation of the search logic. Navigates to perplexity.ai, optionally selects sources, types the query, waits for the answer, extracts the answer text and cited sources from the DOM, and returns a SearchResult.
async function runSearch(query: string, timeoutMs: number, sources: string[] | null): Promise<SearchResult> { const page = await newSearchPage(); try { log("Navigating to perplexity.ai..."); await page.goto(PERPLEXITY_HOME, { waitUntil: "domcontentloaded" }); await dismissDialogs(page); // Wait for the search input to be ready before any further interaction await page.locator("#ask-input").first().waitFor({ state: "visible", timeout: 10_000 }); if (sources) { log(`Selecting sources: [${sources.join(", ")}]...`); await selectSources(page, sources); } log("Typing query..."); await page.keyboard.press("Escape"); await page.waitForTimeout(300); const searchBox = page.locator("#ask-input").first(); await searchBox.waitFor({ state: "visible", timeout: 10_000 }).catch(async (err) => { const bodyHtml = await page.evaluate(() => document.body.innerHTML.slice(0, 5000)); log(`DOM dump (first 5000 chars):\n${bodyHtml}`); throw err; }); await searchBox.click(); await searchBox.fill(query); await searchBox.press("Enter"); log("Waiting for answer to complete..."); // Perplexity shows a "N sources" button when the answer finishes. // The word varies by UI language — match any button whose text contains digits. await page.locator("button").filter({ hasText: /\d/ }).first().waitFor({ timeout: timeoutMs }); await dismissDialogs(page); log("Extracting answer from DOM..."); const [answer, citedSources] = await Promise.all([ extractAnswer(page), extractSources(page), ]); log(`Done. Answer length: ${answer.length} chars, sources: ${citedSources.length}`); return { answer, sources: citedSources }; } finally { await page.close(); } } - src/search.ts:14-22 (schema)Type definitions for SearchResult (answer string + array of Source objects) and Source (title + url). These define the structure of the data returned by the search tool.
export interface Source { title: string; url: string; } export interface SearchResult { answer: string; sources: Source[]; } - src/index.ts:28-40 (registration)MCP tool registration for 'search'. Defines the tool name, description, parameter schema (zod object with 'query' string), and execute callback that calls the search() function and formats the result.
mcp.addTool({ name: "search", description: "Search the web using Perplexity.ai and get an AI-synthesized answer with cited sources. Uses default Perplexity settings.", parameters: z.object({ query: z.string().describe("The search query"), }), execute: async ({ query }) => { await ensureBrowser(); const result = await search(query, TIMEOUT_MS); return formatResult(result); }, }); - src/search.ts:165-230 (helper)Helper functions: extractAnswer() scrapes the answer text from Perplexity's DOM, extractSources() extracts cited source links. These are used by runSearch() to build the SearchResult.
async function extractAnswer(page: Page): Promise<string> { return page.evaluate(() => { const panel = document.querySelector('[role="tabpanel"]'); if (!panel) return ""; function getCleanText(el: Element): string { let text = ""; for (const node of Array.from(el.childNodes)) { if (node.nodeType === Node.TEXT_NODE) { text += node.textContent ?? ""; } else if (node.nodeType === Node.ELEMENT_NODE) { const child = node as Element; const style = window.getComputedStyle(child); // Skip citation chips: pointer cursor + short text (e.g. "wikipedia+3") if (style.cursor === "pointer" && (child.textContent?.trim().length ?? 0) < 40) { continue; } text += getCleanText(child); } } return text; } const parts: string[] = []; const seen = new Set<string>(); panel.querySelectorAll("h2, h3, p, li, pre code").forEach((el) => { if (el.tagName === "P" && el.closest("li")) return; if (el.tagName === "LI" && el.querySelector("li")) return; const tag = el.tagName.toLowerCase(); const text = getCleanText(el).trim().replace(/\s+/g, " "); if (!text || seen.has(text)) return; seen.add(text); if (tag === "h2" || tag === "h3") { parts.push(`\n## ${text}\n`); } else if (tag === "code") { parts.push(`\`\`\`\n${text}\n\`\`\``); } else if (tag === "li") { parts.push(`- ${text}`); } else { parts.push(text); } }); return parts.join("\n").trim(); }); } async function extractSources(page: Page): Promise<Source[]> { return page.evaluate(() => { const sources: { title: string; url: string }[] = []; const seen = new Set<string>(); document.querySelectorAll<HTMLAnchorElement>('a[href^="http"]').forEach((link) => { const url = link.href; if (seen.has(url) || url.includes("perplexity.ai")) return; seen.add(url); const title = link.textContent?.trim() || new URL(url).hostname; sources.push({ title, url }); }); return sources.slice(0, 10); }); }