Cover image
Try Now
2025-04-02

一个困惑性API模型上下文协议(MCP)服务器,该服务器可解锁LLM代理的Perplexity搜索功能。功能具有强大的错误处理,安全输入验证以及带有showthinking参数的透明推理。采用类型安全,模块化架构和生产就绪的实用程序建造。

3 years

Works with Finder

1

Github Watches

0

Github Forks

0

Github Stars

Perplexity MCP Server

TypeScript Model Context Protocol Version License Status GitHub

An MCP server providing tools to interact with the Perplexity AI API, built using the mcp-ts-template. This server allows AI agents compatible with the Model Context Protocol (MCP) to leverage Perplexity's search-augmented query capabilities. Includes a showThinking parameter to enable reasoning models to show its internal reasoning process.

Core Features

  • Utilities: Reusable components for logging, error handling, ID generation, rate limiting, and request context management.
  • Type Safety: Strong typing with TypeScript.
  • Error Handling: Robust error handling system.
  • Security: Basic security features like input sanitization.
  • Perplexity Tool: A ready-to-use tool for interacting with the Perplexity Search API.

.clinerules: This repository includes a .clinerules file that serves as a developer cheat sheet for LLM coding agents (like Cline) providing quick references for codebase patterns, file locations, and code snippets specific to this project.

Table of Contents

Overview

What is Model Context Protocol?

Model Context Protocol (MCP) is a framework that enables AI systems to interact with external tools and resources. It allows language models to:

  • Execute tools that perform actions and return results
  • Access structured resources that provide information
  • Create contextual workflows through standardized interfaces

This server allows AI systems to use the Perplexity API via MCP.

Architecture & Components

The server is based on the mcp-ts-template and follows its modular architecture:

Click to expand architecture diagram
flowchart TB
    subgraph API["API Layer"]
        direction LR
        MCP["MCP Protocol"]
        Val["Validation"]
        San["Sanitization"]

        MCP --> Val --> San
    end

    subgraph Core["Core Components"]
        direction LR
        Config["Configuration"]
        Logger["Logging System"]
        Error["Error Handling"]
        Server["MCP Server"]

        Config --> Server
        Logger --> Server
        Error --> Server
    end

    subgraph Implementation["Implementation Layer"]
        direction LR
        Tool["Tools (Perplexity)"]
        Util["Utilities"]

        Tool --> Server
        Util --> Tool
    end

    San --> Config
    San --> Server

    classDef layer fill:#2d3748,stroke:#4299e1,stroke-width:3px,rx:5,color:#fff
    classDef component fill:#1a202c,stroke:#a0aec0,stroke-width:2px,rx:3,color:#fff
    class API,Core,Implementation layer
    class MCP,Val,San,Config,Logger,Error,Server,Tool,Util component

Core Components:

  • Configuration System: Environment-aware configuration with validation
  • Logging System: Structured logging with sensitive data redaction
  • Error Handling: Centralized error processing with consistent patterns
  • MCP Server: Protocol implementation for tools
  • Validation Layer: Input validation and sanitization using validator and sanitize-html.
  • Utilities: Reusable utility functions for common operations

Features

Core Utilities

  • Logging: Configurable logging with file rotation and sensitive data redaction
  • Error Handling: Pattern-based error classification and standardized reporting
  • ID Generation: Secure unique identifier creation with prefix support
  • Rate Limiting: Request throttling to prevent API abuse
  • Request Context: Request tracking and correlation
  • Sanitization: Input validation and cleaning using validator and sanitize-html.
  • Cost Tracking: Estimation of Perplexity API costs based on model and token usage

Type Safety

  • Global Types: Shared type definitions for consistent interfaces
  • Error Types: Standardized error codes and structures
  • MCP Protocol Types: Type definitions for the MCP protocol
  • Tool Types: Interfaces for tool registration and configuration

