Логотип Perplexity MCP Server

Perplexity MCP Server

Спільнота
escapeWu

A third-party Perplexity MCP/REST API implementation that leverages Pro account Pool to provide unlimited quota for ask and deep search capabilities.

ВидавецьescapeWu
Репозиторійperplexity-ai
МоваPython
Форки
25
Зірки
168
Доступні інструменти
0
Тип транспортуstdio, streamable-http
Категорії
ЛіцензіяMIT
Посилання
  • Підключайте інструменти до робочих процесів із ШІ

    Perplexity MCP Server надає можливості MCP, які можуть використовувати сумісні клієнтські ШІ-застосунки та агенти.

  • Доступні інструменти: 0

    Перегляньте нижче дії, які можна викликати, з назвами й описами, якщо сервер їх надає.

  • Готова конфігурація для копіювання

    Скористайтеся прикладами конфігурації, щоб налаштувати цей сервер у вибраному клієнті MCP.

  • Показники інтересу до відкритого коду

    Зірки: 168, форки: 25 — у пов’язаному репозиторії.

Thanks for LINUX DO

Perplexity MCP Server

中文文档

An unofficial Perplexity.ai server that exposes search capabilities through MCP (Model Context Protocol) and OpenAI-compatible endpoints. Supports multi-token pools for load balancing, health monitoring, and various search modes.

AGENT READ — Deployment

Read this section before advising on or executing deployment. A request for documentation, explanation, or review does not authorize a live deployment. Only change a server when the user explicitly asks to deploy, update, rebuild, restart, or roll out the service.

Route the request

User intentAgent action
Explain or prepare a local installationUse the Quick Start below; do not change remote systems.
Deploy the configured production serverFollow .agents/skills/server-deploy/SKILL.md exactly.
Validate or diagnose a deploymentStart with config, verify, status, and logs; inspect evidence before changing state.

Treat docker-compose.yml, .env.example, and deploy/compose.sh as the deployment sources of truth. The production entry point builds from the checked-out source; do not wait for or substitute a Docker Hub latest image.

First-install prerequisites

  • Require Docker with the Compose plugin.
  • Create .env and token_pool_config.json from their examples only when the destination files do not already exist. Generate a strong MCP_TOKEN (for example with openssl rand -hex 32).
  • Keep .env, token_pool_config.json, data/, CSRF/session tokens, and admin tokens out of Git and command output. Never overwrite the server copies during an update.
  • Preserve the mounted data/ directory so the model cache and WebUI/OAI/MCP session database survive container replacement.
  • On an Internet-facing host, bind to a loopback address and place the service behind TLS/reverse proxying; see .env.example for the port form.

Run the guarded deployment entrypoint from the repository checkout:

bash
./deploy/compose.sh config
./deploy/compose.sh up
./deploy/compose.sh verify
./deploy/compose.sh status

up validates .env and the non-empty token pool, builds the application image from the current checkout, replaces the service, waits for container health, calls /health, and prints status.

Production release contract

  1. Review the intended local diff on main, commit only requested files, and push that exact commit.
  2. Confirm local HEAD equals origin/main before touching the server.
  3. Require a clean remote tracked worktree; use only a fast-forward pull and verify the remote SHA equals the recorded local commit.
  4. Run ./deploy/compose.sh up, followed by verify and status.
  5. Report the deployed commit, image ID, /health result, and final container state.

Stop on a dirty remote worktree, SHA mismatch, failed build, failed health check, or failed status check. Never force-push, run git reset/git clean, use docker compose down, delete images or volumes, or replace server secrets and persistent data as part of routine deployment.

Agent Search Skill

This repository includes .agents/skills/perplexity-search/SKILL.md for Agents that need current public-web information. MCP and REST use one call contract: the bundled PerplexityRestClient exposes the same perplexity_ask_v2, perplexity_research_v2, and detached-task method names, arguments, session behavior, and result shapes as the MCP tools.

Use the standard-library Python REST client when MCP is not the selected transport:

python
import sys
sys.path.insert(0, ".agents/skills/perplexity-search/scripts")
from client import PerplexityRestClient

