Skip to main content
Glama
wysh3

Perplexity MCP Server

search

Perform web searches based on queries and desired detail levels using Perplexity AI. Retrieve general knowledge, find information, or explore perspectives with customizable results.

Instructions

Performs a web search using Perplexity AI based on the provided query and desired detail level. Useful for general knowledge questions, finding information, or getting different perspectives.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
detail_levelNoOptional: Controls the level of detail in the response (default: normal).
queryYesThe search query or question to ask Perplexity.
streamNoOptional: Enable streaming response for large documentation queries (default: false).

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
responseNoThe search result text provided by Perplexity AI.

Implementation Reference

  • The handler function for the MCP 'search' tool. It extracts the query from arguments (ignoring optional detail_level and stream) and delegates execution to the SearchEngine.performSearch method.
    private async handleSearch(args: Record<string, unknown>): Promise<string> {
      const typedArgs = args as {
        query: string;
        detail_level?: "brief" | "normal" | "detailed";
        stream?: boolean;
      };
    
      return await this.searchEngine.performSearch(typedArgs.query);
    }
  • The input/output schema definition and metadata for the 'search' tool, including description, parameters, examples, and use cases.
    {
      name: "search",
      description:
        "Performs a web search using Perplexity AI based on the provided query and desired detail level. Useful for general knowledge questions, finding information, or getting different perspectives.",
      category: "Web Search",
      keywords: ["search", "web", "internet", "query", "find", "information", "lookup", "perplexity"],
      use_cases: [
        "Answering general knowledge questions.",
        "Finding specific information online.",
        "Getting quick summaries or detailed explanations.",
        "Researching topics.",
      ],
      inputSchema: {
        type: "object",
        properties: {
          query: {
            type: "string",
            description: "The search query or question to ask Perplexity.",
            examples: ["What is the capital of France?", "Explain black holes"],
          },
          detail_level: {
            type: "string",
            enum: ["brief", "normal", "detailed"],
            description: "Optional: Controls the level of detail in the response (default: normal).",
            examples: ["brief", "detailed"],
          },
          stream: {
            type: "boolean",
            description:
              "Optional: Enable streaming response for large documentation queries (default: false).",
            examples: [true, false],
          },
        },
        required: ["query"],
      },
      outputSchema: {
        type: "object",
        properties: {
          response: {
            type: "string",
            description: "The search result text provided by Perplexity AI.",
          },
        },
      },
      examples: [
        {
          description: "Simple search query",
          input: { query: "What is the weather in London?" },
          output: { response: "The weather in London is currently..." },
        },
        {
          description: "Detailed search query",
          input: { query: "Explain the theory of relativity", detail_level: "detailed" },
          output: {
            response:
              "Albert Einstein's theory of relativity includes Special Relativity and General Relativity...",
          },
        },
      ],
      related_tools: ["chat_perplexity", "get_documentation", "find_apis"],
    },
  • Registers all MCP tools including 'search' by creating a registry mapping 'search' to its handler and calling setupToolHandlers.
    private setupToolHandlers(): void {
      const toolHandlers = createToolHandlersRegistry({
        chat_perplexity: this.handleChatPerplexity.bind(this),
        get_documentation: this.handleGetDocumentation.bind(this),
        find_apis: this.handleFindApis.bind(this),
        check_deprecated_code: this.handleCheckDeprecatedCode.bind(this),
        search: this.handleSearch.bind(this),
        extract_url_content: this.handleExtractUrlContent.bind(this),
      });
    
      setupToolHandlers(this.server, toolHandlers);
    }
  • Core implementation of the search functionality using Puppeteer to interact with Perplexity AI, including navigation, query submission, answer extraction, retries, and error recovery. Called by the 'search' tool handler.
    async performSearch(query: string): Promise<string> {
      // Set a global timeout for the entire operation with buffer for MCP
      const operationTimeout = setTimeout(() => {
        logError("Global operation timeout reached, initiating recovery...");
        this.browserManager.performRecovery().catch((err: unknown) => {
          logError("Recovery after timeout failed:", {
            error: err instanceof Error ? err.message : String(err),
          });
        });
      }, CONFIG.PAGE_TIMEOUT - CONFIG.MCP_TIMEOUT_BUFFER);
    
      try {
        // Ensure browser is ready
        if (!this.browserManager.isReady()) {
          logInfo("Browser not ready, initializing...");
          await this.browserManager.initialize();
        }
    
        // Reset idle timeout
        this.browserManager.resetIdleTimeout();
    
        // Use retry operation for the entire search process with increased retries
        const ctx = this.browserManager.getPuppeteerContext();
        
        return await retryOperation(ctx, async () => {
          logInfo(`Navigating to Perplexity for query: "${query.substring(0, 30)}${query.length > 30 ? '...' : ''}"`);
          await this.browserManager.navigateToPerplexity();
    
          // Validate main frame is attached
          const page = this.browserManager.getPage();
          if (!page || page.mainFrame().isDetached()) {
            logError("Main frame is detached, will retry with new browser instance");
            throw new Error("Main frame is detached");
          }
    
          logInfo("Waiting for search input...");
          const selector = await this.browserManager.waitForSearchInput();
          if (!selector) {
            logError("Search input not found, taking screenshot for debugging");
            if (page) {
              await page.screenshot({ path: "debug_search_input_not_found.png", fullPage: true });
            }
            throw new Error("Search input not found");
          }
    
          logInfo(`Found search input with selector: ${selector}`);
    
          // Perform the search
          await this.executeSearch(page, selector, query);
    
          // Wait for and extract the answer
          const answer = await this.waitForCompleteAnswer(page);
          return answer;
        }, CONFIG.MAX_RETRIES);
      } catch (error) {
        logError("Search operation failed after all retries:", {
          error: error instanceof Error ? error.message : String(error),
        });
    
        // Handle specific error cases with user-friendly messages
        if (error instanceof Error) {
          if (error.message.includes("detached") || error.message.includes("Detached")) {
            logError("Frame detachment detected, attempting recovery...");
            await this.browserManager.performRecovery();
            return "The search operation encountered a technical issue. Please try again with a more specific query.";
          }
    
          if (error.message.includes("timeout") || error.message.includes("Timed out")) {
            logError("Timeout detected, attempting recovery...");
            await this.browserManager.performRecovery();
            return "The search operation is taking longer than expected. This might be due to high server load. Your query has been submitted and we're waiting for results. Please try again with a more specific query if needed.";
          }
    
          if (error.message.includes("navigation") || error.message.includes("Navigation")) {
            logError("Navigation error detected, attempting recovery...");
            await this.browserManager.performRecovery();
            return "The search operation encountered a navigation issue. This might be due to network connectivity problems. Please try again later.";
          }
        }
    
        // For any other errors, return a user-friendly message
        return `The search operation could not be completed. Error: ${error instanceof Error ? error.message : 'Unknown error'}. Please try again later with a more specific query.`;
      } finally {
        clearTimeout(operationTimeout);
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the tool performs a web search and is useful for certain purposes, but fails to disclose critical behavioral traits like whether it requires authentication, has rate limits, returns structured data, or handles errors. This leaves significant gaps for an agent to understand operational constraints.

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 appropriately sized with two sentences that are front-loaded with the core action. The first sentence states the purpose clearly, and the second adds context without redundancy. However, the second sentence could be slightly more precise, preventing a perfect score.

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

Completeness3/5

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

Given the tool has an output schema (which covers return values), no annotations, and high schema coverage, the description is moderately complete. It explains the basic purpose and usage context but lacks behavioral details like authentication needs or error handling, which are important for a search tool with no annotation support.

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?

Schema description coverage is 100%, so the schema already documents all parameters (query, detail_level, stream) thoroughly. The description adds minimal value beyond the schema by mentioning 'desired detail level' and implying the query's purpose, but doesn't provide additional syntax, format, or usage details. This meets the baseline for high schema coverage.

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 performs a 'web search using Perplexity AI' with a specific query and detail level, which distinguishes it from siblings like 'chat_perplexity' or 'extract_url_content'. However, it doesn't explicitly differentiate from 'find_apis' or 'get_documentation' for information-finding tasks, keeping it from a perfect score.

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 provides implied usage guidelines by stating it's 'useful for general knowledge questions, finding information, or getting different perspectives', which suggests when to use it. However, it lacks explicit when-not-to-use guidance or named alternatives among siblings, such as when to prefer 'chat_perplexity' for conversational queries.

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

Related 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/wysh3/perplexity-mcp-zerver'

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