@perplexity-ai/mcp-server 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/README.md +62 -28
- package/dist/http.js +81 -0
- package/dist/index.js +12 -515
- package/dist/server.js +386 -0
- package/package.json +17 -4
- package/dist/index.test.js +0 -566
- package/dist/vitest.config.js +0 -19
package/dist/index.js
CHANGED
|
@@ -1,533 +1,30 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
12
2
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Definition of the Perplexity Ask Tool.
|
|
17
|
-
* This tool accepts an array of messages and returns a chat completion response
|
|
18
|
-
* from the Perplexity API, with citations appended to the message if provided.
|
|
19
|
-
*/
|
|
20
|
-
const PERPLEXITY_ASK_TOOL = {
|
|
21
|
-
name: "perplexity_ask",
|
|
22
|
-
description: "Engages in a conversation using the Sonar API. " +
|
|
23
|
-
"Accepts an array of messages (each with a role and content) " +
|
|
24
|
-
"and returns a ask completion response from the Perplexity model.",
|
|
25
|
-
inputSchema: {
|
|
26
|
-
type: "object",
|
|
27
|
-
properties: {
|
|
28
|
-
messages: {
|
|
29
|
-
type: "array",
|
|
30
|
-
items: {
|
|
31
|
-
type: "object",
|
|
32
|
-
properties: {
|
|
33
|
-
role: {
|
|
34
|
-
type: "string",
|
|
35
|
-
description: "Role of the message (e.g., system, user, assistant)",
|
|
36
|
-
},
|
|
37
|
-
content: {
|
|
38
|
-
type: "string",
|
|
39
|
-
description: "The content of the message",
|
|
40
|
-
},
|
|
41
|
-
},
|
|
42
|
-
required: ["role", "content"],
|
|
43
|
-
},
|
|
44
|
-
description: "Array of conversation messages",
|
|
45
|
-
},
|
|
46
|
-
},
|
|
47
|
-
required: ["messages"],
|
|
48
|
-
},
|
|
49
|
-
};
|
|
50
|
-
/**
|
|
51
|
-
* Definition of the Perplexity Research Tool.
|
|
52
|
-
* This tool performs deep research queries using the Perplexity API.
|
|
53
|
-
*/
|
|
54
|
-
const PERPLEXITY_RESEARCH_TOOL = {
|
|
55
|
-
name: "perplexity_research",
|
|
56
|
-
description: "Performs deep research using the Perplexity API. " +
|
|
57
|
-
"Accepts an array of messages (each with a role and content) " +
|
|
58
|
-
"and returns a comprehensive research response with citations.",
|
|
59
|
-
inputSchema: {
|
|
60
|
-
type: "object",
|
|
61
|
-
properties: {
|
|
62
|
-
messages: {
|
|
63
|
-
type: "array",
|
|
64
|
-
items: {
|
|
65
|
-
type: "object",
|
|
66
|
-
properties: {
|
|
67
|
-
role: {
|
|
68
|
-
type: "string",
|
|
69
|
-
description: "Role of the message (e.g., system, user, assistant)",
|
|
70
|
-
},
|
|
71
|
-
content: {
|
|
72
|
-
type: "string",
|
|
73
|
-
description: "The content of the message",
|
|
74
|
-
},
|
|
75
|
-
},
|
|
76
|
-
required: ["role", "content"],
|
|
77
|
-
},
|
|
78
|
-
description: "Array of conversation messages",
|
|
79
|
-
},
|
|
80
|
-
strip_thinking: {
|
|
81
|
-
type: "boolean",
|
|
82
|
-
description: "If true, removes <think>...</think> tags and their content from the response to save context tokens. Default is false.",
|
|
83
|
-
},
|
|
84
|
-
},
|
|
85
|
-
required: ["messages"],
|
|
86
|
-
},
|
|
87
|
-
};
|
|
88
|
-
/**
|
|
89
|
-
* Definition of the Perplexity Reason Tool.
|
|
90
|
-
* This tool performs reasoning queries using the Perplexity API.
|
|
91
|
-
*/
|
|
92
|
-
const PERPLEXITY_REASON_TOOL = {
|
|
93
|
-
name: "perplexity_reason",
|
|
94
|
-
description: "Performs reasoning tasks using the Perplexity API. " +
|
|
95
|
-
"Accepts an array of messages (each with a role and content) " +
|
|
96
|
-
"and returns a well-reasoned response using the sonar-reasoning-pro model.",
|
|
97
|
-
inputSchema: {
|
|
98
|
-
type: "object",
|
|
99
|
-
properties: {
|
|
100
|
-
messages: {
|
|
101
|
-
type: "array",
|
|
102
|
-
items: {
|
|
103
|
-
type: "object",
|
|
104
|
-
properties: {
|
|
105
|
-
role: {
|
|
106
|
-
type: "string",
|
|
107
|
-
description: "Role of the message (e.g., system, user, assistant)",
|
|
108
|
-
},
|
|
109
|
-
content: {
|
|
110
|
-
type: "string",
|
|
111
|
-
description: "The content of the message",
|
|
112
|
-
},
|
|
113
|
-
},
|
|
114
|
-
required: ["role", "content"],
|
|
115
|
-
},
|
|
116
|
-
description: "Array of conversation messages",
|
|
117
|
-
},
|
|
118
|
-
strip_thinking: {
|
|
119
|
-
type: "boolean",
|
|
120
|
-
description: "If true, removes <think>...</think> tags and their content from the response to save context tokens. Default is false.",
|
|
121
|
-
},
|
|
122
|
-
},
|
|
123
|
-
required: ["messages"],
|
|
124
|
-
},
|
|
125
|
-
};
|
|
126
|
-
/**
|
|
127
|
-
* Definition of the Perplexity Search Tool.
|
|
128
|
-
* This tool performs web search using the Perplexity Search API.
|
|
129
|
-
*/
|
|
130
|
-
const PERPLEXITY_SEARCH_TOOL = {
|
|
131
|
-
name: "perplexity_search",
|
|
132
|
-
description: "Performs web search using the Perplexity Search API. " +
|
|
133
|
-
"Returns ranked search results with titles, URLs, snippets, and metadata.",
|
|
134
|
-
inputSchema: {
|
|
135
|
-
type: "object",
|
|
136
|
-
properties: {
|
|
137
|
-
query: {
|
|
138
|
-
type: "string",
|
|
139
|
-
description: "Search query string",
|
|
140
|
-
},
|
|
141
|
-
max_results: {
|
|
142
|
-
type: "number",
|
|
143
|
-
description: "Maximum number of results to return (1-20, default: 10)",
|
|
144
|
-
minimum: 1,
|
|
145
|
-
maximum: 20,
|
|
146
|
-
},
|
|
147
|
-
max_tokens_per_page: {
|
|
148
|
-
type: "number",
|
|
149
|
-
description: "Maximum tokens to extract per webpage (default: 1024)",
|
|
150
|
-
minimum: 256,
|
|
151
|
-
maximum: 2048,
|
|
152
|
-
},
|
|
153
|
-
country: {
|
|
154
|
-
type: "string",
|
|
155
|
-
description: "ISO 3166-1 alpha-2 country code for regional results (e.g., 'US', 'GB')",
|
|
156
|
-
},
|
|
157
|
-
},
|
|
158
|
-
required: ["query"],
|
|
159
|
-
},
|
|
160
|
-
};
|
|
161
|
-
// Retrieve the Perplexity API key from environment variables
|
|
3
|
+
import { createPerplexityServer } from "./server.js";
|
|
4
|
+
// Check for required API key
|
|
162
5
|
const PERPLEXITY_API_KEY = process.env.PERPLEXITY_API_KEY;
|
|
163
6
|
if (!PERPLEXITY_API_KEY) {
|
|
164
7
|
console.error("Error: PERPLEXITY_API_KEY environment variable is required");
|
|
165
8
|
process.exit(1);
|
|
166
9
|
}
|
|
167
10
|
/**
|
|
168
|
-
*
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
* @returns {string | undefined} The proxy URL if configured, undefined otherwise
|
|
172
|
-
*/
|
|
173
|
-
function getProxyUrl() {
|
|
174
|
-
return process.env.PERPLEXITY_PROXY ||
|
|
175
|
-
process.env.HTTPS_PROXY ||
|
|
176
|
-
process.env.HTTP_PROXY ||
|
|
177
|
-
undefined;
|
|
178
|
-
}
|
|
179
|
-
/**
|
|
180
|
-
* Creates a proxy-aware fetch function.
|
|
181
|
-
* Uses undici with ProxyAgent when a proxy is configured, otherwise uses native fetch.
|
|
182
|
-
*
|
|
183
|
-
* @param {string} url - The URL to fetch
|
|
184
|
-
* @param {RequestInit} options - Fetch options
|
|
185
|
-
* @returns {Promise<Response>} The fetch response
|
|
186
|
-
*/
|
|
187
|
-
function proxyAwareFetch(url_1) {
|
|
188
|
-
return __awaiter(this, arguments, void 0, function* (url, options = {}) {
|
|
189
|
-
const proxyUrl = getProxyUrl();
|
|
190
|
-
if (proxyUrl) {
|
|
191
|
-
// Use undici with ProxyAgent when proxy is configured
|
|
192
|
-
const proxyAgent = new ProxyAgent(proxyUrl);
|
|
193
|
-
const response = yield undiciFetch(url, Object.assign(Object.assign({}, options), { dispatcher: proxyAgent }));
|
|
194
|
-
// Cast to native Response type for compatibility
|
|
195
|
-
return response;
|
|
196
|
-
}
|
|
197
|
-
else {
|
|
198
|
-
// Use native fetch when no proxy is configured
|
|
199
|
-
return fetch(url, options);
|
|
200
|
-
}
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* Validates an array of message objects for chat completion tools.
|
|
205
|
-
* Ensures each message has a valid role and content field.
|
|
206
|
-
*
|
|
207
|
-
* @param {any} messages - The messages to validate
|
|
208
|
-
* @param {string} toolName - The name of the tool calling this validation (for error messages)
|
|
209
|
-
* @throws {Error} If messages is not an array or if any message is invalid
|
|
210
|
-
*/
|
|
211
|
-
function validateMessages(messages, toolName) {
|
|
212
|
-
if (!Array.isArray(messages)) {
|
|
213
|
-
throw new Error(`Invalid arguments for ${toolName}: 'messages' must be an array`);
|
|
214
|
-
}
|
|
215
|
-
for (let i = 0; i < messages.length; i++) {
|
|
216
|
-
const msg = messages[i];
|
|
217
|
-
if (!msg || typeof msg !== 'object') {
|
|
218
|
-
throw new Error(`Invalid message at index ${i}: must be an object`);
|
|
219
|
-
}
|
|
220
|
-
if (!msg.role || typeof msg.role !== 'string') {
|
|
221
|
-
throw new Error(`Invalid message at index ${i}: 'role' must be a string`);
|
|
222
|
-
}
|
|
223
|
-
if (msg.content === undefined || msg.content === null || typeof msg.content !== 'string') {
|
|
224
|
-
throw new Error(`Invalid message at index ${i}: 'content' must be a string`);
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* Strips thinking tokens (content within <think>...</think> tags) from the response.
|
|
230
|
-
* This helps reduce context usage when the thinking process is not needed.
|
|
231
|
-
*
|
|
232
|
-
* @param {string} content - The content to process
|
|
233
|
-
* @returns {string} The content with thinking tokens removed
|
|
234
|
-
*/
|
|
235
|
-
function stripThinkingTokens(content) {
|
|
236
|
-
return content.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
|
|
237
|
-
}
|
|
238
|
-
/**
|
|
239
|
-
* Performs a chat completion by sending a request to the Perplexity API.
|
|
240
|
-
* Appends citations to the returned message content if they exist.
|
|
241
|
-
*
|
|
242
|
-
* @param {Array<{ role: string; content: string }>} messages - An array of message objects.
|
|
243
|
-
* @param {string} model - The model to use for the completion.
|
|
244
|
-
* @param {boolean} stripThinking - If true, removes <think>...</think> tags from the response.
|
|
245
|
-
* @returns {Promise<string>} The chat completion result with appended citations.
|
|
246
|
-
* @throws Will throw an error if the API request fails.
|
|
247
|
-
*/
|
|
248
|
-
export function performChatCompletion(messages_1) {
|
|
249
|
-
return __awaiter(this, arguments, void 0, function* (messages, model = "sonar-pro", stripThinking = false) {
|
|
250
|
-
// Read timeout fresh each time to respect env var changes
|
|
251
|
-
const TIMEOUT_MS = parseInt(process.env.PERPLEXITY_TIMEOUT_MS || "300000", 10);
|
|
252
|
-
// Construct the API endpoint URL and request body
|
|
253
|
-
const url = new URL("https://api.perplexity.ai/chat/completions");
|
|
254
|
-
const body = {
|
|
255
|
-
model: model, // Model identifier passed as parameter
|
|
256
|
-
messages: messages,
|
|
257
|
-
// Additional parameters can be added here if required (e.g., max_tokens, temperature, etc.)
|
|
258
|
-
// See the Sonar API documentation for more details:
|
|
259
|
-
// https://docs.perplexity.ai/api-reference/chat-completions
|
|
260
|
-
};
|
|
261
|
-
const controller = new AbortController();
|
|
262
|
-
const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
263
|
-
let response;
|
|
264
|
-
try {
|
|
265
|
-
response = yield proxyAwareFetch(url.toString(), {
|
|
266
|
-
method: "POST",
|
|
267
|
-
headers: {
|
|
268
|
-
"Content-Type": "application/json",
|
|
269
|
-
"Authorization": `Bearer ${PERPLEXITY_API_KEY}`,
|
|
270
|
-
},
|
|
271
|
-
body: JSON.stringify(body),
|
|
272
|
-
signal: controller.signal,
|
|
273
|
-
});
|
|
274
|
-
clearTimeout(timeoutId);
|
|
275
|
-
}
|
|
276
|
-
catch (error) {
|
|
277
|
-
clearTimeout(timeoutId);
|
|
278
|
-
if (error instanceof Error && error.name === "AbortError") {
|
|
279
|
-
throw new Error(`Request timeout: Perplexity API did not respond within ${TIMEOUT_MS}ms. Consider increasing PERPLEXITY_TIMEOUT_MS.`);
|
|
280
|
-
}
|
|
281
|
-
throw new Error(`Network error while calling Perplexity API: ${error}`);
|
|
282
|
-
}
|
|
283
|
-
// Check for non-successful HTTP status
|
|
284
|
-
if (!response.ok) {
|
|
285
|
-
let errorText;
|
|
286
|
-
try {
|
|
287
|
-
errorText = yield response.text();
|
|
288
|
-
}
|
|
289
|
-
catch (parseError) {
|
|
290
|
-
errorText = "Unable to parse error response";
|
|
291
|
-
}
|
|
292
|
-
throw new Error(`Perplexity API error: ${response.status} ${response.statusText}\n${errorText}`);
|
|
293
|
-
}
|
|
294
|
-
// Attempt to parse the JSON response from the API
|
|
295
|
-
let data;
|
|
296
|
-
try {
|
|
297
|
-
data = yield response.json();
|
|
298
|
-
}
|
|
299
|
-
catch (jsonError) {
|
|
300
|
-
throw new Error(`Failed to parse JSON response from Perplexity API: ${jsonError}`);
|
|
301
|
-
}
|
|
302
|
-
// Validate response structure
|
|
303
|
-
if (!data.choices || !Array.isArray(data.choices) || data.choices.length === 0) {
|
|
304
|
-
throw new Error("Invalid API response: missing or empty choices array");
|
|
305
|
-
}
|
|
306
|
-
const firstChoice = data.choices[0];
|
|
307
|
-
if (!firstChoice.message || typeof firstChoice.message.content !== 'string') {
|
|
308
|
-
throw new Error("Invalid API response: missing message content");
|
|
309
|
-
}
|
|
310
|
-
// Directly retrieve the main message content from the response
|
|
311
|
-
let messageContent = firstChoice.message.content;
|
|
312
|
-
// Strip thinking tokens if requested
|
|
313
|
-
if (stripThinking) {
|
|
314
|
-
messageContent = stripThinkingTokens(messageContent);
|
|
315
|
-
}
|
|
316
|
-
// If citations are provided, append them to the message content
|
|
317
|
-
if (data.citations && Array.isArray(data.citations) && data.citations.length > 0) {
|
|
318
|
-
messageContent += "\n\nCitations:\n";
|
|
319
|
-
data.citations.forEach((citation, index) => {
|
|
320
|
-
messageContent += `[${index + 1}] ${citation}\n`;
|
|
321
|
-
});
|
|
322
|
-
}
|
|
323
|
-
return messageContent;
|
|
324
|
-
});
|
|
325
|
-
}
|
|
326
|
-
/**
|
|
327
|
-
* Formats search results from the Perplexity Search API into a readable string.
|
|
328
|
-
*
|
|
329
|
-
* @param {any} data - The search response data from the API.
|
|
330
|
-
* @returns {string} Formatted search results.
|
|
331
|
-
*/
|
|
332
|
-
export function formatSearchResults(data) {
|
|
333
|
-
if (!data.results || !Array.isArray(data.results)) {
|
|
334
|
-
return "No search results found.";
|
|
335
|
-
}
|
|
336
|
-
let formattedResults = `Found ${data.results.length} search results:\n\n`;
|
|
337
|
-
data.results.forEach((result, index) => {
|
|
338
|
-
formattedResults += `${index + 1}. **${result.title}**\n`;
|
|
339
|
-
formattedResults += ` URL: ${result.url}\n`;
|
|
340
|
-
if (result.snippet) {
|
|
341
|
-
formattedResults += ` ${result.snippet}\n`;
|
|
342
|
-
}
|
|
343
|
-
if (result.date) {
|
|
344
|
-
formattedResults += ` Date: ${result.date}\n`;
|
|
345
|
-
}
|
|
346
|
-
formattedResults += `\n`;
|
|
347
|
-
});
|
|
348
|
-
return formattedResults;
|
|
349
|
-
}
|
|
350
|
-
/**
|
|
351
|
-
* Performs a web search using the Perplexity Search API.
|
|
352
|
-
*
|
|
353
|
-
* @param {string} query - The search query string.
|
|
354
|
-
* @param {number} maxResults - Maximum number of results to return (1-20).
|
|
355
|
-
* @param {number} maxTokensPerPage - Maximum tokens to extract per webpage.
|
|
356
|
-
* @param {string} country - Optional ISO country code for regional results.
|
|
357
|
-
* @returns {Promise<string>} The formatted search results.
|
|
358
|
-
* @throws Will throw an error if the API request fails.
|
|
359
|
-
*/
|
|
360
|
-
export function performSearch(query_1) {
|
|
361
|
-
return __awaiter(this, arguments, void 0, function* (query, maxResults = 10, maxTokensPerPage = 1024, country) {
|
|
362
|
-
// Read timeout fresh each time to respect env var changes
|
|
363
|
-
const TIMEOUT_MS = parseInt(process.env.PERPLEXITY_TIMEOUT_MS || "300000", 10);
|
|
364
|
-
const url = new URL("https://api.perplexity.ai/search");
|
|
365
|
-
const body = {
|
|
366
|
-
query: query,
|
|
367
|
-
max_results: maxResults,
|
|
368
|
-
max_tokens_per_page: maxTokensPerPage,
|
|
369
|
-
};
|
|
370
|
-
if (country) {
|
|
371
|
-
body.country = country;
|
|
372
|
-
}
|
|
373
|
-
const controller = new AbortController();
|
|
374
|
-
const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
375
|
-
let response;
|
|
376
|
-
try {
|
|
377
|
-
response = yield proxyAwareFetch(url.toString(), {
|
|
378
|
-
method: "POST",
|
|
379
|
-
headers: {
|
|
380
|
-
"Content-Type": "application/json",
|
|
381
|
-
"Authorization": `Bearer ${PERPLEXITY_API_KEY}`,
|
|
382
|
-
},
|
|
383
|
-
body: JSON.stringify(body),
|
|
384
|
-
signal: controller.signal,
|
|
385
|
-
});
|
|
386
|
-
clearTimeout(timeoutId);
|
|
387
|
-
}
|
|
388
|
-
catch (error) {
|
|
389
|
-
clearTimeout(timeoutId);
|
|
390
|
-
if (error instanceof Error && error.name === "AbortError") {
|
|
391
|
-
throw new Error(`Request timeout: Perplexity Search API did not respond within ${TIMEOUT_MS}ms. Consider increasing PERPLEXITY_TIMEOUT_MS.`);
|
|
392
|
-
}
|
|
393
|
-
throw new Error(`Network error while calling Perplexity Search API: ${error}`);
|
|
394
|
-
}
|
|
395
|
-
// Check for non-successful HTTP status
|
|
396
|
-
if (!response.ok) {
|
|
397
|
-
let errorText;
|
|
398
|
-
try {
|
|
399
|
-
errorText = yield response.text();
|
|
400
|
-
}
|
|
401
|
-
catch (parseError) {
|
|
402
|
-
errorText = "Unable to parse error response";
|
|
403
|
-
}
|
|
404
|
-
throw new Error(`Perplexity Search API error: ${response.status} ${response.statusText}\n${errorText}`);
|
|
405
|
-
}
|
|
406
|
-
let data;
|
|
407
|
-
try {
|
|
408
|
-
data = yield response.json();
|
|
409
|
-
}
|
|
410
|
-
catch (jsonError) {
|
|
411
|
-
throw new Error(`Failed to parse JSON response from Perplexity Search API: ${jsonError}`);
|
|
412
|
-
}
|
|
413
|
-
return formatSearchResults(data);
|
|
414
|
-
});
|
|
415
|
-
}
|
|
416
|
-
// Initialize the server with tool metadata and capabilities
|
|
417
|
-
const server = new Server({
|
|
418
|
-
name: "example-servers/perplexity-ask",
|
|
419
|
-
version: "0.1.0",
|
|
420
|
-
}, {
|
|
421
|
-
capabilities: {
|
|
422
|
-
tools: {},
|
|
423
|
-
},
|
|
424
|
-
});
|
|
425
|
-
/**
|
|
426
|
-
* Registers a handler for listing available tools.
|
|
427
|
-
* When the client requests a list of tools, this handler returns all available Perplexity tools.
|
|
428
|
-
*/
|
|
429
|
-
server.setRequestHandler(ListToolsRequestSchema, () => __awaiter(void 0, void 0, void 0, function* () {
|
|
430
|
-
return ({
|
|
431
|
-
tools: [PERPLEXITY_ASK_TOOL, PERPLEXITY_RESEARCH_TOOL, PERPLEXITY_REASON_TOOL, PERPLEXITY_SEARCH_TOOL],
|
|
432
|
-
});
|
|
433
|
-
}));
|
|
434
|
-
/**
|
|
435
|
-
* Registers a handler for calling a specific tool.
|
|
436
|
-
* Processes requests by validating input and invoking the appropriate tool.
|
|
437
|
-
*
|
|
438
|
-
* @param {object} request - The incoming tool call request.
|
|
439
|
-
* @returns {Promise<object>} The response containing the tool's result or an error.
|
|
11
|
+
* Initializes and runs the server using standard I/O for communication.
|
|
12
|
+
* Logs an error and exits if the server fails to start.
|
|
440
13
|
*/
|
|
441
|
-
|
|
14
|
+
async function main() {
|
|
442
15
|
try {
|
|
443
|
-
const
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
switch (name) {
|
|
448
|
-
case "perplexity_ask": {
|
|
449
|
-
validateMessages(args.messages, "perplexity_ask");
|
|
450
|
-
const messages = args.messages;
|
|
451
|
-
const result = yield performChatCompletion(messages, "sonar-pro");
|
|
452
|
-
return {
|
|
453
|
-
content: [{ type: "text", text: result }],
|
|
454
|
-
isError: false,
|
|
455
|
-
};
|
|
456
|
-
}
|
|
457
|
-
case "perplexity_research": {
|
|
458
|
-
validateMessages(args.messages, "perplexity_research");
|
|
459
|
-
const messages = args.messages;
|
|
460
|
-
const stripThinking = typeof args.strip_thinking === "boolean" ? args.strip_thinking : false;
|
|
461
|
-
const result = yield performChatCompletion(messages, "sonar-deep-research", stripThinking);
|
|
462
|
-
return {
|
|
463
|
-
content: [{ type: "text", text: result }],
|
|
464
|
-
isError: false,
|
|
465
|
-
};
|
|
466
|
-
}
|
|
467
|
-
case "perplexity_reason": {
|
|
468
|
-
validateMessages(args.messages, "perplexity_reason");
|
|
469
|
-
const messages = args.messages;
|
|
470
|
-
const stripThinking = typeof args.strip_thinking === "boolean" ? args.strip_thinking : false;
|
|
471
|
-
const result = yield performChatCompletion(messages, "sonar-reasoning-pro", stripThinking);
|
|
472
|
-
return {
|
|
473
|
-
content: [{ type: "text", text: result }],
|
|
474
|
-
isError: false,
|
|
475
|
-
};
|
|
476
|
-
}
|
|
477
|
-
case "perplexity_search": {
|
|
478
|
-
if (typeof args.query !== "string") {
|
|
479
|
-
throw new Error("Invalid arguments for perplexity_search: 'query' must be a string");
|
|
480
|
-
}
|
|
481
|
-
const { query, max_results, max_tokens_per_page, country } = args;
|
|
482
|
-
const maxResults = typeof max_results === "number" ? max_results : undefined;
|
|
483
|
-
const maxTokensPerPage = typeof max_tokens_per_page === "number" ? max_tokens_per_page : undefined;
|
|
484
|
-
const countryCode = typeof country === "string" ? country : undefined;
|
|
485
|
-
const result = yield performSearch(query, maxResults, maxTokensPerPage, countryCode);
|
|
486
|
-
return {
|
|
487
|
-
content: [{ type: "text", text: result }],
|
|
488
|
-
isError: false,
|
|
489
|
-
};
|
|
490
|
-
}
|
|
491
|
-
default:
|
|
492
|
-
// Respond with an error if an unknown tool is requested
|
|
493
|
-
return {
|
|
494
|
-
content: [{ type: "text", text: `Unknown tool: ${name}` }],
|
|
495
|
-
isError: true,
|
|
496
|
-
};
|
|
497
|
-
}
|
|
16
|
+
const server = createPerplexityServer();
|
|
17
|
+
const transport = new StdioServerTransport();
|
|
18
|
+
await server.connect(transport);
|
|
19
|
+
console.error("Perplexity MCP Server running on stdio with Ask, Research, Reason, and Search tools");
|
|
498
20
|
}
|
|
499
21
|
catch (error) {
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
content: [
|
|
503
|
-
{
|
|
504
|
-
type: "text",
|
|
505
|
-
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
|
|
506
|
-
},
|
|
507
|
-
],
|
|
508
|
-
isError: true,
|
|
509
|
-
};
|
|
22
|
+
console.error("Fatal error running server:", error);
|
|
23
|
+
process.exit(1);
|
|
510
24
|
}
|
|
511
|
-
}));
|
|
512
|
-
/**
|
|
513
|
-
* Initializes and runs the server using standard I/O for communication.
|
|
514
|
-
* Logs an error and exits if the server fails to start.
|
|
515
|
-
*/
|
|
516
|
-
function runServer() {
|
|
517
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
518
|
-
try {
|
|
519
|
-
const transport = new StdioServerTransport();
|
|
520
|
-
yield server.connect(transport);
|
|
521
|
-
console.error("Perplexity MCP Server running on stdio with Ask, Research, Reason, and Search tools");
|
|
522
|
-
}
|
|
523
|
-
catch (error) {
|
|
524
|
-
console.error("Fatal error running server:", error);
|
|
525
|
-
process.exit(1);
|
|
526
|
-
}
|
|
527
|
-
});
|
|
528
25
|
}
|
|
529
26
|
// Start the server and catch any startup errors
|
|
530
|
-
|
|
27
|
+
main().catch((error) => {
|
|
531
28
|
console.error("Fatal error running server:", error);
|
|
532
29
|
process.exit(1);
|
|
533
30
|
});
|