-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
393 lines (355 loc) · 11.1 KB
/
index.ts
File metadata and controls
393 lines (355 loc) · 11.1 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
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
InitializedNotificationSchema,
} from "@modelcontextprotocol/sdk/types.js";
import type { Tool } from "@modelcontextprotocol/sdk/types.js";
import { createServer } from "http";
import { randomUUID } from "crypto";
import dotenv from "dotenv";
// Load environment variables from .env file
dotenv.config();
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"],
},
};
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"],
},
};
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"],
},
};
// Check for API key
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);
}
async function performChatCompletion(
messages: Array<{ role: string; content: string }>,
model: string = "sonar-pro"
): Promise<string> {
const url = new URL("https://api.perplexity.ai/chat/completions");
const body = {
model: model,
messages: messages,
};
let response;
try {
response = await fetch(url.toString(), {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${PERPLEXITY_API_KEY}`,
},
body: JSON.stringify(body),
});
} catch (error) {
throw new Error(`Network error while calling Perplexity API: ${error}`);
}
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}`
);
}
let data;
try {
data = await response.json();
} catch (jsonError) {
throw new Error(`Failed to parse JSON response from Perplexity API: ${jsonError}`);
}
let messageContent = data.choices[0].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;
}
// Create a new server instance
function createServerInstance() {
const serverInstance = new Server(
{
name: "dedalus-labs/sonar",
version: "0.1.0",
},
{
capabilities: {
tools: {},
},
}
);
// Notification handlers
serverInstance.setNotificationHandler(InitializedNotificationSchema, async () => {
// Client has acknowledged initialization
console.log('Client initialized');
});
// Tool handlers
serverInstance.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [PERPLEXITY_ASK_TOOL, PERPLEXITY_RESEARCH_TOOL, PERPLEXITY_REASON_TOOL],
}));
serverInstance.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");
}
const result = await performChatCompletion(args.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");
}
const result = await performChatCompletion(args.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");
}
const result = await performChatCompletion(args.messages, "sonar-reasoning-pro");
return {
content: [{ type: "text", text: result }],
isError: false,
};
}
default:
return {
content: [{ type: "text", text: `Unknown tool: ${name}` }],
isError: true,
};
}
} catch (error) {
return {
content: [
{
type: "text",
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
},
],
isError: true,
};
}
});
return serverInstance;
}
// Parse command line arguments
function parseArgs() {
const args = process.argv.slice(2);
const options: { port?: number; stdio?: boolean } = {};
for (let i = 0; i < args.length; i++) {
if (args[i] === '--port' && i + 1 < args.length) {
options.port = parseInt(args[i + 1], 10);
i++;
} else if (args[i] === '--stdio') {
options.stdio = true;
}
}
return options;
}
// Session storage for streamable HTTP
const streamableSessions = new Map<string, {transport: any, server: any}>();
// SSE transport handler
async function handleSSE(req: any, res: any) {
const serverInstance = createServerInstance();
const transport = new SSEServerTransport('/sse', res);
try {
await serverInstance.connect(transport);
} catch (error) {
console.error('SSE connection error:', error);
}
}
// Streamable HTTP transport handler
async function handleStreamable(req: any, res: any) {
const sessionId = req.headers['mcp-session-id'] as string | undefined;
if (sessionId) {
// Use existing session
const session = streamableSessions.get(sessionId);
if (!session) {
res.statusCode = 404;
res.end('Session not found');
return;
}
return await session.transport.handleRequest(req, res);
}
// Create new session for initialization
if (req.method === 'POST') {
const serverInstance = createServerInstance();
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
onsessioninitialized: (sessionId) => {
streamableSessions.set(sessionId, { transport, server: serverInstance });
console.log('New session created:', sessionId);
}
});
transport.onclose = () => {
if (transport.sessionId) {
streamableSessions.delete(transport.sessionId);
console.log('Session closed:', transport.sessionId);
}
};
try {
await serverInstance.connect(transport);
await transport.handleRequest(req, res);
} catch (error) {
console.error('Streamable HTTP connection error:', error);
}
return;
}
res.statusCode = 400;
res.end('Invalid request');
}
// HTTP server setup
function startHttpServer(port: number) {
const httpServer = createServer();
httpServer.on('request', async (req, res) => {
const url = new URL(req.url!, `http://${req.headers.host}`);
if (url.pathname === '/sse') {
await handleSSE(req, res);
} else if (url.pathname === '/mcp') {
await handleStreamable(req, res);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
httpServer.listen(port, () => {
console.log(`Listening on http://localhost:${port}`);
console.log('Put this in your client config:');
console.log(JSON.stringify({
"mcpServers": {
"perplexity-ask": {
"url": `http://localhost:${port}/sse`
}
}
}, null, 2));
console.log('If your client supports streamable HTTP, you can use the /mcp endpoint instead.');
});
return httpServer;
}
// Main server function
async function runServer() {
const options = parseArgs();
if (options.stdio) {
// STDIO mode (only if --stdio flag is used)
const serverInstance = createServerInstance();
const transport = new StdioServerTransport();
await serverInstance.connect(transport);
console.error("Perplexity MCP Server running on stdio with Ask, Research, and Reason tools");
} else {
// HTTP mode (default) - use specified port or default to 8080
const port = options.port || 8080;
startHttpServer(port);
}
}
runServer().catch((error) => {
console.error("Fatal error running server:", error);
process.exit(1);
});