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