client = PerplexityRestClient.from_config()
result = client.perplexity_ask_v2("What changed this week? Cite primary sources.")

The command line uses the same operation names:

bash
python3 .agents/skills/perplexity-search/scripts/client.py \
  perplexity_ask_v2 "What changed this week? Cite primary sources."

Set PPLX_BASE_URL and MCP_TOKEN for REST use. The checked-in configuration is sanitized and contains no deployment credentials.

Screenshots

ADMIN Panel https://yourdomain.com/admin/

OpenAI Playground https://yourdomain.com/playground/ OpenAI Playground with persistent native follow-up conversations

Getting Started

Docker Compose Deployment

1. Prepare Configuration

Copy and edit the configuration file:

bash
cp token_pool_config-example.json token_pool_config.json

Edit token_pool_config.json with your Perplexity account tokens:

json
{
  "heart_beat": {
    "enable": true,
    "question": "What is the date today?",
    "interval": 6,
    "tg_bot_token": "your-telegram-bot-token",
    "tg_chat_id": "your-telegram-chat-id"
  },
  "fallback": {
    "fallback_to_auto": true
  },
  "incognito": {
    "enabled": false
  },
  "tokens": [
    {
      "id": "account1@example.com",
      "csrf_token": "your-csrf-token-1",
      "session_token": "your-session-token-1"
    },
    {
      "id": "account2@example.com",
      "csrf_token": "your-csrf-token-2",
      "session_token": "your-session-token-2"
    }
  ]
}

How to get tokens: Open perplexity.ai -> F12 Developer Tools -> Application -> Cookies

  • csrf_token corresponds to next-auth.csrf-token
  • session_token corresponds to __Secure-next-auth.session-token

Heartbeat Configuration (Recommand, handle cookie expire!)

Periodically checks token health and notifies via Telegram:

OptionDescription
enableEnable heartbeat checks
questionQuestion used for testing
intervalCheck interval (in hours)
tg_bot_tokenTelegram Bot Token
tg_chat_idTelegram Chat ID

Fallback Configuration (Optional)

Automatically downgrades to anonymous Auto mode when all tokens are unavailable:

OptionDescription
fallback_to_autoEnable fallback to anonymous mode (default true)

Incognito Configuration (Optional)

When enabled, forces all queries (MCP and OpenAI endpoints) to run in incognito mode, preventing search history from being saved on Perplexity accounts:

OptionDescription
enabledForce incognito mode for all queries (default false)

Can also be toggled at runtime via the Admin UI or POST /incognito/config API.

2. Start the Service

bash
# Create .env file (optional)
cp .env.example .env

# Start services
docker compose up -d

docker-compose.yml Example

yml
services:
  perplexity-mcp:
    image: shancw/perplexity-mcp:latest
    container_name: perplexity-mcp
    ports:
      - "${MCP_PORT:-8000}:8000"
    environment:
      - MCP_TOKEN=${MCP_TOKEN:-sk-123456}
      - PPLX_ADMIN_TOKEN=${PPLX_ADMIN_TOKEN:-}
      # - PPLX_SESSION_DB=/app/data/webui_sessions.sqlite3
      # - SOCKS_PROXY=${SOCKS_PROXY:-}
    volumes:
      # Mount the token pool and persistent daily model cache
      - ./token_pool_config.json:/app/token_pool_config.json
      - ./data:/app/data
    restart: unless-stopped

.env Variables

bash
MCP_PORT=8000
MCP_TOKEN=sk-123456
PPLX_ADMIN_TOKEN=your-admin-token
# PPLX_SESSION_DB=./data/webui_sessions.sqlite3
# Optional outside Docker:
# PPLX_MODELS_CONFIG_URL=https://raw.githubusercontent.com/escapeWu/perplexity-ai/main/catalog/model_config_v2.json
# PPLX_MODEL_CACHE_PATH=./data/model_config_v2.json
# PPLX_MODEL_CACHE_TTL=86400

Multi-Token Pool (Load Balancing)

