MCP Perplexity Server

MCP Perplexity Server

Provides AI-powered search, research, and reasoning capabilities through integration with Perplexity.ai, offering three specialized tools: general conversational AI, deep research with citations, and advanced reasoning.

Category
访问服务器

README

MCP Perplexity Server

MCP server for Perplexity.ai that provides AI-powered search, research, and reasoning capabilities.

🚀 Features

  • Perplexity AI Integration: Three specialized tools for different use cases
    • perplexity_ask: General conversational AI using sonar-pro model
    • perplexity_research: Deep research with citations using sonar-deep-research model
    • perplexity_reason: Advanced reasoning using sonar-reasoning-pro model
  • TypeScript: Full type safety with modern TypeScript patterns
  • HTTP Transport: RESTful API with Express.js server
  • Session Management: Stateful connections with proper session handling
  • Configuration Management: Environment-based configuration with validation
  • Error Handling: Comprehensive error handling and logging
  • Health Checks: Built-in health monitoring endpoints
  • Docker Support: Production-ready containerization
  • Development Tools: ESLint, Prettier, and testing setup
  • Production Ready: Optimized for scalability and security

📋 Prerequisites

  • Node.js 20+
  • npm or yarn
  • Docker (optional, for containerization)

🛠️ Quick Start

Option 1: Use the Project Generator (Recommended)

# Clone the template
git clone <your-repo-url>
cd mcp-perplexity


# Create a new project using the generator
./create-mcp-project your-project-name --description "Your project description" --author "Your Name"

# Or use the Node.js script directly
node setup-new-project.js your-project-name --description "Your project description" --author "Your Name"

Generator Options:

  • --description <desc>: Project description
  • --author <name>: Author name
  • --target-dir <dir>: Target directory (default: mcp-<project-name>)
  • --install-deps: Install npm dependencies automatically
  • --no-git: Skip git repository initialization

Option 2: Manual Setup

# Clone the template
git clone <your-repo-url>
cd mcp-template

# Install dependencies
npm install

# Copy environment configuration
cp .env.example .env  # Create this file with your settings

2. Environment Configuration

Create a .env file in the root directory:

# Server Configuration
PORT=3000
LOG_LEVEL=info

# Perplexity API Configuration
PERPLEXITY_API_KEY=your_perplexity_api_key_here

3. Development

# Start development server with hot reload
npm run dev

# Build for production
npm run build

# Start production server
npm start

# Run tests
npm test

# Lint and format code
npm run lint
npm run lint:fix

🏗️ Project Structure

mcp-perplexity/
├── src/
│   ├── config/           # Configuration management
│   │   └── index.ts      # Main config file
│   ├── services/         # Service layer
│   │   └── perplexity.ts # Perplexity API service
│   ├── utils/            # Utility functions
│   └── index.ts          # Main server application
├── create-mcp-project    # Bash script for project generation
├── setup-new-project.js  # Node.js project generator
├── Dockerfile            # Docker configuration
├── package.json          # Dependencies and scripts
├── tsconfig.json         # TypeScript configuration
└── README.md            # This file

🔧 Project Generator

This template includes powerful project generation tools to quickly create new MCP servers:

Features:

  • Automatic Name Conversion: Converts kebab-case names to all required formats (camelCase, PascalCase, etc.)
  • File Templating: Updates all files with the new project name and details
  • Git Integration: Optionally initializes a new git repository
  • Dependency Management: Can automatically install npm dependencies
  • Smart Copy Logic: Excludes development files and prevents infinite recursion

Usage Examples:

# Basic usage
./create-mcp-project weather-service

# With full options
./create-mcp-project task-manager \
  --description "AI-powered task management MCP server" \
  --author "Your Name" \
  --install-deps

# Custom target directory
./create-mcp-project file-processor --target-dir ./my-custom-server

# Skip git initialization
./create-mcp-project data-analyzer --no-git

🔧 Architecture

Core Components

  1. McpServerApp: Main application class that orchestrates the MCP server
  2. Configuration: Environment-based configuration with type safety
  3. Session Management: HTTP-based stateful sessions with cleanup
  4. Transport Layer: StreamableHTTPServerTransport for MCP communication
  5. Error Handling: Comprehensive error handling with proper HTTP responses

HTTP Endpoints

  • GET /health - Health check endpoint
  • POST /mcp - Main MCP communication endpoint
  • GET /mcp - Server-to-client notifications via SSE
  • DELETE /mcp - Session termination

🛠️ Customization Guide

Using Perplexity Tools

The server provides three Perplexity AI tools:

1. perplexity_ask

General conversational AI using the sonar-pro model.

{
  "name": "perplexity_ask",
  "arguments": {
    "messages": [
      {
        "role": "user",
        "content": "What are the latest developments in AI?"
      }
    ]
  }
}

2. perplexity_research

Deep research with citations using the sonar-deep-research model.

