AI搜索研究服务器

MCP Perplexity Server是一个基于AI的搜索、研究和推理服务器,提供三种专用工具(通用对话AI、深度研究和高级推理),支持TypeScript、HTTP传输、会话管理和Docker部署。

  • by samwang0723
  • JavaScript
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 samwang0723/mcp-perplexity

使用说明

MCP困惑服务器

用于Perplexy.ai的MCP服务器,提供基于人工智能的搜索、研究和推理功能。

🚀 特性

  • 困惑AI集成:针对不同用例的三种专用工具
    • perplexity_ask:使用声纳专业模型的通用对话式人工智能
    • perplexity_research:使用声纳深度研究模型进行引用的深度研究
    • perplexity_reason:使用声纳推理专业模型进行高级推理
  • TypeScript:具有现代TypeScript模式的完全类型安全
  • HTTP传输:带有Express.js服务器的RESTful API
  • 会话管理:具有适当会话处理的有状态连接
  • 配置管理:基于环境的配置和验证
  • 错误处理:全面的错误处理和记录
  • 健康检查:内置健康监测端点
  • Docker支持:生产就绪的集装箱化
  • 开发工具:ESLint、Prettier和测试设置
  • 生产就绪:针对可扩展性和安全性进行了优化

📋 先决条件

  • Node.js 20+
  • npm或纱线
  • Docker(可选,用于容器化)

🛠️ 快速开始

选项1:使用项目生成器(推荐)

# 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"

发电机选项:

  • --description <desc>:项目描述
  • --author <name>:作者姓名
  • --target-dir <dir>:目标目录(默认:mcp-)
  • --install-deps:自动安装npm依赖项
  • --no-git:跳过git存储库初始化

选项2:手动设置

# 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.环境配置

创建一个 .env 根目录中的文件:

# Server Configuration
PORT=3000
LOG_LEVEL=info

# Perplexity API Configuration
PERPLEXITY_API_KEY=your_perplexity_api_key_here

3.发展

# 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

🏗️ 项目结构

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

🔧 项目生成器

此模板包括强大的项目生成工具,可快速创建新的MCP服务器:

特征:

  • 自动名称转换:将烤肉串案例名称转换为所有必需的格式(camelCase、PascalCase等)
  • 文件模板:使用新的项目名称和详细信息更新所有文件
  • Git集成:可选择初始化新的git存储库
  • 依赖管理:可以自动安装npm依赖项
  • 智能复制逻辑:排除开发文件并防止无限递归

使用示例:

# 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

🔧 建筑

核心组件

  1. McpServerApp:编排MCP服务器的主应用程序类
  2. 配置:基于环境的配置,具有类型安全
  3. 会话管理:具有清理功能的基于HTTP的有状态会话
  4. 传输层:用于MCP通信的StreamableHTTPServerTransport
  5. 错误处理:使用正确的HTTP响应进行全面的错误处理

HTTP端点

  • GET /health -健康检查端点
  • POST /mcp -主MCP通信端点
  • GET /mcp -通过SSE发送服务器到客户端的通知
  • DELETE /mcp -会话终止

🛠️ 定制指南

使用困惑工具

服务器提供了三种困惑AI工具:

1.困惑_提问

使用声纳专业模型的通用对话式人工智能。

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

2.困惑_探索

使用声纳深度研究模型进行引用的深入研究。

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

3.困惑_原因

使用声纳推理pro模型进行高级推理。

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

添加新工具

要添加新的MCP工具,请修改 createServer() 方法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}`);
    }
  }
);

配置管理

在中添加新的配置选项 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',
  },
};

添加中间件

在中添加Express中间件 run() 方法:

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部署

构建并运行

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

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

Docker Compose(推荐)

创建一个 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

运行方式:

docker-compose up -d

🔒 安全最佳实践

此模板实现了多种安全措施:

  • 输入验证:所有工具参数的Zod模式验证
  • 错误处理:无信息泄露的安全错误响应
  • 会话管理:适当的会话清理和验证
  • HTTP安全:已准备好进行安全标头和CORS配置
  • 环境变量:安全配置管理

建议的附加安全措施

// 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);

📊 监控和日志记录

该模板包括基本的日志记录设置。对于生产,考虑添加:

  • 结构化日志记录:Winston,JSON格式
  • 指标收集:普罗米修斯指标
  • 健康检查:综合健康终点
  • APM集成:应用程序性能监控

🧪 测试

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

写作测试

在中创建测试文件 src/**/*.test.ts:

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

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

🚀 生产部署

环境变量

NODE_ENV=production
PORT=3000
LOG_LEVEL=warn

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

性能优化

  • 启用gzip压缩
  • 实现正确的缓存标头
  • 对数据库使用连接池
  • 监控内存使用情况并实施限制
  • 设置日志轮换

缩放注意事项

  • 跨多个实例的负载平衡
  • 数据库连接池
  • 会话存储外部化(Redis)
  • Kubernetes中的水平pod自动缩放

📚 参考文献

🤝 贡献

  1. 复刻仓库
  2. 创建要素分支
  3. 进行更改
  4. 添加新功能的测试
  5. 运行测试套件
  6. 提交拉取请求

📝 许可证

此项目根据MIT许可证获得许可-有关详细信息,请参阅许可证文件。

🆘 支持

如有疑问和支持:

  • 检查 MCP文件
  • 审查现有问题
  • 创建包含详细信息的新问题

编码愉快! 🎉