Configure multiple Perplexity account tokens to enable load balancing and high availability. See the "Prepare Configuration" section above for the JSON structure.

MCP Configuration

json
{
  "mcpServers": {
    "perplexity": {
      "type": "http",
      "url": "http://127.0.0.1:8000/mcp",
      "headers": {
        "Authorization": "Bearer sk-123456"
      }
    }
  }
}

MCP Tools

ToolWhen to use
perplexity_ask_v2Focused current search with optional OAI model ID, thinking, files, and session_id
perplexity_research_v2Deep Research with optional files and session_id
get_skill_index, get_tasks_useDiscover and read the detached-task operating guide
perplexity_task_submitStart a detached search or research task and return job_id
perplexity_task_statusObserve a detached task; only state: completed is complete
perplexity_task_cancelExplicitly cancel a detached task

The companion Python REST client exposes methods with these same names and normalizes REST responses to the same top-level status, session_id, job_id, model, and data/snapshot conventions. This lets integrations change transport without changing their search workflow.

perplexity_ask_v2 defaults to perplexity-search when model is omitted. Its model values are the same IDs returned by /v1/models, for example gpt-5-6-terra; thinking: true selects the paired thinking model. Both v2 tools create a session when session_id is omitted and return it at the top level of the result:

json
{
  "status": "ok",
  "session_id": "sess_...",
  "model": "gpt-5-6-terra-thinking",
  "data": {"answer": "...", "sources": []}
}

The legacy tools list_models, search, research, perplexity_ask, perplexity_search, perplexity_reason, perplexity_research, and toggle_builtin_tools remain callable for compatibility, but are marked deprecated / pending_removal in MCP metadata and descriptions.

OpenAI Compatible Endpoints

Base URL: http://127.0.0.1:8000/v1 Authorization: Bearer <MCP_TOKEN>

Chat completions stream live upstream events by default. Pass "stream": false to wait for a complete JSON response. The Playground also requests optional Perplexity progress chunks so it can display analysis, web search, source review, and answer-writing stages. Other OpenAI clients can opt in with "perplexity": {"include_progress": true}; the extension is disabled by default for API compatibility.

Every valid chat-completions request is assigned a native conversation session. Omit session_id to start one, then read the top-level session_id from the JSON response. Streaming responses include the same value in every JSON SSE chunk and in the X-Session-ID response header. To continue, send that ID with only the current user turn:

json
{
  "model": "perplexity-search",
  "session_id": "sess_...",
  "messages": [{"role": "user", "content": "Now compare it with Tokyo"}],
  "stream": false
}

The first turn permanently binds the session to one compatible Perplexity account. Follow-ups reuse that account and the upstream native cursor; they never fail over to another account. An unknown session returns HTTP 404.

Examples

List Models

bash
curl http://127.0.0.1:8000/v1/models -H "Authorization: Bearer sk-123456"

Chat Completions (Non-streaming)

bash
curl http://127.0.0.1:8000/v1/chat/completions \
  -H "Authorization: Bearer sk-123456" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "perplexity-search",
    "messages": [{"role": "user", "content": "How is the weather today?"}],
    "stream": false
  }'

Chat Completions (Streaming)

bash
curl http://127.0.0.1:8000/v1/chat/completions \
  -H "Authorization: Bearer sk-123456" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "perplexity-thinking",
    "messages": [{"role": "user", "content": "Analyze AI trends"}],
    "perplexity": {"include_progress": true}
  }'

Progress updates remain regular chat.completion.chunk events with an empty content delta and an additional perplexity_progress field. Clients that do not understand the extension can leave it disabled.

For catalog models that provide both regular and reasoning variants, pass "thinking": true while keeping the regular model ID. The server resolves the paired -thinking model before calling Perplexity:

json
{
  "model": "gpt-5-6-terra",
  "thinking": true,
  "messages": [{"role": "user", "content": "Analyze this problem"}]
}

Models without a reasoning variant return an invalid_request_error. reasoning_effort is intentionally rejected: Perplexity's web endpoint exposes reasoning through model selection and does not provide a verified effort control.

Supported Models