Error Handling

  • Pattern-Based Classification: Automatically categorize errors based on message patterns
  • Consistent Formatting: Standardized error responses with additional context
  • Error Mapping: Custom error transformation for domain-specific errors
  • Safe Try/Catch Patterns: Centralized error processing helpers

Security

  • Input Validation: Using validator for various data type checks.
  • Input Sanitization: Using sanitize-html to prevent injection attacks.
  • Parameter Bounds: Enforced limits within sanitization logic to prevent abuse.
  • Sensitive Data Redaction: Automatic redaction in logs.

Perplexity Search Tool

  • perplexity_search: The core tool provided by this server, enabling interaction with the Perplexity Search API.

Installation

Prerequisites

Setup

  1. Clone this repository:

    # Replace with the actual repository URL if different
    git clone https://github.com/casey/perplexity-mcp-server.git
    cd perplexity-mcp-server
    
  2. Install dependencies:

    npm install
    
  3. Build the project:

    npm run build
    

Configuration

Environment Variables

This server requires the following environment variables:

Variable Description Default Value
PERPLEXITY_API_KEY API key for authentication with Perplexity (Required)
PERPLEXITY_DEFAULT_MODEL Default model to use for Perplexity requests "sonar-reasoning"
PERPLEXITY_DEFAULT_SEARCH_CONTEXT Search context size ('low', 'medium', 'high') "high"
LOG_LEVEL Logging level ("debug", "info", "warn", "error") "info"
NODE_ENV Runtime environment ("development", "production") "development"

MCP Client Settings

Add this server to your MCP client settings (e.g., in VS Code or Claude Desktop):

{
  "mcpServers": {
    "perplexity": {
      "command": "node",
      "args": ["/path/to/perplexity-mcp-server/dist/index.js"],
      "env": {
        "PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY"
      }
    }
  }
}

Replace /path/to/perplexity-mcp-server/dist/index.js with the actual path to the built server file and YOUR_PERPLEXITY_API_KEY with your key.

Configuration System (Internal)

The internal configuration system manages settings:

  • Environment Config: Loads settings like the API key from environment variables.
  • Validation: Validates configuration values (e.g., search context size).
  • Logging: Logs warnings for missing or invalid configuration.

Project Structure

The codebase follows a modular structure within the src/ directory:

src/
├── config/           # Configuration management
├── index.ts          # Main entry point
├── mcp-server/       # MCP server implementation
│   ├── server.ts     # Server setup and registration
│   └── tools/        # Tool implementations
│       └── perplexitySearch/
│           ├── index.ts
│           ├── logic.ts
│           └── registration.ts
├── services/         # External service integrations
│   ├── index.ts
│   └── perplexityApi.ts
├── types-global/     # Global type definitions
│   ├── errors.ts
│   ├── mcp.ts
│   └── tool.ts
└── utils/            # Utility functions
    ├── costTracker.ts
    ├── errorHandler.ts
    ├── idGenerator.ts
    ├── index.ts
    ├── logger.ts
    ├── rateLimiter.ts
    ├── requestContext.ts
    └── sanitization.ts

For a detailed, up-to-date view of the project structure, run:

npm run tree

Tool Documentation

perplexity_search

The perplexity_search tool performs search-augmented queries using the Perplexity API. It takes a natural language query, performs a web search using Perplexity's backend, and then uses an LLM to synthesize an answer based on the search results.

Input Parameters

Parameter Type Required Description
query string Yes The primary search query or question to be processed by Perplexity
return_related_questions boolean No When true, instructs the Perplexity model to suggest related questions alongside the main answer (Default: false)
search_recency_filter string No Filter search results by timeframe (e.g., 'day', 'week', 'month', 'year')
search_domain_filter string[] No Limit search to specific domains (e.g., ['wikipedia.org'])
showThinking boolean No Include the model's internal reasoning in the response (Default: false)

Examples

Basic usage:

