Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
481 lines (449 loc) · 15 KB
/
Copy pathindex.ts
File metadata and controls
481 lines (449 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
Tool,
} from "@modelcontextprotocol/sdk/types.js";
/**
* Definition of the Perplexity Ask Tool.
* This tool accepts an array of messages and returns a chat completion response
* from the Perplexity API, with citations appended to the message if provided.
*/
const PERPLEXITY_ASK_TOOL: Tool = {
name: "perplexity_ask",
description:
"Engages in a conversation using the Sonar API. " +
"Accepts an array of messages (each with a role and content) " +
"and returns a ask completion response from the Perplexity model.",
inputSchema: {
type: "object",
properties: {
messages: {
type: "array",
items: {
type: "object",
properties: {
role: {
type: "string",
description: "Role of the message (e.g., system, user, assistant)",
},
content: {
type: "string",
description: "The content of the message",
},
},
required: ["role", "content"],
},
description: "Array of conversation messages",
},
},
required: ["messages"],
},
};
/**
* Definition of the Perplexity Research Tool.
* This tool performs deep research queries using the Perplexity API.
*/
const PERPLEXITY_RESEARCH_TOOL: Tool = {
name: "perplexity_research",
description:
"Performs deep research using the Perplexity API. " +
"Accepts an array of messages (each with a role and content) " +
"and returns a comprehensive research response with citations.",
inputSchema: {
type: "object",
properties: {
messages: {
type: "array",
items: {
type: "object",
properties: {
role: {
type: "string",
description: "Role of the message (e.g., system, user, assistant)",
},
content: {
type: "string",
description: "The content of the message",
},
},
required: ["role", "content"],
},
description: "Array of conversation messages",
},
},
required: ["messages"],
},
};
/**
* Definition of the Perplexity Reason Tool.
* This tool performs reasoning queries using the Perplexity API.
*/
const PERPLEXITY_REASON_TOOL: Tool = {
name: "perplexity_reason",
description:
"Performs reasoning tasks using the Perplexity API. " +
"Accepts an array of messages (each with a role and content) " +
"and returns a well-reasoned response using the sonar-reasoning-pro model.",
inputSchema: {
type: "object",
properties: {
messages: {
type: "array",
items: {
type: "object",
properties: {
role: {
type: "string",
description: "Role of the message (e.g., system, user, assistant)",
},
content: {
type: "string",
description: "The content of the message",
},
},
required: ["role", "content"],
},
description: "Array of conversation messages",
},
},
required: ["messages"],
},
};
/**
* Definition of the Perplexity Search Tool.
* This tool performs web search using the Perplexity Search API.
*/
const PERPLEXITY_SEARCH_TOOL: Tool = {
name: "perplexity_search",
description:
"Performs web search using the Perplexity Search API. " +
"Returns ranked search results with titles, URLs, snippets, and metadata.",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description: "Search query string",
},
max_results: {
type: "number",
description: "Maximum number of results to return (1-20, default: 10)",
minimum: 1,
maximum: 20,
},
max_tokens_per_page: {
type: "number",
description: "Maximum tokens to extract per webpage (default: 1024)",
minimum: 256,
maximum: 2048,
},
country: {
type: "string",
description: "ISO 3166-1 alpha-2 country code for regional results (e.g., 'US', 'GB')",
},
},
required: ["query"],
},
};
// Retrieve the Perplexity API key from environment variables
const PERPLEXITY_API_KEY = process.env.PERPLEXITY_API_KEY;
if (!PERPLEXITY_API_KEY) {
console.error("Error: PERPLEXITY_API_KEY environment variable is required");
process.exit(1);
}
// Configure timeout for API requests (default: 5 minutes)
// Can be overridden via PERPLEXITY_TIMEOUT_MS environment variable
const TIMEOUT_MS = parseInt(process.env.PERPLEXITY_TIMEOUT_MS || "300000", 10);
/**
* Performs a chat completion by sending a request to the Perplexity API.
* Appends citations to the returned message content if they exist.
*
* @param {Array<{ role: string; content: string }>} messages - An array of message objects.
* @param {string} model - The model to use for the completion.
* @returns {Promise<string>} The chat completion result with appended citations.
* @throws Will throw an error if the API request fails.
*/
async function performChatCompletion(
messages: Array<{ role: string; content: string }>,
model: string = "sonar-pro"
): Promise<string> {
// Construct the API endpoint URL and request body
const url = new URL("https://api.perplexity.ai/chat/completions");
const body = {
model: model, // Model identifier passed as parameter
messages: messages,
// Additional parameters can be added here if required (e.g., max_tokens, temperature, etc.)
// See the Sonar API documentation for more details:
// https://docs.perplexity.ai/api-reference/chat-completions
};
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);
let response;
try {
response = await fetch(url.toString(), {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${PERPLEXITY_API_KEY}`,
},
body: JSON.stringify(body),
signal: controller.signal,
});
clearTimeout(timeoutId);
} catch (error) {
clearTimeout(timeoutId);
if (error instanceof Error && error.name === "AbortError") {
throw new Error(`Request timeout: Perplexity API did not respond within ${TIMEOUT_MS}ms. Consider increasing PERPLEXITY_TIMEOUT_MS.`);
}
throw new Error(`Network error while calling Perplexity API: ${error}`);
}
// Check for non-successful HTTP status
if (!response.ok) {
let errorText;
try {
errorText = await response.text();
} catch (parseError) {
errorText = "Unable to parse error response";
}
throw new Error(
`Perplexity API error: ${response.status} ${response.statusText}\n${errorText}`
);
}
// Attempt to parse the JSON response from the API
let data;
try {
data = await response.json();
} catch (jsonError) {
throw new Error(`Failed to parse JSON response from Perplexity API: ${jsonError}`);
}
// Directly retrieve the main message content from the response
let messageContent = data.choices[0].message.content;
// If citations are provided, append them to the message content
if (data.citations && Array.isArray(data.citations) && data.citations.length > 0) {
messageContent += "\n\nCitations:\n";
data.citations.forEach((citation: string, index: number) => {
messageContent += `[${index + 1}] ${citation}\n`;
});
}
return messageContent;
}
/**
* Formats search results from the Perplexity Search API into a readable string.
*
* @param {any} data - The search response data from the API.
* @returns {string} Formatted search results.
*/
function formatSearchResults(data: any): string {
if (!data.results || !Array.isArray(data.results)) {
return "No search results found.";
}
let formattedResults = `Found ${data.results.length} search results:\n\n`;
data.results.forEach((result: any, index: number) => {
formattedResults += `${index + 1}. **${result.title}**\n`;
formattedResults += ` URL: ${result.url}\n`;
if (result.snippet) {
formattedResults += ` ${result.snippet}\n`;
}
if (result.date) {
formattedResults += ` Date: ${result.date}\n`;
}
formattedResults += `\n`;
});
return formattedResults;
}
/**
* Performs a web search using the Perplexity Search API.
*
* @param {string} query - The search query string.
* @param {number} maxResults - Maximum number of results to return (1-20).
* @param {number} maxTokensPerPage - Maximum tokens to extract per webpage.
* @param {string} country - Optional ISO country code for regional results.
* @returns {Promise<string>} The formatted search results.
* @throws Will throw an error if the API request fails.
*/
async function performSearch(
query: string,
maxResults: number = 10,
maxTokensPerPage: number = 1024,
country?: string
): Promise<string> {
const url = new URL("https://api.perplexity.ai/search");
const body: any = {
query: query,
max_results: maxResults,
max_tokens_per_page: maxTokensPerPage,
};
if (country) {
body.country = country;
}
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);
let response;
try {
response = await fetch(url.toString(), {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${PERPLEXITY_API_KEY}`,
},
body: JSON.stringify(body),
signal: controller.signal,
});
clearTimeout(timeoutId);
} catch (error) {
clearTimeout(timeoutId);
if (error instanceof Error && error.name === "AbortError") {
throw new Error(`Request timeout: Perplexity Search API did not respond within ${TIMEOUT_MS}ms. Consider increasing PERPLEXITY_TIMEOUT_MS.`);
}
throw new Error(`Network error while calling Perplexity Search API: ${error}`);
}
// Check for non-successful HTTP status
if (!response.ok) {
let errorText;
try {
errorText = await response.text();
} catch (parseError) {
errorText = "Unable to parse error response";
}
throw new Error(
`Perplexity Search API error: ${response.status} ${response.statusText}\n${errorText}`
);
}
let data;
try {
data = await response.json();
} catch (jsonError) {
throw new Error(`Failed to parse JSON response from Perplexity Search API: ${jsonError}`);
}
return formatSearchResults(data);
}
// Initialize the server with tool metadata and capabilities
const server = new Server(
{
name: "example-servers/perplexity-ask",
version: "0.1.0",
},
{
capabilities: {
tools: {},
},
}
);
/**
* Registers a handler for listing available tools.
* When the client requests a list of tools, this handler returns all available Perplexity tools.
*/
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [PERPLEXITY_ASK_TOOL, PERPLEXITY_RESEARCH_TOOL, PERPLEXITY_REASON_TOOL, PERPLEXITY_SEARCH_TOOL],
}));
/**
* Registers a handler for calling a specific tool.
* Processes requests by validating input and invoking the appropriate tool.
*
* @param {object} request - The incoming tool call request.
* @returns {Promise<object>} The response containing the tool's result or an error.
*/
server.setRequestHandler(CallToolRequestSchema, async (request) => {
try {
const { name, arguments: args } = request.params;
if (!args) {
throw new Error("No arguments provided");
}
switch (name) {
case "perplexity_ask": {
if (!Array.isArray(args.messages)) {
throw new Error("Invalid arguments for perplexity_ask: 'messages' must be an array");
}
// Invoke the chat completion function with the provided messages
const messages = args.messages;
const result = await performChatCompletion(messages, "sonar-pro");
return {
content: [{ type: "text", text: result }],
isError: false,
};
}
case "perplexity_research": {
if (!Array.isArray(args.messages)) {
throw new Error("Invalid arguments for perplexity_research: 'messages' must be an array");
}
// Invoke the chat completion function with the provided messages using the deep research model
const messages = args.messages;
const result = await performChatCompletion(messages, "sonar-deep-research");
return {
content: [{ type: "text", text: result }],
isError: false,
};
}
case "perplexity_reason": {
if (!Array.isArray(args.messages)) {
throw new Error("Invalid arguments for perplexity_reason: 'messages' must be an array");
}
// Invoke the chat completion function with the provided messages using the reasoning model
const messages = args.messages;
const result = await performChatCompletion(messages, "sonar-reasoning-pro");
return {
content: [{ type: "text", text: result }],
isError: false,
};
}
case "perplexity_search": {
if (typeof args.query !== "string") {
throw new Error("Invalid arguments for perplexity_search: 'query' must be a string");
}
const { query, max_results, max_tokens_per_page, country } = args;
const maxResults = typeof max_results === "number" ? max_results : undefined;
const maxTokensPerPage = typeof max_tokens_per_page === "number" ? max_tokens_per_page : undefined;
const countryCode = typeof country === "string" ? country : undefined;
const result = await performSearch(
query,
maxResults,
maxTokensPerPage,
countryCode
);
return {
content: [{ type: "text", text: result }],
isError: false,
};
}
default:
// Respond with an error if an unknown tool is requested
return {
content: [{ type: "text", text: `Unknown tool: ${name}` }],
isError: true,
};
}
} catch (error) {
// Return error details in the response
return {
content: [
{
type: "text",
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
},
],
isError: true,
};
}
});
/**
* Initializes and runs the server using standard I/O for communication.
* Logs an error and exits if the server fails to start.
*/
async function runServer() {
try {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Perplexity MCP Server running on stdio with Ask, Research, Reason, and Search tools");
} catch (error) {
console.error("Fatal error running server:", error);
process.exit(1);
}
}
// Start the server and catch any startup errors
runServer().catch((error) => {
console.error("Fatal error running server:", error);
process.exit(1);
});