The repository publishes a validated Perplexity v2 model snapshot at catalog/model_config_v2.json. Servers fetch that snapshot from GitHub Raw every 24 hours and persist a local cache. /v1/models, MCP list_models, validation, and upstream model_preference routing all use that same catalog.

  • Pro accounts expose Pro models.
  • Max accounts expose both Pro and Max models.
  • Max-only requests are routed only to Max accounts.
  • Browser-agent entries are excluded because they do not use the search API.
  • perplexity-search, perplexity-thinking, and perplexity-deepsearch remain stable default IDs. Use GET /v1/models for the current full list.

If the daily refresh fails, the last valid on-disk catalog remains active. Static built-in mappings are used only when no valid cache exists.

Star History

What's New

  • 2026-09-20: v2.0.0 — Major runtime rewrite: replace the blocking per-request chat path with a durable, observable task runtime shared by OAI, MCP, and WebUI. Add account-affine concurrency, priority queues, deadlines, idempotency, retained events, resumable streams/results, strict upstream validation, bounded inputs and snapshots, atomic persistence, and background tasks that survive observer disconnects.
  • 2026-08-16: v1.15.0 — Add OpenAI-aligned v2 MCP ask/research tools and REST session continuation with account-bound conversations, refresh the dynamic model catalog, deprecate legacy MCP tools, and align the Playground model and Thinking controls with Perplexity WebUI.
  • 2026-08-13: v1.14.0 — Add server-backed Playground conversations with a responsive session sidebar, native Perplexity follow-up threads, persistent history, and immutable per-conversation account binding without cross-account failover.
  • 2026-08-12: v1.13.3 — Upgrade curl-cffi browser fingerprints to stop Grok 4.5 and Claude Sonnet 5 requests from silently falling back to Best/turbo, and expose requested-versus-effective model metadata with a server warning when upstream downgrades recur.
  • 2026-07-31: v1.13.2 — Prevent all explicitly selected models from being silently downgraded by matching Perplexity's current browser request protocol, and publish a validated Pro/Max model snapshot that servers refresh daily from GitHub Raw.
  • 2026-07-30: v1.13.1 — Restore real-time Playground progress and answer streaming for Perplexity's new block-based response protocol, reconstruct offset Markdown chunks, and deduplicate repeated lifecycle stages.
  • 2026-07-30: v1.13.0 — Add a daily cached Perplexity model catalog with Pro/Max-aware discovery and account routing, expose live model metadata in the Playground, and remove unused client-side SDK, account automation, Labs, examples, and legacy assets for server-only deployment.
  • 2026-07-29: v1.12.0 — Add optional structured Perplexity progress events and a live Playground stage timeline, preserve partial output across stream failures and cancellation, and align service requests with the browser query_source required by current models.
  • 2026-07-29: v1.11.0 — Stream OpenAI-compatible chat completions from upstream in real time by default, retain opt-in complete JSON responses with stream: false, add WebUI stream mode controls and working cancellation, and harden stream failover and cleanup.
  • 2026-07-29: v1.10.1 — Close synchronous streaming responses reliably, move user-info network calls outside the pool lock, use starvation-free smooth weighted round-robin scheduling, sync runtime dependencies, and make Playground cancellation abort active requests.
  • 2026-07-28: v1.10.0 — Add the current non-Max model lineup (Sonar 2, GPT-5.6 Terra, Gemini 3.1 Pro, Claude Sonnet 5, Kimi K3, GLM 5.2, Grok 4.5, and Nemotron 3 Ultra), centralize model mappings, and sync MCP/OpenAI discovery, tests, and docs.

Upstream Project

https://github.com/helallao/perplexity-ai

  • fix param lack, auto redirect to GPT-5.6-nano, and add fancy mcp/restapi server

Встановлення

TypingMind
{
  "mcpServers": {
    "perplexity-ai": {
      "command": "python",
      "args": [
        "-m",
        "perplexity.server.main"
      ]
    }
  }
}

Використовуйте MCP Perplexity MCP Server з різними моделями ШІ

