MCP server for DrTrips research using Perplexity AI API
npm install drtrips-research-mcp

A professional Model Context Protocol (MCP) server for research capabilities using Perplexity AI via OpenRouter API. Provides intelligent research with automatic citation extraction, customizable system prompts, and dual response formats (Markdown/JSON).
DrTrips Research MCP enables LLMs to perform comprehensive web research through Perplexity AI models. It offers:
- Up-to-date Information: Access current web information through Perplexity's search capabilities
- Automatic Citations: Every response includes source URLs for verification
- Customizable Behavior: Control research focus with custom system prompts
- Dual Output Formats: Choose between human-readable Markdown or machine-readable JSON
- Professional Error Handling: Actionable error messages guide users to solutions
- Token Tracking: Monitor API usage with detailed token consumption metrics
- Response Limits: Automatic truncation at 25,000 characters for optimal context usage
---
Markdown Format (Human-readable, default):
``markdownResearch Content Here...
š Citations:
[1] https://source1.com
[2] https://source2.com
---
š Query: Your question here
š¤ Model: perplexity/sonar
ā
Finish Reason: stop
`
JSON Format (Machine-readable):
`json`
{
"answer": "Research content here...",
"citations": ["https://source1.com", "https://source2.com"],
"model": "perplexity/sonar",
"finish_reason": "stop",
"usage": {
"input_tokens": 40,
"output_tokens": 521,
"total_tokens": 561
},
"total_sources": 13
}
---
- Node.js 18 or higher
- OpenRouter API key (get from OpenRouter)
`bash`
npm install drtrips-research-mcp
`bash`
git clone https://github.com/drtrips/research-mcp.git
cd drtrips-research-mcp
npm install
npm run build
---
Create a .env file in the project root:
`bashRequired: Your OpenRouter API key
OPENROUTER_API_KEY=sk-or-v1-your-api-key-here
$3
Choose from these Perplexity models on OpenRouter:
| Model | Description | Best For |
|-------|-------------|----------|
|
perplexity/sonar | Balanced quality and speed | General research (default) |
| perplexity/sonar-pro | Higher quality responses | Complex topics requiring depth |
| perplexity/sonar-reasoning | Extended reasoning | Multi-step analysis |See all models at OpenRouter Models
---
Usage
$3
Add to your Claude Desktop configuration file:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.jsonLinux:
~/.config/Claude/claude_desktop_config.json`json
{
"mcpServers": {
"drtrips-research": {
"command": "npx",
"args": ["drtrips-research-mcp"],
"env": {
"OPENROUTER_API_KEY": "sk-or-v1-your-api-key-here",
"MODEL_USE": "perplexity/sonar"
}
}
}
}
`Or with local installation:
`json
{
"mcpServers": {
"drtrips-research": {
"command": "node",
"args": ["/absolute/path/to/drtrips-research-mcp/dist/index.js"],
"env": {
"OPENROUTER_API_KEY": "sk-or-v1-your-api-key-here",
"MODEL_USE": "perplexity/sonar"
}
}
}
}
`After configuration, restart Claude Desktop to activate the server.
$3
For testing and debugging:
`bash
npx @modelcontextprotocol/inspector node dist/index.js
`---
Tool:
drtrips_researchPerform research queries using Perplexity AI with customizable system prompts and response formats.
$3
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
|
query | string | ā
Yes | - | Research question (2-500 characters) |
| systemprompt | string | ā No | Default assistant | Custom system prompt (max 2000 chars) |
| response_format | string | ā No | "markdown" | Output format: "markdown" or "json" |$3
#### Example 1: Basic Query (Markdown)
`json
{
"query": "What are the latest developments in quantum computing?"
}
`Response:
`markdown
Quantum computing has seen significant breakthroughs in 2024...š Citations:
[1] https://example.com/quantum-news
[2] https://example.com/research-paper
---
š Query: What are the latest developments in quantum computing?
š¤ Model: perplexity/sonar
ā
Finish Reason: stop
`#### Example 2: Travel Research with Custom Prompt
`json
{
"query": "Best travel destinations in Southeast Asia for families",
"systemprompt": "You are a travel expert specializing in Southeast Asia. Provide detailed recommendations with practical tips, budget considerations, and cultural insights."
}
`Response includes:
- Family-friendly destinations
- Budget breakdowns
- Cultural tips
- Practical travel advice
- Source citations
#### Example 3: Technical Research in JSON Format
`json
{
"query": "Current trends in artificial intelligence regulation",
"systemprompt": "You are a technical researcher. Focus on recent academic papers and technical specifications.",
"response_format": "json"
}
`Response:
`json
{
"answer": "AI regulation has evolved significantly in 2024...",
"citations": [
"https://example.com/ai-regulation-2024",
"https://example.com/policy-paper"
],
"model": "perplexity/sonar",
"finish_reason": "stop",
"usage": {
"input_tokens": 45,
"output_tokens": 623,
"total_tokens": 668
},
"total_sources": 8
}
`#### Example 4: Business Analysis
`json
{
"query": "Electric vehicle market analysis 2024",
"systemprompt": "You are a business analyst. Emphasize market data, financial implications, and competitive analysis.",
"response_format": "markdown"
}
`---
Response Structure
$3
The
content[0].text field contains the formatted research response:- Markdown format: Research content + citations section + metadata footer
- JSON format: Stringified JSON object with structured data
$3
Always included regardless of
response_format:`typescript
{
query: string; // Original query
systemprompt: string; // System prompt used (or "default")
timestamp: string; // ISO 8601 timestamp
model: string; // Model identifier (e.g., "perplexity/sonar")
finish_reason: string; // Completion status (e.g., "stop")
usage: {
input_tokens: number; // Tokens in request
output_tokens: number; // Tokens in response
total_tokens: number; // Total tokens consumed
};
citations: string[]; // Array of source URLs
total_sources: number; // Count of citation sources
}
`---
Error Handling
The server provides actionable error messages for common issues:
$3
`
ā Error: Rate limit exceededā ļø Please wait a few seconds before making another request.
The API has usage limits to ensure fair access.
`$3
`
ā Error: Authentication failedš Please check your OPENROUTER_API_KEY environment variable is set correctly.
Get your API key from https://openrouter.ai/keys
`$3
`
ā Error: Request timed outā±ļø Try with a simpler, more focused query or try again later.
Complex queries may take longer to process.
`$3
`
ā Error: Validation ErrorQuery must be at least 2 characters
Query must not exceed 500 characters
`$3
`
ā Error: Network connection errorš Please check your internet connection and verify that
https://openrouter.ai is accessible.
`---
Performance & Limits
$3
- Query: 2-500 characters
- System Prompt: Up to 2,000 characters
- Response: Limited to 25,000 characters (automatically truncated with guidance)
$3
- Average: 5-15 seconds depending on query complexity
- Timeout: 30 seconds (configurable in code)
$3
Monitor token consumption in the response metadata:
-
input_tokens: Your query and system prompt
- output_tokens: Generated research content
- total_tokens: Combined usage for billingPricing: See OpenRouter Pricing for current rates.
---
Security Considerations
$3
- ā
Store API keys in environment variables, never in code
- ā
Use
.env files excluded from version control (.gitignore)
- ā
Validate API key on server startup
- ā
Clear error messages when authentication fails$3
- ā
Zod schema validation for all inputs
- ā
String length constraints (query: 2-500, systemprompt: ā¤2000)
- ā
Strict mode prevents extra fields
- ā
Enum validation for
response_format$3
- ā
Error messages are user-friendly, not revealing internal details
- ā
Server-side logging for debugging (stderr, not stdout)
- ā
Actionable guidance in error messages
---
Development
$3
`
drtrips-research-mcp/
āāā src/
ā āāā index.ts # Main entry point
ā āāā server.ts # MCP server setup & tool registration
ā āāā config/
ā ā āāā settings.ts # Environment configuration
ā āāā models/
ā ā āāā research-models.ts # Zod schemas & TypeScript types
ā āāā services/
ā āāā perplexity-client.ts # Perplexity API integration
āāā dist/ # Compiled JavaScript
āāā evaluations/
ā āāā research_eval.xml # Evaluation test cases
āāā package.json
āāā tsconfig.json
āāā README.md
`$3
`bash
Install dependencies
npm installBuild TypeScript
npm run buildDevelopment with auto-reload
npm run devRun built server
npm start
`$3
`bash
Compile TypeScript
npm run buildTest with MCP Inspector
npx @modelcontextprotocol/inspector node dist/index.jsVerify JavaScript syntax
node -c dist/index.js
`---
Tool Annotations
The
drtrips_research tool includes MCP annotations for client guidance:`typescript
{
readOnlyHint: true, // Does not modify environment
destructiveHint: false, // Non-destructive operation
idempotentHint: true, // Safe to repeat with same args
openWorldHint: true // Interacts with external API
}
`Note: These are hints, not security guarantees. Clients should not make security-critical decisions based solely on annotations.
---
Use Cases
$3
- Current Events: "Latest developments in AI regulation 2024"
- Research: "Quantum computing breakthroughs"
- Travel Planning: "Best destinations in Southeast Asia" (with travel expert prompt)
- Market Analysis: "Electric vehicle market trends" (with business analyst prompt)
- Technical Research: "Machine learning frameworks comparison" (with technical researcher prompt)
- General Knowledge: Any topic requiring up-to-date, cited information
$3
- Calculations: Use computational tools instead
- Data Transformations: Use data processing tools
- Private Information: Tool only searches public web
- Historical Data: Limited to information available online
- Real-time Data: Responses may have slight delays
---
Troubleshooting
$3
1. Check Node.js version:
node --version (must be ā„18)
2. Verify API key is set in .env file
3. Check for build errors: npm run build
4. Review logs in stderr output$3
- Some queries may not return citations
- Try more specific queries
- Check if model supports citations (all Perplexity models do)
$3
- Query is too broad, try more specific search terms
- Use filters or constraints in your query
- Consider breaking into multiple smaller queries
$3
- Complex queries take longer (5-15 seconds average)
- Network latency may vary
- Consider using simpler queries or more specific terms
---
API Costs & Rate Limits
$3
Perplexity models on OpenRouter are billed per token:
- Check current pricing: OpenRouter Pricing
- Monitor usage in response metadata (
usage object)
- Set up billing alerts in OpenRouter dashboard$3
- Limits enforced by OpenRouter/Perplexity
- Server returns helpful messages on rate limit (429)
- Suggestion: Wait a few seconds between requests
---
Contributing
Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch (
git checkout -b feature/amazing-feature)
3. Commit changes (git commit -m 'Add amazing feature')
4. Push to branch (git push origin feature/amazing-feature`)- Follow TypeScript best practices
- Use Zod for input validation
- Add tests for new features
- Update documentation
- Follow existing code style
---
This project is licensed under the MIT License - see the LICENSE file for details.
---
- Issues: GitHub Issues
- Documentation: This README
- API Documentation: OpenRouter Docs
- MCP Specification: Model Context Protocol
---
#### Documentation
- ā
Professional README.md following MCP best practices
- ā
Comprehensive documentation with 19 sections
- ā
4 detailed usage examples
- ā
Complete error handling documentation
- ā
Security considerations section
- ā
Troubleshooting guide
- ā
Use cases guide (when to use/not use)
- ā
Contributing guidelines
- ā
Development setup documentation
#### Improvements
- Enhanced README with badges and professional structure
- Better organized documentation for users and developers
- Clear setup instructions for all platforms (macOS, Windows, Linux)
- Comprehensive API documentation with TypeScript types
---
#### Features
- ā
Dual response formats (Markdown/JSON)
- ā
Enhanced input validation with Zod
- ā
Character limit protection (25,000 chars)
- ā
Actionable error messages
- ā
Tool annotations (readOnly, destructive, idempotent, openWorld)
- ā
Comprehensive tool description
- ā
10 evaluation test cases
#### Improvements
- Enhanced error handling with specific guidance
- Better input validation constraints
- Automatic response truncation with user guidance
- Professional documentation
#### Technical
- TypeScript strict mode enabled
- Proper MCP best practices implementation
- Modular architecture with clear separation of concerns
---
- Perplexity AI for powerful search capabilities
- OpenRouter for unified API access
- Model Context Protocol for standardized LLM tool integration
- Anthropic for Claude and MCP ecosystem support
---
Made with ā¤ļø by DrTrips