### Node.js HTTP Server Deployment Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Instructions for setting up and starting the MCP HTTP server using Node.js. Includes setting the API key, installing dependencies, building the project, and starting the server in different modes (HTTP, public access). ```bash export PERPLEXITY_API_KEY=your_key_here npm install && npm run build # Start HTTP server npm run start:http # Listening at http://0.0.0.0:8080/mcp # Start with public access npm run start:http:public ``` -------------------------------- ### Deploy MCP Server with Node.js Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/README.md Set the Perplexity API key, install dependencies, build the project, and start the HTTP server using npm commands. ```bash export PERPLEXITY_API_KEY=your_key_here npm install && npm run build && npm run start:http ``` -------------------------------- ### Local Development with STDIO Mode Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/DOCKER.md Install dependencies, build the project, and start the server locally using STDIO transport for development. This method bypasses Docker. ```bash npm install npm run build PERPLEXITY_API_KEY=your_key_here npm start ``` -------------------------------- ### Build Docker Image Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/DOCKER.md Build the Docker image from the project root. Ensure Docker is installed and you are in the project directory. ```bash docker build -t perplexity-mcp-server . ``` -------------------------------- ### Install Perplexity MCP Server via Claude Plugin Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/README.md Instructions for installing the Perplexity MCP server as a plugin within the Claude environment. This involves setting the API key as an environment variable and then using Claude commands to add and install the plugin. ```bash export PERPLEXITY_API_KEY="your_key_here" claude # Then run: /plugin marketplace add perplexityai/modelcontextprotocol # Then run: /plugin install perplexity ``` -------------------------------- ### Install MCP Server via npx (Quiet Mode) Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt If your MCP client encounters EOF errors during initialization, try replacing 'npx -y' with 'npx -yq' to suppress npx's installation output on stdout. ```bash npx -yq @perplexity-ai/mcp-server ``` -------------------------------- ### Claude Plugin Marketplace Installation Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Install the Perplexity MCP server as a Claude plugin. First, set your API key as an environment variable, then use the 'claude' command to add and install the plugin. ```bash export PERPLEXITY_API_KEY="your_key_here" claude # Then inside Claude: /plugin marketplace add perplexityai/modelcontextprotocol /plugin install perplexity ``` -------------------------------- ### Docker Build and Run Commands Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Commands for building a Docker image for the MCP server and running it with various configurations, including basic setup, extended timeouts, proxy settings, and using a `.env` file. ```bash # Build docker build -t perplexity-mcp-server . # Run (basic) docker run --rm -p 8080:8080 \ -e PERPLEXITY_API_KEY=your_key_here \ perplexity-mcp-server # Run with extended timeout and proxy docker run --rm -p 8080:8080 \ -e PERPLEXITY_API_KEY=your_key_here \ -e PERPLEXITY_TIMEOUT_MS=600000 \ -e PERPLEXITY_PROXY=https://user:pass@proxy.corp.com:8080 \ perplexity-mcp-server # Run with .env file docker run --rm -p 8080:8080 --env-file .env perplexity-mcp-server ``` -------------------------------- ### Configure MCP Servers in Client Config Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/README.md Use the `mcpServers` wrapper in client configurations for manual setup. Ensure the structure matches the client's schema. ```json { "mcpServers": { "perplexity": { "command": "npx", "args": ["-y", "@perplexity-ai/mcp-server"], "env": { "PERPLEXITY_API_KEY": "your_key_here" } } } } ``` -------------------------------- ### Install MCP Server via npx Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Use this command to add the MCP server to Claude Code or Codex for local integration. Ensure your PERPLEXITY_API_KEY is set. ```bash # Add to Claude Code claude mcp add perplexity --env PERPLEXITY_API_KEY="your_key_here" -- npx -y @perplexity-ai/mcp-server # Add to Codex codex mcp add perplexity --env PERPLEXITY_API_KEY="your_key_here" -- npx -y @perplexity-ai/mcp-server ``` -------------------------------- ### Proxy-Aware Fetch Wrapper Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Use `proxyAwareFetch` to automatically route requests through a proxy if environment variables like PERPLEXITY_PROXY, HTTPS_PROXY, or HTTP_PROXY are set. It falls back to native fetch when no proxy is configured. Ensure `undici` is installed for proxy support. ```typescript import { proxyAwareFetch, getProxyUrl } from "./server.js"; // Check active proxy const proxy = getProxyUrl(); console.log(proxy); // "https://user:pass@proxy.corp.example.com:8080" or undefined // Direct usage — proxy is applied automatically based on env vars process.env.PERPLEXITY_PROXY = "https://proxy.corp.example.com:8080"; const response = await proxyAwareFetch("https://api.perplexity.ai/chat/completions", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer pplx-...", }, body: JSON.stringify({ model: "sonar-pro", messages: [{ role: "user", content: "Hello" }] }), }); const data = await response.json(); ``` -------------------------------- ### Deploy MCP Server with Docker Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/README.md Build the Docker image and run the MCP server container, exposing the default port and setting the required API key. ```bash docker build -t perplexity-mcp-server . docker run -p 8080:8080 -e PERPLEXITY_API_KEY=your_key_here perplexity-mcp-server ``` -------------------------------- ### Run Docker Container with Proxy Support Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/DOCKER.md Run the Docker container with proxy support. Configure the PERPLEXITY_PROXY environment variable with your proxy host and port. Authentication can be included in the URL if needed. ```bash docker run --rm -p 8080:8080 \ -e PERPLEXITY_API_KEY=your_key_here \ -e PERPLEXITY_PROXY=https://your-proxy-host:8080 \ perplexity-mcp-server ``` ```bash docker run --rm -p 8080:8080 \ -e PERPLEXITY_API_KEY=your_key_here \ -e PERPLEXITY_PROXY=https://username:password@your-proxy-host:8080 \ perplexity-mcp-server ``` -------------------------------- ### Core Function: createPerplexityServer Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Factory function that instantiates and returns a configured McpServer with all four tools registered. It accepts an optional `serviceOrigin` string that is forwarded as the `X-Service` HTTP header on all outbound API calls for attribution. ```APIDOC ## Core Function: `createPerplexityServer` Factory function that instantiates and returns a configured `McpServer` with all four tools registered. Accepts an optional `serviceOrigin` string that is forwarded as the `X-Service` HTTP header on all outbound API calls for attribution. ### Usage (STDIO Mode) ```typescript import { createPerplexityServer } from "./server.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; // STDIO mode — used by src/index.ts const server = createPerplexityServer("my-custom-client"); const transport = new StdioServerTransport(); await server.connect(transport); ``` ### Usage (HTTP Mode) ```typescript import { createPerplexityServer } from "./server.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import express from "express"; const app = express(); const mcpServer = createPerplexityServer(); // serviceOrigin optional app.all("/mcp", async (req, res) => { const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true, }); res.on("close", () => transport.close()); await mcpServer.connect(transport); await transport.handleRequest(req, res, req.body); }); app.listen(8080); // Server accessible at http://localhost:8080/mcp ``` ``` -------------------------------- ### Manual MCP Client Configuration Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Configure MCP servers for clients like Cursor, Claude Desktop, Kiro, Windsurf, and VS Code using this JSON structure. Replace 'your_key_here' with your actual API key and adjust PERPLEXITY_TIMEOUT_MS as needed. ```json { "mcpServers": { "perplexity": { "command": "npx", "args": ["-y", "@perplexity-ai/mcp-server"], "env": { "PERPLEXITY_API_KEY": "your_key_here", "PERPLEXITY_TIMEOUT_MS": "600000" } } } } ``` -------------------------------- ### Create Perplexity Server for STDIO and HTTP modes Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt The createPerplexityServer factory function instantiates a configured McpServer. It accepts an optional serviceOrigin string for attribution in HTTP calls. STDIO mode is used by src/index.ts, while HTTP mode is used by src/http.ts. ```typescript import { createPerplexityServer } from "./server.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; // STDIO mode — used by src/index.ts const server = createPerplexityServer("my-custom-client"); const transport = new StdioServerTransport(); await server.connect(transport); ``` ```typescript // HTTP mode — used by src/http.ts import express from "express"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; const app = express(); const mcpServer = createPerplexityServer(); // serviceOrigin optional app.all("/mcp", async (req, res) => { const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true, }); res.on("close", () => transport.close()); await mcpServer.connect(transport); await transport.handleRequest(req, res, req.body); }); app.listen(8080); // Server accessible at http://localhost:8080/mcp ``` -------------------------------- ### perplexity_reason Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Performs step-by-step analytical reasoning with web grounding using the `sonar-reasoning-pro` model. Best for math, logic, comparisons, multi-step problem solving, and any task requiring chain-of-thought. ```APIDOC ## MCP Tool: `perplexity_reason` ### Description Step-by-step analytical reasoning with web grounding using the `sonar-reasoning-pro` model. Best for math, logic, comparisons, multi-step problem solving, and any task requiring chain-of-thought. Supports `strip_thinking` to suppress intermediate reasoning tokens in output, plus recency and domain filters. ### Tool Call Example ```json { "tool": "perplexity_reason", "arguments": { "messages": [ { "role": "user", "content": "Compare the time complexity of QuickSort vs MergeSort. Which should I prefer for sorting 10M records that are nearly sorted, and why?" } ], "strip_thinking": false, "search_recency_filter": "month", "search_context_size": "low" } } ``` ### Expected Structured Output ```json { "response": "\nQuickSort average O(n log n), worst O(n²)...\n\n\nFor nearly-sorted data, MergeSort is preferred because...\n\nCitations:\n[1] https://..." } ``` ### Input Schema | Field | Type | Required | Description | |---|---|---|---| | `messages` | `{role, content}[]` | ✅ | Query messages | | `strip_thinking` | `boolean` | No | Remove `` tokens (default: `false`) | | `search_recency_filter` | `"hour"│"day"│"week"│"month"│"year"` | No | Filter by recency | | `search_domain_filter` | `string[]` | No | Domain allow/deny list | | `search_context_size` | `"low"│"medium"│"high"` | No | Web context depth | ``` -------------------------------- ### Set Proxy Environment Variable (Bash) Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/README.md Configure the `PERPLEXITY_PROXY` environment variable to route internet traffic through your network's proxy. Include username and password if required. ```bash export PERPLEXITY_PROXY=https://your-proxy-host:8080 ``` ```bash export PERPLEXITY_PROXY=https://username:password@your-proxy-host:8080 ``` -------------------------------- ### Run Docker Container with Environment File Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/DOCKER.md Run the Docker container using an environment file to manage configuration variables like API key, timeout, and proxy. Ensure the .env file is in the same directory or specify its path. ```bash docker run --rm -p 8080:8080 --env-file .env perplexity-mcp-server ``` -------------------------------- ### Run Docker Container with Custom Timeout Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/DOCKER.md Run the Docker container with a custom request timeout in milliseconds. The default is 5 minutes. Ensure PERPLEXITY_API_KEY is also set. ```bash docker run --rm -p 8080:8080 \ -e PERPLEXITY_API_KEY=your_key_here \ -e PERPLEXITY_TIMEOUT_MS=600000 \ perplexity-mcp-server ``` -------------------------------- ### Add Perplexity MCP Server with Codex Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/README.md Use this command to add the Perplexity MCP server using Codex, setting the API key via environment variables. Ensure you replace 'your_key_here' with your actual Perplexity API key. ```bash codex mcp add perplexity --env PERPLEXITY_API_KEY="your_key_here" -- npx -y @perplexity-ai/mcp-server ``` -------------------------------- ### Add Perplexity MCP Server with Claude Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/README.md Use this command to add the Perplexity MCP server using Claude, setting the API key via environment variables. Ensure you replace 'your_key_here' with your actual Perplexity API key. ```bash claude mcp add perplexity --env PERPLEXITY_API_KEY="your_key_here" -- npx -y @perplexity-ai/mcp-server ``` -------------------------------- ### perplexity_ask Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Performs conversational Q&A with real-time web grounding using the `sonar-pro` model. Ideal for quick factual questions, summaries, and general lookups. Returns AI-synthesized text with numbered citation footnotes. ```APIDOC ## MCP Tool: `perplexity_ask` ### Description Conversational Q&A with real-time web grounding using the `sonar-pro` model. Best for quick factual questions, summaries, and general lookups. Returns AI-synthesized text with numbered citation footnotes. Supports recency filters, domain restrictions, and search context size tuning. ### Tool Call Example ```json { "tool": "perplexity_ask", "arguments": { "messages": [ { "role": "system", "content": "Be concise and cite your sources." }, { "role": "user", "content": "What are the latest developments in quantum computing as of this week?" } ], "search_recency_filter": "week", "search_domain_filter": ["nature.com", "arxiv.org", "-reddit.com"], "search_context_size": "medium" } } ``` ### Expected Structured Output ```json { "response": "Recent quantum computing breakthroughs include...\n\nCitations:\n[1] https://arxiv.org/abs/...\n[2] https://nature.com/articles/..." } ``` ### Input Schema | Field | Type | Required | Description | |---|---|---|---| | `messages` | `{role, content}[]` | ✅ | Conversation history (`system`/`user`/`assistant` roles) | | `search_recency_filter` | `"hour"│"day"│"week"│"month"│"year"` | No | Filter results by age | | `search_domain_filter` | `string[]` | No | Include/exclude domains (prefix `-` to exclude) | | `search_context_size` | `"low"│"medium"│"high"` | No | Web context depth (default: `"low"`) | ``` -------------------------------- ### Run Docker Container in HTTP Mode Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/DOCKER.md Run the Docker container in HTTP mode, accessible via HTTP requests on port 8080. Replace 'your_key_here' with your actual Perplexity API key. ```bash docker run --rm -p 8080:8080 -e PERPLEXITY_API_KEY=your_key_here perplexity-mcp-server ``` -------------------------------- ### MCP Client Configuration for HTTP Docker Server Source: https://github.com/perplexityai/modelcontextprotocol/blob/main/DOCKER.md Configure your MCP client to connect to the Perplexity MCP Server running in HTTP mode via Docker. The URL should point to the exposed port and path. ```json { "mcpServers": { "perplexity": { "url": "http://localhost:8080/mcp" } } } ``` -------------------------------- ### Call perplexity_reason for Analytical Reasoning Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Utilize perplexity_reason for step-by-step problem solving, comparisons, and logical analysis. It grounds reasoning in web search results and can suppress intermediate thinking tokens. Configure recency and context size filters. ```json // MCP tool call — perplexity_reason { "tool": "perplexity_reason", "arguments": { "messages": [ { "role": "user", "content": "Compare the time complexity of QuickSort vs MergeSort. Which should I prefer for sorting 10M records that are nearly sorted, and why?" } ], "strip_thinking": false, "search_recency_filter": "month", "search_context_size": "low" } } // Expected structured output { "response": "\nQuickSort average O(n log n), worst O(n²)... \n\nFor nearly-sorted data, MergeSort is preferred because...\n\nCitations:\n[1] https://..." } ``` -------------------------------- ### Call perplexity_ask for Conversational Q&A Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Use perplexity_ask for quick factual questions and summaries. Configure recency filters, domain restrictions, and context size for tailored results. The output includes synthesized text with citation footnotes. ```json // MCP tool call — perplexity_ask { "tool": "perplexity_ask", "arguments": { "messages": [ { "role": "system", "content": "Be concise and cite your sources." }, { "role": "user", "content": "What are the latest developments in quantum computing as of this week?" } ], "search_recency_filter": "week", "search_domain_filter": ["nature.com", "arxiv.org", "-reddit.com"], "search_context_size": "medium" } } // Expected structured output { "response": "Recent quantum computing breakthroughs include...\n\nCitations:\n[1] https://arxiv.org/abs/...\n[2] https://nature.com/articles/..." } ``` -------------------------------- ### MCP Tool: perplexity_search Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Performs a raw web search returning a ranked list of results with titles, URLs, snippets, and dates. It directly uses the `/search` endpoint and is suitable for discovering URLs, checking current news, or finding sources for downstream processing. ```APIDOC ## MCP Tool: `perplexity_search` ### Description Raw web search returning a ranked list of results with titles, URLs, snippets, and dates — no AI synthesis. Uses the `/search` endpoint directly. Best for discovering URLs, checking current news, or finding sources for downstream processing. ### Input Schema | Field | Type | Required | Description | |---|---|---|---| | `query` | `string` | ✅ | Search query | | `max_results` | `number` (1–20) | No | Number of results (default: `10`) | | `max_tokens_per_page` | `number` (256–2048) | No | Tokens extracted per page (default: `1024`) | | `country` | `string` | No | ISO 3166-1 alpha-2 country code (e.g., `"US"`, `"GB"`) | ### Request Example ```json { "tool": "perplexity_search", "arguments": { "query": "OpenAI GPT-5 release date announcement", "max_results": 5, "max_tokens_per_page": 512, "country": "US" } } ``` ### Response Example ```json { "results": "Found 5 search results:\n\n1. **OpenAI Announces GPT-5 Launch**\n URL: https://openai.com/blog/...\n GPT-5 is set to launch...\n Date: 2025-05-14\n\n2. **GPT-5 Features and Capabilities**\n URL: https://techcrunch.com/...\n ..." } ``` ``` -------------------------------- ### Call perplexity_research for Deep Multi-Source Research Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Employ perplexity_research for comprehensive topic overviews and literature reviews. It uses SSE streaming for long-running inference and supports options to strip thinking tokens and tune reasoning effort for deeper analysis. ```json // MCP tool call — perplexity_research { "tool": "perplexity_research", "arguments": { "messages": [ { "role": "user", "content": "Provide a comprehensive overview of mRNA vaccine technology, covering mechanisms, current approvals, and ongoing research." } ], "strip_thinking": true, "reasoning_effort": "high" } } // Expected structured output { "response": "## mRNA Vaccine Technology\n\n### Mechanism of Action\n...\n\nCitations:\n[1] https://...\n[2] https://..." } ``` -------------------------------- ### Call perplexity_search tool Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Use the perplexity_search tool for raw web searches. It returns a ranked list of results with titles, URLs, snippets, and dates. Best for discovering URLs, checking current news, or finding sources for downstream processing. ```json // MCP tool call — perplexity_search { "tool": "perplexity_search", "arguments": { "query": "OpenAI GPT-5 release date announcement", "max_results": 5, "max_tokens_per_page": 512, "country": "US" } } // Expected structured output { "results": "Found 5 search results:\n\n1. **OpenAI Announces GPT-5 Launch**\n URL: https://openai.com/blog/... GPT-5 is set to launch...\n Date: 2025-05-14\n 2. **GPT-5 Features and Capabilities**\n URL: https://techcrunch.com/... ..." } ``` -------------------------------- ### Perform Chat Completion with Perplexity Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Internal function to call the Perplexity /chat/completions endpoint. Automatically switches to SSE streaming for sonar-deep-research model and appends citations as footnotes. Supports optional ChatCompletionOptions for search filtering. ```typescript import { performChatCompletion } from "./server.js"; import type { Message, ChatCompletionOptions } from "./types.js"; const messages: Message[] = [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Summarize the latest AI safety research." }, ]; const options: ChatCompletionOptions = { search_recency_filter: "month", search_domain_filter: ["arxiv.org", "openai.com"], search_context_size: "high", }; // Quick answer with sonar-pro const answer = await performChatCompletion(messages, "sonar-pro", false, "my-app", options); console.log(answer); // "Recent AI safety research includes... // // Citations: // [1] https://arxiv.org/..." ``` ```typescript // Deep research with thinking stripped const research = await performChatCompletion( messages, "sonar-deep-research", true, // strip_thinking = true "my-app", { reasoning_effort: "high" } ); ``` ```typescript // Advanced reasoning const reasoning = await performChatCompletion(messages, "sonar-reasoning-pro", false); ``` -------------------------------- ### Perform Search with Perplexity Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Internal function that calls the Perplexity /search endpoint and formats results into a human-readable string with numbered entries including title, URL, snippet, and date. ```typescript import { performSearch } from "./server.js"; // Basic search const results = await performSearch("TypeScript 5.0 new features", 5); console.log(results); // "Found 5 search results: // // 1. **TypeScript 5.0 Announcement** // URL: https://devblogs.microsoft.com/typescript/... // TypeScript 5.0 introduces decorators... // Date: 2023-03-16 // ..." ``` ```typescript // Geo-targeted search with token limits const usResults = await performSearch( "federal interest rate decision", 10, // max_results 512, // max_tokens_per_page "US", // country "news-app" // serviceOrigin ); ``` -------------------------------- ### Core Function: performChatCompletion Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Internal function that calls the Perplexity `/chat/completions` endpoint. It automatically switches to SSE streaming for the `sonar-deep-research` model and appends citations as numbered footnotes. Supports optional `ChatCompletionOptions` for search filtering. ```APIDOC ## Core Function: `performChatCompletion` Internal function that calls the Perplexity `/chat/completions` endpoint. Automatically switches to SSE streaming for the `sonar-deep-research` model. Appends citations as numbered footnotes. Supports optional `ChatCompletionOptions` for search filtering. ### Parameters - `messages` (Message[]): An array of message objects representing the conversation history. - `model` (string): The model to use for chat completion (e.g., `"sonar-pro"`, `"sonar-deep-research"`, `"sonar-reasoning-pro"`). - `strip_thinking` (boolean): Whether to strip thinking process from the response (default: `false`). - `serviceOrigin` (string): An optional identifier for the client service. - `options` (ChatCompletionOptions, optional): Additional options for search filtering and reasoning effort. ### Response Returns a string containing the chat completion, potentially with citations as footnotes. ### Examples #### Quick answer with sonar-pro ```typescript import { performChatCompletion } from "./server.js"; import type { Message, ChatCompletionOptions } from "./types.js"; const messages: Message[] = [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Summarize the latest AI safety research." }, ]; const answer = await performChatCompletion(messages, "sonar-pro", false, "my-app"); console.log(answer); // "Recent AI safety research includes... \n\nCitations:\n[1] https://arxiv.org/..." ``` #### Deep research with thinking stripped ```typescript const options: ChatCompletionOptions = { search_recency_filter: "month", search_domain_filter: ["arxiv.org", "openai.com"], search_context_size: "high", }; const research = await performChatCompletion( messages, "sonar-deep-research", true, // strip_thinking = true "my-app", { reasoning_effort: "high" } // Example of passing options ); ``` #### Advanced reasoning ```typescript const reasoning = await performChatCompletion(messages, "sonar-reasoning-pro", false); ``` ``` -------------------------------- ### Core Function: performSearch Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Internal function that calls the Perplexity `/search` endpoint and formats the results into a human-readable string. Each entry includes the title, URL, snippet, and date. ```APIDOC ## Core Function: `performSearch` Internal function that calls the Perplexity `/search` endpoint and formats results. Returns a human-readable string with numbered entries containing title, URL, snippet, and date. ### Parameters - `query` (string): The search query. - `max_results` (number, optional): The maximum number of results to return (default: 10). - `max_tokens_per_page` (number, optional): The maximum tokens to extract per page (default: 1024). - `country` (string, optional): ISO 3166-1 alpha-2 country code for geo-targeting (e.g., `"US"`). - `serviceOrigin` (string, optional): An identifier for the client service. ### Response Returns a formatted string of search results. ### Examples #### Basic search ```typescript import { performSearch } from "./server.js"; const results = await performSearch("TypeScript 5.0 new features", 5); console.log(results); // "Found 5 search results:\n\n1. **TypeScript 5.0 Announcement**\n URL: https://devblogs.microsoft.com/typescript/...\n TypeScript 5.0 introduces decorators...\n Date: 2023-03-16\n..." ``` #### Geo-targeted search with token limits ```typescript const usResults = await performSearch( "federal interest rate decision", 10, // max_results 512, // max_tokens_per_page "US", // country "news-app" // serviceOrigin ); ``` ``` -------------------------------- ### Use Structured Logger for Debugging Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Utilize the structured logger for writing logs to stderr, which is safe for STDIO MCP transport. The log level can be controlled via the PERPLEXITY_LOG_LEVEL environment variable. Meta objects are JSON.stringify'd. ```typescript import { logger } from "./logger.js"; // Set level via env: PERPLEXITY_LOG_LEVEL=DEBUG logger.debug("Parsed SSE chunk", { chunkSize: 512, model: "sonar-deep-research" }); // [2025-07-14T10:00:00.000Z] DEBUG: Parsed SSE chunk {"chunkSize":512,"model":"sonar-deep-research"} logger.info("Server started", { port: 8080, address: "0.0.0.0" }); // [2025-07-14T10:00:00.000Z] INFO: Server started {"port":8080,"address":"0.0.0.0"} logger.warn("Proxy configured but unreachable", { proxy: "https://proxy:8080" }); // [2025-07-14T10:00:00.000Z] WARN: Proxy configured but unreachable {"proxy":"..."} logger.error("API key missing"); // [2025-07-14T10:00:00.000Z] ERROR: API key missing // All output goes to stderr — safe with STDIO MCP transport // Meta objects are JSON.stringify'd; circular references return "[Unstringifiable]" ``` -------------------------------- ### perplexity_research Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Performs deep multi-source research using the `sonar-deep-research` model. Uses SSE streaming internally to handle long-running inference. Ideal for literature reviews, comprehensive topic overviews, and investigative queries across many sources. ```APIDOC ## MCP Tool: `perplexity_research` ### Description Deep multi-source research using the `sonar-deep-research` model. Uses SSE streaming internally to handle long-running inference. Ideal for literature reviews, comprehensive topic overviews, and investigative queries across many sources. Significantly slower (30+ seconds). Supports optional `strip_thinking` to remove chain-of-thought tokens and `reasoning_effort` to tune depth. ### Tool Call Example ```json { "tool": "perplexity_research", "arguments": { "messages": [ { "role": "user", "content": "Provide a comprehensive overview of mRNA vaccine technology, covering mechanisms, current approvals, and ongoing research." } ], "strip_thinking": true, "reasoning_effort": "high" } } ``` ### Expected Structured Output ```json { "response": "## mRNA Vaccine Technology\n\n### Mechanism of Action\n...\n\nCitations:\n[1] https://...\n[2] https://..." } ``` ### Input Schema | Field | Type | Required | Description | |---|---|---|---| | `messages` | `{role, content}[]` | ✅ | Query messages | | `strip_thinking` | `boolean` | No | Remove `` tokens (default: `false`) | | `reasoning_effort` | `"minimal"│"low"│"medium"│"high"` | No | Research depth | ``` -------------------------------- ### Validate API Responses with Zod Schemas Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Use Zod schemas to parse and validate raw API responses. Invalid responses will throw structured errors with actionable messages. Ensure the correct schema is imported for the expected response type. ```typescript import { ChatCompletionResponseSchema, SearchResponseSchema, SearchResultSchema, } from "./validation.js"; // Parse and validate a raw chat completion API response const raw = await fetch("https://api.perplexity.ai/chat/completions", { ... }); const json = await raw.json(); const validated = ChatCompletionResponseSchema.parse(json); // validated.choices[0].message.content — guaranteed to be a string // validated.citations — string[] | undefined // validated.usage.total_tokens — number | undefined // Parse and validate a search response const searchRaw = await fetch("https://api.perplexity.ai/search", { ... }); const searchJson = await searchRaw.json(); const searchData = SearchResponseSchema.parse(searchJson); // searchData.results[0].title — string (required) // searchData.results[0].url — string (required) // searchData.results[0].snippet — string | undefined // searchData.results[0].date — string | undefined // ZodError surfaces actionable messages import { z } from "zod"; try { ChatCompletionResponseSchema.parse({ choices: [] }); // empty choices fails min(1) } catch (e) { if (e instanceof z.ZodError) { console.error(e.issues); // [{ path: ["choices"], message: "Array must contain at least 1 element(s)" }] } } ``` -------------------------------- ### HTTP Server Health Check Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt A `curl` command to perform a health check on the running HTTP server. It queries the `/health` endpoint and expects a JSON response indicating the service status. ```bash curl http://localhost:8080/health # {"status":"ok","service":"perplexity-mcp-server"} ``` -------------------------------- ### Strip Thinking Tokens from Model Responses Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Use `stripThinkingTokens` to remove `` blocks from model outputs. This utility is helpful when `strip_thinking: true` is enabled for functions like `perplexity_reason` or `perplexity_research`. It handles single and multiple occurrences effectively. ```typescript import { stripThinkingTokens } from "./server.js"; const raw = ` Let me reason through this step by step... The answer is clearly B. Based on the evidence, option B is correct because...`; const clean = stripThinkingTokens(raw); console.log(clean); // "Based on the evidence, option B is correct because..." // Multiple think blocks are all removed const multi = stripThinkingTokens("step 1 Answer: X verify confirmed."); console.log(multi); // "Answer: X confirmed." ``` -------------------------------- ### Validate Messages for API Calls Source: https://context7.com/perplexityai/modelcontextprotocol/llms.txt Employ `validateMessages` as a runtime assertion to ensure the `messages` array is correctly formatted before sending it to the API. It throws descriptive errors for issues like missing `role`, null `content`, or incorrect input types. This function acts as a guard within tool handlers. ```typescript import { validateMessages } from "./server.js"; // Valid — passes silently validateMessages( [{ role: "user", content: "Hello" }], "perplexity_ask" ); // Invalid role type — throws try { validateMessages([{ role: 123, content: "hi" }], "perplexity_ask"); } catch (e) { console.error(e.message); // "Invalid message at index 0: 'role' must be a string" } // Null content — throws try { validateMessages([{ role: "user", content: null }], "perplexity_ask"); } catch (e) { console.error(e.message); // "Invalid message at index 0: 'content' must be a string" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.