TypingMind підключає інструменти MCP на рівні робочого простору, тож після підключення Perplexity MCP Server ви можете використовувати їх із різними моделями ШІ в TypingMind, а не налаштовувати окремо для кожної моделі. Ви можете запустити MCP локально на своєму пристрої або підключитися до віддаленого сервера MCP за URL.

Варіант 1: використовуйте локальний конектор

Виберіть цей варіант, якщо серверу MCP потрібен доступ до локальних файлів, програм або приватних ресурсів на вашому комп’ютері.

1

Відкрийте налаштування MCP

У TypingMind перейдіть до розділу «Налаштування», відкрийте «Розширені налаштування», потім «Протокол контексту моделі» й виберіть «Параметри конектора».

  1. Відкрийте TypingMind у браузері.
  2. Натисніть значок налаштувань.
  3. Перейдіть до розділу «Розширені налаштування».
  4. Відкрийте розділ «Протокол контексту моделі».
  5. Натисніть «Параметри конектора» й виберіть «Цей пристрій».
Екран налаштування конектора MCP у TypingMind з вибраним варіантом «Цей пристрій»
2

Виконайте команду конектора

Виберіть «Цей пристрій», скопіюйте команду з TypingMind і виконайте її в терміналі. Не зупиняйте процес, поки користуєтеся MCP.

  1. Скопіюйте команду налаштування, показану в TypingMind.
  2. Відкрийте «Термінал» у macOS або Windows Terminal у Windows.
  3. Вставте й виконайте команду.
  4. Підтвердьте встановлення пакета, якщо термінал запитає дозволу продовжити.
  5. Не закривайте вікно термінала й не зупиняйте процес, поки користуєтеся інструментами MCP.
3

Додайте Perplexity MCP Server як сервер

Коли статус конектора зміниться на «Готово», натисніть «Змінити сервери» та вставте конфігурацію сервера MCP.

  1. Зачекайте, доки статус конектора зміниться на «Готово».
  2. Натисніть «Змінити сервери».
  3. Вставте конфігурацію сервера MCP Perplexity MCP Server.
  4. Збережіть список серверів.
  5. Оновіть дані, щоб переконатися, що конектор досі готовий до роботи.