{
  "query": "What are the latest developments in quantum computing?"
}

Advanced usage:

{
  "query": "What are the latest developments in quantum computing?",
  "return_related_questions": true,
  "search_recency_filter": "month",
  "search_domain_filter": ["nature.com", "science.org", "arxiv.org"],
  "showThinking": true
}

Development Guidelines

This project uses the structure and guidelines from the mcp-ts-template.

Adding a New Tool

Follow the template's guidelines:

  1. Create Directory: src/mcp-server/tools/yourNewTool/
  2. Define Logic & Schema: logic.ts (Input/Output types, validation schema, core function).
  3. Implement Registration: registration.ts (Import logic, schema, use ErrorHandler.tryCatch and server.tool()).
  4. Export Registration: index.ts (Export registration function).
  5. Register in Server: src/mcp-server/server.ts (Import and call registration function).

Adding a New Resource

Resources are not the primary focus of this server, but if needed, follow the template's guidelines:

  1. Create Directory: src/mcp-server/resources/yourNewResource/
  2. Define Logic & Schema: logic.ts (Param types, query schema, core function).
  3. Implement Registration: registration.ts (Import logic, schema, define ResourceTemplate, use ErrorHandler.tryCatch and server.resource()).
  4. Export Registration: index.ts (Export registration function).
  5. Register in Server: src/mcp-server/server.ts (Import and call registration function).

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.


Built with the Model Context Protocol

相关推荐

  • NiKole Maxwell
  • I craft unique cereal names, stories, and ridiculously cute Cereal Baby images.

  • Joshua Armstrong
  • Confidential guide on numerology and astrology, based of GG33 Public information

  • https://suefel.com
  • Latest advice and best practices for custom GPT development.

  • Emmet Halm
  • Converts Figma frames into front-end code for various mobile frameworks.

  • Elijah Ng Shi Yi
  • Advanced software engineer GPT that excels through nailing the basics.

  • Yasir Eryilmaz
  • AI scriptwriting assistant for short, engaging video content.

  • Alexandru Strujac
  • Efficient thumbnail creator for YouTube videos

  • Daren White
  • A supportive coach for mastering all Spanish tenses.

  • J. DE HARO OLLE
  • Especialista en juegos de palabras en varios idiomas.

  • albert tan
  • Japanese education, creating tailored learning experiences.

  • https://maiplestudio.com
  • Find Exhibitors, Speakers and more

  • apappascs
  • 发现市场上最全面,最新的MCP服务器集合。该存储库充当集中式枢纽,提供了广泛的开源和专有MCP服务器目录,并提供功能,文档链接和贡献者。

  • ShrimpingIt
  • MCP系列GPIO Expander的基于Micropython I2C的操作,源自ADAFRUIT_MCP230XX

  • pontusab
  • 光标与风浪冲浪社区,查找规则和MCP

  • av
  • 毫不费力地使用一个命令运行LLM后端,API,前端和服务。

  • rahulc0dy
  • 测试您的MCP服务器。

  • jae-jae
  • MCP服务器使用剧作《无头浏览器》获取网页内容。

  • ravitemer
  • 一个功能强大的Neovim插件,用于管理MCP(模型上下文协议)服务器

  • patruff
  • Ollama和MCP服务器之间的桥梁,使本地LLMS可以使用模型上下文协议工具

  • HiveNexus
  • 一个适用于中小型团队的AI聊天机器人,支持DeepSeek,Open AI,Claude和Gemini等车型。 专为中小团队设计的ai聊天应用,支持deepSeek,打开ai,claude,双子座等模型。

    Reviews

    5 (1)
    Avatar
    user_B0S4nvkA
    2025-04-17

    I've been using the perplexity-mcp-server by cyanheads for a while now, and it has significantly improved my workflow. The setup was straightforward, and its capabilities in managing multiple server connections effortlessly are impressive. Highly recommended for anyone looking to streamline their server interactions!