{
  "name": "perplexity_research",
  "arguments": {
    "messages": [
      {
        "role": "user",
        "content": "Research the current state of quantum computing and its applications"
      }
    ]
  }
}

3. perplexity_reason

Advanced reasoning using the sonar-reasoning-pro model.

{
  "name": "perplexity_reason",
  "arguments": {
    "messages": [
      {
        "role": "user",
        "content": "Analyze the pros and cons of different renewable energy sources"
      }
    ]
  }
}

Adding New Tools

To add a new MCP tool, modify the createServer() method in src/index.ts:

// Register your custom tool
server.tool(
  'your-tool-name',
  'Description of your tool',
  {
    // Define input schema using Zod
    parameter1: z.string().describe('Parameter description'),
    parameter2: z.number().optional().describe('Optional parameter'),
  },
  async ({ parameter1, parameter2 }) => {
    try {
      // Your tool implementation here
      const result = await yourCustomLogic(parameter1, parameter2);

      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          } as TextContent,
        ],
      };
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : String(error);
      throw new Error(`Error in your-tool-name: ${errorMessage}`);
    }
  }
);

Configuration Management

Add new configuration options in src/config/index.ts:

interface Config {
  logging: LoggingConfig;
  server: ServerConfig;
  // Add your custom config sections
  database: {
    url: string;
    timeout: number;
  };
  external: {
    apiKey: string;
    baseUrl: string;
  };
}

const config: Config = {
  // ... existing config
  database: {
    url: process.env.DATABASE_URL || 'sqlite://memory',
    timeout: parseInt(process.env.DB_TIMEOUT || '5000', 10),
  },
  external: {
    apiKey: process.env.EXTERNAL_API_KEY || '',
    baseUrl: process.env.EXTERNAL_BASE_URL || 'https://api.example.com',
  },
};

Adding Middleware

Add Express middleware in the run() method:

async run() {
  const app = express();
  app.use(express.json());

  // Add your custom middleware
  app.use(cors()); // CORS support
  app.use(helmet()); // Security headers
  app.use(morgan('combined')); // Request logging

  // ... rest of the setup
}

🐳 Docker Deployment

Build and Run

# Build Docker image
docker build -t mcp-perplexity-server .

# Run container
docker run -p 3000:3000 --env-file .env mcp-perplexity-server

Docker Compose (Recommended)

Create a docker-compose.yml:

version: '3.8'
services:
  mcp-server:
    build: .
    ports:
      - '3000:3000'
    environment:
      - NODE_ENV=production
      - PORT=3000
      - LOG_LEVEL=info
    restart: unless-stopped
    healthcheck:
      test: ['CMD', 'curl', '-f', 'http://localhost:3000/health']
      interval: 30s
      timeout: 10s
      retries: 3

Run with:

docker-compose up -d

🔒 Security Best Practices

This template implements several security measures:

  • Input Validation: Zod schema validation for all tool parameters
  • Error Handling: Safe error responses without information leakage
  • Session Management: Proper session cleanup and validation
  • HTTP Security: Ready for security headers and CORS configuration
  • Environment Variables: Secure configuration management

Recommended Additional Security

// Add security middleware
import helmet from 'helmet';
import cors from 'cors';
import rateLimit from 'express-rate-limit';

app.use(helmet());
app.use(
  cors({
    origin: process.env.ALLOWED_ORIGINS?.split(',') || false,
  })
);

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Limit each IP to 100 requests per windowMs
});
app.use('/mcp', limiter);

📊 Monitoring and Logging

The template includes basic logging setup. For production, consider adding:

  • Structured Logging: Winston with JSON format
  • Metrics Collection: Prometheus metrics
  • Health Checks: Comprehensive health endpoints
  • APM Integration: Application Performance Monitoring

🧪 Testing

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

Writing Tests

Create test files in src/**/*.test.ts:

import { describe, test, expect } from '@jest/globals';
// Your test imports

describe('YourComponent', () => {
  test('should handle valid input', async () => {
    // Test implementation
  });
});

🚀 Production Deployment

Environment Variables

NODE_ENV=production
PORT=3000
LOG_LEVEL=warn

# Add your production-specific variables
DATABASE_URL=postgresql://...
REDIS_URL=redis://...
API_KEYS=...

Performance Optimization

  • Enable gzip compression
  • Implement proper caching headers
  • Use connection pooling for databases
  • Monitor memory usage and implement limits
  • Set up log rotation

Scaling Considerations

  • Load balancing across multiple instances
  • Database connection pooling
  • Session store externalization (Redis)
  • Horizontal pod autoscaling in Kubernetes

📚 References

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Run the test suite
  6. Submit a pull request

📝 License

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

🆘 Support

For questions and support:

  • Check the MCP Documentation
  • Review existing issues
  • Create a new issue with detailed information

Happy coding! 🎉

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选