Налаштування MCP у TypingMind з активним сервером і кнопкою «Змінити сервери»
{
  "mcpServers": {
    "perplexity-ai": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Використовуйте підключення з різними моделями

Збережіть список серверів, відкрийте «Плагіни», увімкніть інструменти MCP для Perplexity MCP Server, а потім виберіть будь-яку підтримувану модель ШІ в TypingMind і використовуйте інструменти в чаті або призначте їх агенту ШІ.

  1. Відкрийте сторінку «Плагіни» в TypingMind.
  2. Увімкніть інструменти MCP для Perplexity MCP Server.
  3. Почніть чат і виберіть модель ШІ, яку хочете використовувати.
  4. Використовуйте інструменти MCP у чаті або призначте їх агенту ШІ.
  5. За потреби перемикайтеся на іншу модель ШІ без повторного підключення MCP.
Чат TypingMind із використанням увімкнених інструментів MCP і вибраної моделі ШІ
Допоможете з цим завданням через Perplexity MCP Server?
Perplexity MCP Server
Звісно. Я це прочитав.
Ось що я знайшов за допомогою Perplexity MCP Server.

Варіант 2: додайте URL сервера MCP

Виберіть цей варіант, якщо Perplexity MCP Server уже розміщено віддалено або вашій команді потрібен один спільний конектор для кількох користувачів.

1

Відкрийте конектори MCP

У TypingMind перейдіть до розділу «Плагіни», відкрийте «Конектори MCP» і виберіть «Додати URL».

  1. Відкрийте TypingMind у браузері.
  2. Перейдіть до розділу «Плагіни».
  3. Відкрийте конектори MCP.
  4. Натисніть «Додати URL».
Форма «Додати URL власного сервера MCP» у TypingMind
2

Вставте URL сервера

Введіть URL сервера MCP від постачальника у поле «URL сервера». Додайте назву підключення, опис, значок, власні HTTP-заголовки або налаштування клієнта OAuth, якщо сервер їх потребує.

  1. Вставте URL сервера MCP від постачальника у поле «URL сервера».
  2. Введіть назву підключення для Perplexity MCP Server.
  3. Додайте опис і значок, щоб було легше впізнати підключення.
  4. Додайте власні HTTP-заголовки або дані клієнта OAuth, якщо сервер потребує автентифікації.
3

Створіть підключення

Натисніть «Створити підключення», потім поверніться до списку плагінів і переконайтеся, що нове підключення MCP активне.

  1. Натисніть «Створити підключення».
  2. Поверніться до списку конекторів MCP.
  3. Переконайтеся, що підключення Perplexity MCP Server відображається як активне.
  4. Оновіть список плагінів, якщо підключення не з’явилося одразу.
4

Перемикайте моделі без повторного підключення

Почніть чат із бажаною моделлю, увімкніть інструменти Perplexity MCP Server у розділі «Плагіни» й за потреби перемикайтеся на іншу модель. Підключення MCP залишається доступним у робочому просторі TypingMind.

  1. Почніть новий чат у TypingMind.
  2. Виберіть модель ШІ, яку хочете використовувати.
  3. Увімкніть інструменти Perplexity MCP Server у розділі «Плагіни».
  4. За потреби попросіть модель скористатися інструментом.
  5. Перемкніться на іншу модель ШІ й використовуйте те саме підключення MCP.
Чат TypingMind із використанням увімкнених інструментів MCP і вибраної моделі ШІ
Допоможете з цим завданням через Perplexity MCP Server?
Perplexity MCP Server
Звісно. Я це прочитав.
Ось що я знайшов за допомогою Perplexity MCP Server.

Поширені запитання

Для чого використовується сервер MCP Perplexity MCP Server?

Perplexity MCP Server — це сервер MCP, який дає змогу сумісним клієнтам ШІ підключатися до зовнішніх інструментів і контексту. У TypingMind ви можете додати цей сервер MCP один раз і зробити його інструменти доступними у своєму робочому просторі ШІ.

Чи можу я використовувати MCP Perplexity MCP Server з кількома моделями ШІ в TypingMind?

Так. TypingMind підключає інструменти MCP на рівні робочого простору, тому ви можете використовувати Perplexity MCP Server з різними моделями ШІ, як-от Claude, ChatGPT, Gemini або іншими моделями, які ви налаштували в TypingMind, без окремого налаштування сервера MCP для кожної моделі.

Навіщо використовувати MCP Perplexity MCP Server із TypingMind?

TypingMind — один із найкращих інтерфейсів для чату з великими мовними моделями, адже він об’єднує різні моделі ШІ, промпти, плагіни, агентів ШІ, ключі API та інструменти MCP в одному робочому просторі. Підключивши Perplexity MCP Server, ви зможете використовувати його інструменти MCP з вибраними моделями та впорядковано працювати з чатами в TypingMind.

Як підключити MCP Perplexity MCP Server до TypingMind?

Perplexity MCP Server можна підключити в TypingMind через локальний конектор MCP або додавши URL віддаленого сервера MCP. Використовуйте локальний конектор, коли серверу потрібен доступ до файлів, застосунків або приватних ресурсів на вашому пристрої, а URL сервера — коли сервер MCP розміщено віддалено.

Які інструменти надає MCP Perplexity MCP Server у TypingMind?

Perplexity MCP Server надає можливості MCP, які можна ввімкнути на сторінці «Плагіни» в TypingMind і використовувати в чаті або призначати агентам ШІ.

Чи потрібно передавати свої ключі API в TypingMind, щоб використовувати MCP Perplexity MCP Server?

Ні. TypingMind орієнтований насамперед на локальну роботу й дає змогу зберігати контроль над постачальниками моделей, ключами API, промптами та конфігурацією MCP. Якщо Perplexity MCP Server потребує автентифікації, під час створення підключення додайте потрібні заголовки, налаштування OAuth або локальну конфігурацію для цього сервера MCP.

Схожі сервери MCP

Усі

Створіть власний ШІ-простір уже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