Skip to main content
Glama
quequiere

perplexity-web-mcp

by quequiere

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

TableJSON Schema
NameRequiredDescriptionDefault
queryYesThe search query

Implementation Reference

  • 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);
    }
  • 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();
      }
    }
  • 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);
      },
    });
  • 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);
      });
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the transparency burden. It discloses that it uses default Perplexity settings and returns a synthesized answer with sources, but it does not mention potential rate limits, authentication needs, or other behavioral traits.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise with two sentences. The first sentence front-loads the purpose and result, and the second adds relevant context about default settings. It is efficiently structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple tool with one parameter and no output schema, the description is fairly complete. It explains what the tool does and mentions the default setting context. However, it could mention any output format or prerequisites.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 100% schema description coverage, the baseline is 3. The description does not add any additional meaning to the 'query' parameter beyond what the schema already provides, so it meets the baseline.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool searches the web using Perplexity.ai and returns an AI-synthesized answer with cited sources. It distinguishes itself from the sibling 'login' but does not explicitly differentiate from 'search_advanced', though mentioning 'default settings' hints at a distinction.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies that normal searches use defaults, but it doesn't explicitly state when to use this tool versus 'search_advanced' or provide any prerequisites or context for usage.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/quequiere/perplexity-web-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server