@perplexity-ai/mcp-server 0.14.0 → 1.1.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 +49 -0
- package/LICENSE +21 -201
- package/README.md +105 -157
- package/dist/http.d.ts +15 -0
- package/dist/http.js +190 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +23 -0
- package/dist/logger.d.ts +19 -0
- package/dist/logger.js +82 -0
- package/dist/server.d.ts +61 -0
- package/dist/server.js +613 -0
- package/dist/types.d.ts +93 -0
- package/dist/types.js +1 -0
- package/dist/validation.d.ts +1063 -0
- package/dist/validation.js +62 -0
- package/package.json +67 -155
- package/compat.d.mts +0 -58
- package/compat.d.mts.map +0 -1
- package/compat.d.ts +0 -58
- package/compat.d.ts.map +0 -1
- package/compat.js +0 -387
- package/compat.js.map +0 -1
- package/compat.mjs +0 -378
- package/compat.mjs.map +0 -1
- package/dynamic-tools.d.mts +0 -12
- package/dynamic-tools.d.mts.map +0 -1
- package/dynamic-tools.d.ts +0 -12
- package/dynamic-tools.d.ts.map +0 -1
- package/dynamic-tools.js +0 -135
- package/dynamic-tools.js.map +0 -1
- package/dynamic-tools.mjs +0 -132
- package/dynamic-tools.mjs.map +0 -1
- package/filtering.d.mts +0 -2
- package/filtering.d.mts.map +0 -1
- package/filtering.d.ts +0 -2
- package/filtering.d.ts.map +0 -1
- package/filtering.js +0 -20
- package/filtering.js.map +0 -1
- package/filtering.mjs +0 -13
- package/filtering.mjs.map +0 -1
- package/headers.d.mts +0 -4
- package/headers.d.mts.map +0 -1
- package/headers.d.ts +0 -4
- package/headers.d.ts.map +0 -1
- package/headers.js +0 -22
- package/headers.js.map +0 -1
- package/headers.mjs +0 -18
- package/headers.mjs.map +0 -1
- package/http.d.mts +0 -9
- package/http.d.mts.map +0 -1
- package/http.d.ts +0 -9
- package/http.d.ts.map +0 -1
- package/http.js +0 -108
- package/http.js.map +0 -1
- package/http.mjs +0 -100
- package/http.mjs.map +0 -1
- package/index.d.mts +0 -3
- package/index.d.mts.map +0 -1
- package/index.d.ts +0 -3
- package/index.d.ts.map +0 -1
- package/index.js +0 -91
- package/index.js.map +0 -1
- package/index.mjs +0 -89
- package/index.mjs.map +0 -1
- package/options.d.mts +0 -18
- package/options.d.mts.map +0 -1
- package/options.d.ts +0 -18
- package/options.d.ts.map +0 -1
- package/options.js +0 -415
- package/options.js.map +0 -1
- package/options.mjs +0 -408
- package/options.mjs.map +0 -1
- package/server.d.mts +0 -35
- package/server.d.mts.map +0 -1
- package/server.d.ts +0 -35
- package/server.d.ts.map +0 -1
- package/server.js +0 -166
- package/server.js.map +0 -1
- package/server.mjs +0 -152
- package/server.mjs.map +0 -1
- package/src/compat.ts +0 -483
- package/src/dynamic-tools.ts +0 -159
- package/src/filtering.ts +0 -14
- package/src/headers.ts +0 -23
- package/src/http.ts +0 -127
- package/src/index.ts +0 -108
- package/src/options.ts +0 -453
- package/src/server.ts +0 -201
- package/src/stdio.ts +0 -13
- package/src/tools/chat/completions/create-chat-completions.ts +0 -1323
- package/src/tools/index.ts +0 -73
- package/src/tools/search/create-search.ts +0 -89
- package/src/tools/types.ts +0 -103
- package/src/tools.ts +0 -1
- package/src/tsconfig.json +0 -11
- package/stdio.d.mts +0 -3
- package/stdio.d.mts.map +0 -1
- package/stdio.d.ts +0 -3
- package/stdio.d.ts.map +0 -1
- package/stdio.js +0 -14
- package/stdio.js.map +0 -1
- package/stdio.mjs +0 -10
- package/stdio.mjs.map +0 -1
- package/tools/chat/completions/create-chat-completions.d.mts +0 -45
- package/tools/chat/completions/create-chat-completions.d.mts.map +0 -1
- package/tools/chat/completions/create-chat-completions.d.ts +0 -45
- package/tools/chat/completions/create-chat-completions.d.ts.map +0 -1
- package/tools/chat/completions/create-chat-completions.js +0 -1320
- package/tools/chat/completions/create-chat-completions.js.map +0 -1
- package/tools/chat/completions/create-chat-completions.mjs +0 -1316
- package/tools/chat/completions/create-chat-completions.mjs.map +0 -1
- package/tools/index.d.mts +0 -10
- package/tools/index.d.mts.map +0 -1
- package/tools/index.d.ts +0 -10
- package/tools/index.d.ts.map +0 -1
- package/tools/index.js +0 -57
- package/tools/index.js.map +0 -1
- package/tools/index.mjs +0 -50
- package/tools/index.mjs.map +0 -1
- package/tools/search/create-search.d.mts +0 -45
- package/tools/search/create-search.d.mts.map +0 -1
- package/tools/search/create-search.d.ts +0 -45
- package/tools/search/create-search.d.ts.map +0 -1
- package/tools/search/create-search.js +0 -86
- package/tools/search/create-search.js.map +0 -1
- package/tools/search/create-search.mjs +0 -82
- package/tools/search/create-search.mjs.map +0 -1
- package/tools/types.d.mts +0 -51
- package/tools/types.d.mts.map +0 -1
- package/tools/types.d.ts +0 -51
- package/tools/types.d.ts.map +0 -1
- package/tools/types.js +0 -46
- package/tools/types.js.map +0 -1
- package/tools/types.mjs +0 -42
- package/tools/types.mjs.map +0 -1
- package/tools.d.mts +0 -2
- package/tools.d.mts.map +0 -1
- package/tools.d.ts +0 -2
- package/tools.d.ts.map +0 -1
- package/tools.js +0 -18
- package/tools.js.map +0 -1
- package/tools.mjs +0 -2
- package/tools.mjs.map +0 -1
package/dist/server.js
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { fetch as undiciFetch, ProxyAgent } from "undici";
|
|
4
|
+
import { AgentResponseSchema, SearchResponseSchema } from "./validation.js";
|
|
5
|
+
const PERPLEXITY_API_KEY = process.env.PERPLEXITY_API_KEY;
|
|
6
|
+
const PERPLEXITY_BASE_URL = process.env.PERPLEXITY_BASE_URL || "https://api.perplexity.ai";
|
|
7
|
+
const VERSION = "1.1.0";
|
|
8
|
+
// Agent API presets backing each tool: https://docs.perplexity.ai/docs/agent-api/presets
|
|
9
|
+
export const ASK_PRESET = "fast";
|
|
10
|
+
export const REASON_PRESET = "medium";
|
|
11
|
+
export const RESEARCH_PRESET = "high";
|
|
12
|
+
export function getProxyUrl() {
|
|
13
|
+
return process.env.PERPLEXITY_PROXY ||
|
|
14
|
+
process.env.HTTPS_PROXY ||
|
|
15
|
+
process.env.HTTP_PROXY ||
|
|
16
|
+
undefined;
|
|
17
|
+
}
|
|
18
|
+
export async function proxyAwareFetch(url, options = {}) {
|
|
19
|
+
const proxyUrl = getProxyUrl();
|
|
20
|
+
if (proxyUrl) {
|
|
21
|
+
const proxyAgent = new ProxyAgent(proxyUrl);
|
|
22
|
+
const undiciOptions = {
|
|
23
|
+
...options,
|
|
24
|
+
dispatcher: proxyAgent,
|
|
25
|
+
};
|
|
26
|
+
const response = await undiciFetch(url, undiciOptions);
|
|
27
|
+
return response;
|
|
28
|
+
}
|
|
29
|
+
return fetch(url, options);
|
|
30
|
+
}
|
|
31
|
+
export function validateMessages(messages, toolName) {
|
|
32
|
+
if (!Array.isArray(messages)) {
|
|
33
|
+
throw new Error(`Invalid arguments for ${toolName}: 'messages' must be an array`);
|
|
34
|
+
}
|
|
35
|
+
for (let i = 0; i < messages.length; i++) {
|
|
36
|
+
const msg = messages[i];
|
|
37
|
+
if (!msg || typeof msg !== 'object') {
|
|
38
|
+
throw new Error(`Invalid message at index ${i}: must be an object`);
|
|
39
|
+
}
|
|
40
|
+
if (!msg.role || typeof msg.role !== 'string') {
|
|
41
|
+
throw new Error(`Invalid message at index ${i}: 'role' must be a string`);
|
|
42
|
+
}
|
|
43
|
+
if (msg.content === undefined || msg.content === null || typeof msg.content !== 'string') {
|
|
44
|
+
throw new Error(`Invalid message at index ${i}: 'content' must be a string`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
async function makeApiRequest(endpoint, body, serviceOrigin, signal) {
|
|
49
|
+
if (!PERPLEXITY_API_KEY) {
|
|
50
|
+
throw new Error("PERPLEXITY_API_KEY environment variable is required");
|
|
51
|
+
}
|
|
52
|
+
// Read timeout fresh each time to respect env var changes
|
|
53
|
+
const TIMEOUT_MS = parseInt(process.env.PERPLEXITY_TIMEOUT_MS || "300000", 10);
|
|
54
|
+
const url = new URL(`${PERPLEXITY_BASE_URL}/${endpoint}`);
|
|
55
|
+
const controller = new AbortController();
|
|
56
|
+
const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
57
|
+
// An abort from the caller's signal also tears down an in-flight body stream.
|
|
58
|
+
if (signal) {
|
|
59
|
+
if (signal.aborted) {
|
|
60
|
+
controller.abort();
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
signal.addEventListener("abort", () => controller.abort(), { once: true });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
let response;
|
|
67
|
+
try {
|
|
68
|
+
const headers = {
|
|
69
|
+
"Content-Type": "application/json",
|
|
70
|
+
"Authorization": `Bearer ${PERPLEXITY_API_KEY}`,
|
|
71
|
+
"User-Agent": `perplexity-mcp/${VERSION}`,
|
|
72
|
+
"X-Source": "pplx-mcp-server",
|
|
73
|
+
};
|
|
74
|
+
if (serviceOrigin) {
|
|
75
|
+
headers["X-Service"] = serviceOrigin;
|
|
76
|
+
}
|
|
77
|
+
response = await proxyAwareFetch(url.toString(), {
|
|
78
|
+
method: "POST",
|
|
79
|
+
headers,
|
|
80
|
+
body: JSON.stringify(body),
|
|
81
|
+
signal: controller.signal,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
clearTimeout(timeoutId);
|
|
86
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
87
|
+
if (signal?.aborted) {
|
|
88
|
+
// The caller knows whether its signal meant cancellation or deadline.
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
throw new Error(`Request timeout: Perplexity API did not respond within ${TIMEOUT_MS}ms. Consider increasing PERPLEXITY_TIMEOUT_MS.`);
|
|
92
|
+
}
|
|
93
|
+
throw new Error(`Network error while calling Perplexity API: ${error}`);
|
|
94
|
+
}
|
|
95
|
+
clearTimeout(timeoutId);
|
|
96
|
+
if (!response.ok) {
|
|
97
|
+
let errorText;
|
|
98
|
+
try {
|
|
99
|
+
errorText = await response.text();
|
|
100
|
+
}
|
|
101
|
+
catch (parseError) {
|
|
102
|
+
errorText = "Unable to parse error response";
|
|
103
|
+
}
|
|
104
|
+
throw new Error(`Perplexity API error: ${response.status} ${response.statusText}\n${errorText}`);
|
|
105
|
+
}
|
|
106
|
+
return response;
|
|
107
|
+
}
|
|
108
|
+
/** Best-effort cancellation of an agent run so an abandoned request stops billing. */
|
|
109
|
+
export async function cancelAgentResponse(responseId, serviceOrigin) {
|
|
110
|
+
try {
|
|
111
|
+
await makeApiRequest(`v1/agent/${encodeURIComponent(responseId)}/cancel`, {}, serviceOrigin);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
// The run may already be terminal; nothing actionable either way.
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Consume an Agent API SSE stream and return the final response object.
|
|
119
|
+
* Emits progress via hooks.onProgress as reasoning events arrive.
|
|
120
|
+
*/
|
|
121
|
+
export async function consumeAgentStream(response, hooks, serviceOrigin, deadlineSignal) {
|
|
122
|
+
const body = response.body;
|
|
123
|
+
if (!body) {
|
|
124
|
+
throw new Error("Response body is null");
|
|
125
|
+
}
|
|
126
|
+
const reader = body.getReader();
|
|
127
|
+
const decoder = new TextDecoder();
|
|
128
|
+
let buffer = "";
|
|
129
|
+
let eventName;
|
|
130
|
+
let responseId;
|
|
131
|
+
let finalResponse;
|
|
132
|
+
let streamError;
|
|
133
|
+
const handleEvent = (type, parsed) => {
|
|
134
|
+
const eventResponse = parsed.response;
|
|
135
|
+
if (eventResponse?.id) {
|
|
136
|
+
responseId = eventResponse.id;
|
|
137
|
+
}
|
|
138
|
+
switch (type) {
|
|
139
|
+
case "response.completed":
|
|
140
|
+
finalResponse = parsed.response;
|
|
141
|
+
break;
|
|
142
|
+
case "response.failed": {
|
|
143
|
+
const error = parsed.error;
|
|
144
|
+
streamError = error?.message || "Agent request failed";
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
case "response.cancelled":
|
|
148
|
+
streamError = "Agent request was cancelled";
|
|
149
|
+
break;
|
|
150
|
+
case "error": {
|
|
151
|
+
const error = parsed.error;
|
|
152
|
+
streamError = error?.message || (typeof parsed.message === "string" ? parsed.message : "Agent request failed");
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
case "response.reasoning.search_queries": {
|
|
156
|
+
const queries = Array.isArray(parsed.queries) ? parsed.queries.filter((q) => typeof q === "string") : [];
|
|
157
|
+
if (queries.length > 0) {
|
|
158
|
+
hooks?.onProgress?.({ message: `Searching: ${queries.join(" | ")}` });
|
|
159
|
+
}
|
|
160
|
+
break;
|
|
161
|
+
}
|
|
162
|
+
case "response.reasoning.search_results": {
|
|
163
|
+
const results = Array.isArray(parsed.results) ? parsed.results : [];
|
|
164
|
+
if (results.length > 0) {
|
|
165
|
+
hooks?.onProgress?.({ message: `Reading ${results.length} search results` });
|
|
166
|
+
}
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
case "response.reasoning.fetch_url_queries":
|
|
170
|
+
hooks?.onProgress?.({ message: "Fetching page content" });
|
|
171
|
+
break;
|
|
172
|
+
case "response.output_item.added": {
|
|
173
|
+
const item = parsed.item;
|
|
174
|
+
if (item?.type === "message") {
|
|
175
|
+
hooks?.onProgress?.({ message: "Writing answer" });
|
|
176
|
+
}
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
// Stop reading as soon as a terminal event is in hand: waiting for the
|
|
182
|
+
// server to close the socket would let a deadline abort in the tail window
|
|
183
|
+
// discard an already-received (and billed) answer.
|
|
184
|
+
const isTerminal = () => finalResponse !== undefined || streamError !== undefined;
|
|
185
|
+
try {
|
|
186
|
+
while (!isTerminal()) {
|
|
187
|
+
const { done, value } = await reader.read();
|
|
188
|
+
if (done)
|
|
189
|
+
break;
|
|
190
|
+
buffer += decoder.decode(value, { stream: true });
|
|
191
|
+
const lines = buffer.split("\n");
|
|
192
|
+
// Keep the last potentially incomplete line in the buffer
|
|
193
|
+
buffer = lines.pop() || "";
|
|
194
|
+
for (const line of lines) {
|
|
195
|
+
const trimmed = line.trim();
|
|
196
|
+
if (!trimmed) {
|
|
197
|
+
eventName = undefined;
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (trimmed.startsWith("event:")) {
|
|
201
|
+
eventName = trimmed.slice("event:".length).trim();
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
if (!trimmed.startsWith("data:"))
|
|
205
|
+
continue;
|
|
206
|
+
const data = trimmed.slice("data:".length).trim();
|
|
207
|
+
if (data === "[DONE]")
|
|
208
|
+
continue;
|
|
209
|
+
try {
|
|
210
|
+
const parsed = JSON.parse(data);
|
|
211
|
+
const type = typeof parsed.type === "string" ? parsed.type : eventName;
|
|
212
|
+
if (type) {
|
|
213
|
+
handleEvent(type, parsed);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
// Skip malformed JSON chunks (e.g. keep-alive pings)
|
|
218
|
+
}
|
|
219
|
+
if (isTerminal())
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (isTerminal()) {
|
|
224
|
+
void reader.cancel().catch(() => { });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
if (hooks?.signal?.aborted || deadlineSignal?.aborted) {
|
|
229
|
+
if (responseId) {
|
|
230
|
+
// Stop the server-side run so an abandoned request stops billing.
|
|
231
|
+
void cancelAgentResponse(responseId, serviceOrigin);
|
|
232
|
+
}
|
|
233
|
+
if (hooks?.signal?.aborted) {
|
|
234
|
+
throw new Error("Request cancelled");
|
|
235
|
+
}
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
throw new Error(`Network error while streaming from Perplexity API: ${error}`);
|
|
239
|
+
}
|
|
240
|
+
if (hooks?.signal?.aborted) {
|
|
241
|
+
if (responseId) {
|
|
242
|
+
void cancelAgentResponse(responseId, serviceOrigin);
|
|
243
|
+
}
|
|
244
|
+
throw new Error("Request cancelled");
|
|
245
|
+
}
|
|
246
|
+
if (streamError) {
|
|
247
|
+
throw new Error(`Perplexity API error: ${streamError}`);
|
|
248
|
+
}
|
|
249
|
+
if (!finalResponse) {
|
|
250
|
+
throw new Error("Agent stream ended without a completed response");
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
return AgentResponseSchema.parse(finalResponse);
|
|
254
|
+
}
|
|
255
|
+
catch (error) {
|
|
256
|
+
throw new Error(`Invalid response from Perplexity Agent API: ${error}`);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
export function extractAgentText(response) {
|
|
260
|
+
return response.output
|
|
261
|
+
.filter((item) => item.type === "message")
|
|
262
|
+
.flatMap((item) => item.content ?? [])
|
|
263
|
+
.filter((part) => part.type === "output_text" && typeof part.text === "string")
|
|
264
|
+
.map((part) => part.text)
|
|
265
|
+
.join("");
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Append the "Citations:" block ("[n] url" lines) to the answer text, keyed
|
|
269
|
+
* by the numeric search-result ids that inline references point at. The
|
|
270
|
+
* answer body is never modified: bracketed tokens also appear in code, LaTeX,
|
|
271
|
+
* and slice syntax, so any rewrite risks corrupting the answer. If ids are
|
|
272
|
+
* missing or ambiguous, all unique source URLs are appended with positional
|
|
273
|
+
* numbering instead.
|
|
274
|
+
*/
|
|
275
|
+
export function formatAgentResponseText(response) {
|
|
276
|
+
const text = extractAgentText(response);
|
|
277
|
+
const entries = [];
|
|
278
|
+
const urlById = new Map();
|
|
279
|
+
let idsUsable = true;
|
|
280
|
+
for (const item of response.output) {
|
|
281
|
+
if (item.type !== "search_results" || !Array.isArray(item.results))
|
|
282
|
+
continue;
|
|
283
|
+
for (const result of item.results) {
|
|
284
|
+
if (!result.url)
|
|
285
|
+
continue;
|
|
286
|
+
entries.push({ id: result.id, url: result.url });
|
|
287
|
+
if (typeof result.id !== "number") {
|
|
288
|
+
idsUsable = false;
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
const existing = urlById.get(result.id);
|
|
292
|
+
if (existing === undefined) {
|
|
293
|
+
urlById.set(result.id, result.url);
|
|
294
|
+
}
|
|
295
|
+
else if (existing !== result.url) {
|
|
296
|
+
idsUsable = false;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (entries.length === 0) {
|
|
301
|
+
return text;
|
|
302
|
+
}
|
|
303
|
+
let output = text + "\n\nCitations:\n";
|
|
304
|
+
if (idsUsable) {
|
|
305
|
+
const emitted = new Set();
|
|
306
|
+
for (const entry of entries) {
|
|
307
|
+
const id = entry.id;
|
|
308
|
+
if (emitted.has(id))
|
|
309
|
+
continue;
|
|
310
|
+
emitted.add(id);
|
|
311
|
+
output += `[${id}] ${entry.url}\n`;
|
|
312
|
+
}
|
|
313
|
+
return output;
|
|
314
|
+
}
|
|
315
|
+
const seen = new Set();
|
|
316
|
+
let position = 0;
|
|
317
|
+
for (const entry of entries) {
|
|
318
|
+
if (seen.has(entry.url))
|
|
319
|
+
continue;
|
|
320
|
+
seen.add(entry.url);
|
|
321
|
+
position += 1;
|
|
322
|
+
output += `[${position}] ${entry.url}\n`;
|
|
323
|
+
}
|
|
324
|
+
return output;
|
|
325
|
+
}
|
|
326
|
+
function buildWebSearchTool(options) {
|
|
327
|
+
if (!options)
|
|
328
|
+
return undefined;
|
|
329
|
+
const filters = {
|
|
330
|
+
...(options.search_recency_filter && { search_recency_filter: options.search_recency_filter }),
|
|
331
|
+
...(options.search_domain_filter && { search_domain_filter: options.search_domain_filter }),
|
|
332
|
+
};
|
|
333
|
+
const tool = {
|
|
334
|
+
type: "web_search",
|
|
335
|
+
...(Object.keys(filters).length > 0 && { filters }),
|
|
336
|
+
...(options.search_context_size && { search_context_size: options.search_context_size }),
|
|
337
|
+
};
|
|
338
|
+
// No override means the preset's own web_search config stays in effect.
|
|
339
|
+
return Object.keys(tool).length > 1 ? tool : undefined;
|
|
340
|
+
}
|
|
341
|
+
export async function performAgentResponse(messages, preset, serviceOrigin, options, hooks) {
|
|
342
|
+
const webSearchTool = buildWebSearchTool(options);
|
|
343
|
+
const body = {
|
|
344
|
+
preset,
|
|
345
|
+
input: messages.map((message) => ({
|
|
346
|
+
type: "message",
|
|
347
|
+
role: message.role,
|
|
348
|
+
content: message.content,
|
|
349
|
+
})),
|
|
350
|
+
// Always stream: long runs outlive intermediate proxy timeouts, and the
|
|
351
|
+
// reasoning events double as progress reporting.
|
|
352
|
+
stream: true,
|
|
353
|
+
...(webSearchTool && { tools: [webSearchTool] }),
|
|
354
|
+
};
|
|
355
|
+
// PERPLEXITY_TIMEOUT_MS bounds the whole call, not just time-to-headers:
|
|
356
|
+
// streamed responses return headers immediately, so a headers-only timeout
|
|
357
|
+
// would never fire.
|
|
358
|
+
const TIMEOUT_MS = parseInt(process.env.PERPLEXITY_TIMEOUT_MS || "300000", 10);
|
|
359
|
+
const deadline = new AbortController();
|
|
360
|
+
const timeoutId = setTimeout(() => deadline.abort(), TIMEOUT_MS);
|
|
361
|
+
const abortDeadline = () => deadline.abort();
|
|
362
|
+
if (hooks?.signal) {
|
|
363
|
+
if (hooks.signal.aborted) {
|
|
364
|
+
deadline.abort();
|
|
365
|
+
}
|
|
366
|
+
else {
|
|
367
|
+
hooks.signal.addEventListener("abort", abortDeadline, { once: true });
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
try {
|
|
371
|
+
const response = await makeApiRequest("v1/agent", body, serviceOrigin, deadline.signal);
|
|
372
|
+
const agentResponse = await consumeAgentStream(response, hooks, serviceOrigin, deadline.signal);
|
|
373
|
+
return formatAgentResponseText(agentResponse);
|
|
374
|
+
}
|
|
375
|
+
catch (error) {
|
|
376
|
+
if (hooks?.signal?.aborted) {
|
|
377
|
+
throw new Error("Request cancelled");
|
|
378
|
+
}
|
|
379
|
+
if (deadline.signal.aborted) {
|
|
380
|
+
throw new Error(`Request timeout: Perplexity API did not respond within ${TIMEOUT_MS}ms. Consider increasing PERPLEXITY_TIMEOUT_MS.`);
|
|
381
|
+
}
|
|
382
|
+
throw error;
|
|
383
|
+
}
|
|
384
|
+
finally {
|
|
385
|
+
clearTimeout(timeoutId);
|
|
386
|
+
hooks?.signal?.removeEventListener("abort", abortDeadline);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
export function formatSearchResults(data) {
|
|
390
|
+
if (!data.results || !Array.isArray(data.results)) {
|
|
391
|
+
return "No search results found.";
|
|
392
|
+
}
|
|
393
|
+
let formattedResults = `Found ${data.results.length} search results:\n\n`;
|
|
394
|
+
data.results.forEach((result, index) => {
|
|
395
|
+
formattedResults += `${index + 1}. **${result.title}**\n`;
|
|
396
|
+
formattedResults += ` URL: ${result.url}\n`;
|
|
397
|
+
if (result.snippet) {
|
|
398
|
+
formattedResults += ` ${result.snippet}\n`;
|
|
399
|
+
}
|
|
400
|
+
if (result.date) {
|
|
401
|
+
formattedResults += ` Date: ${result.date}\n`;
|
|
402
|
+
}
|
|
403
|
+
formattedResults += `\n`;
|
|
404
|
+
});
|
|
405
|
+
return formattedResults;
|
|
406
|
+
}
|
|
407
|
+
export async function performSearch(query, maxResults = 10, maxTokensPerPage = 1024, country, filters, serviceOrigin) {
|
|
408
|
+
const body = {
|
|
409
|
+
query: query,
|
|
410
|
+
max_results: maxResults,
|
|
411
|
+
max_tokens_per_page: maxTokensPerPage,
|
|
412
|
+
...(country && { country }),
|
|
413
|
+
...(filters?.search_recency_filter && { search_recency_filter: filters.search_recency_filter }),
|
|
414
|
+
...(filters?.search_domain_filter && { search_domain_filter: filters.search_domain_filter }),
|
|
415
|
+
};
|
|
416
|
+
const response = await makeApiRequest("search", body, serviceOrigin);
|
|
417
|
+
let data;
|
|
418
|
+
try {
|
|
419
|
+
const json = await response.json();
|
|
420
|
+
data = SearchResponseSchema.parse(json);
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
throw new Error(`Failed to parse JSON response from Perplexity Search API: ${error}`);
|
|
424
|
+
}
|
|
425
|
+
return formatSearchResults(data);
|
|
426
|
+
}
|
|
427
|
+
function buildHooks(extra) {
|
|
428
|
+
const progressToken = extra?._meta?.progressToken;
|
|
429
|
+
const sendNotification = extra?.sendNotification;
|
|
430
|
+
let progress = 0;
|
|
431
|
+
return {
|
|
432
|
+
signal: extra?.signal,
|
|
433
|
+
onProgress: progressToken !== undefined && sendNotification
|
|
434
|
+
? (update) => {
|
|
435
|
+
void sendNotification({
|
|
436
|
+
method: "notifications/progress",
|
|
437
|
+
params: {
|
|
438
|
+
progressToken,
|
|
439
|
+
progress: ++progress,
|
|
440
|
+
message: update.message,
|
|
441
|
+
},
|
|
442
|
+
}).catch(() => { });
|
|
443
|
+
}
|
|
444
|
+
: undefined,
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
export function createPerplexityServer(serviceOrigin) {
|
|
448
|
+
const server = new McpServer({
|
|
449
|
+
name: "ai.perplexity/mcp-server",
|
|
450
|
+
version: VERSION,
|
|
451
|
+
}, {
|
|
452
|
+
instructions: "Perplexity AI server for web-grounded search, research, and reasoning, backed by the Perplexity Agent API. " +
|
|
453
|
+
"Use perplexity_search for finding URLs, facts, and recent news. Supports recency filters and domain restrictions. " +
|
|
454
|
+
"Use perplexity_ask for quick AI-answered questions with citations. Supports recency filters, domain restrictions, and search context size control. " +
|
|
455
|
+
"Use perplexity_research for in-depth multi-source investigation (slow, can take minutes). " +
|
|
456
|
+
"Use perplexity_reason for complex analysis requiring step-by-step logic. Supports recency filters, domain restrictions, and search context size control. " +
|
|
457
|
+
"All tools are read-only and access live web data.",
|
|
458
|
+
});
|
|
459
|
+
const messageSchema = z.object({
|
|
460
|
+
role: z.enum(["system", "user", "assistant"]).describe("Role of the message sender"),
|
|
461
|
+
content: z.string().describe("The content of the message"),
|
|
462
|
+
});
|
|
463
|
+
const messagesField = z.array(messageSchema).describe("Array of conversation messages");
|
|
464
|
+
const searchRecencyFilterField = z.enum(["hour", "day", "week", "month", "year"]).optional()
|
|
465
|
+
.describe("Filter search results by recency. Use 'hour' for very recent news, 'day' for today's updates, 'week' for this week, etc.");
|
|
466
|
+
const searchDomainFilterField = z.array(z.string()).optional()
|
|
467
|
+
.describe("Restrict search results to specific domains (e.g., ['wikipedia.org', 'arxiv.org']). Use '-' prefix for exclusion (e.g., ['-reddit.com']).");
|
|
468
|
+
const searchContextSizeField = z.enum(["low", "medium", "high"]).optional()
|
|
469
|
+
.describe("Controls how much web context is retrieved. 'low' is fastest, 'high' provides more comprehensive results.");
|
|
470
|
+
const responseOutputSchema = {
|
|
471
|
+
response: z.string().describe("AI-generated text response with numbered citation references"),
|
|
472
|
+
};
|
|
473
|
+
// Input schemas
|
|
474
|
+
const askAndReasonInputSchema = {
|
|
475
|
+
messages: messagesField,
|
|
476
|
+
search_recency_filter: searchRecencyFilterField,
|
|
477
|
+
search_domain_filter: searchDomainFilterField,
|
|
478
|
+
search_context_size: searchContextSizeField,
|
|
479
|
+
};
|
|
480
|
+
const researchInputSchema = {
|
|
481
|
+
messages: messagesField,
|
|
482
|
+
};
|
|
483
|
+
server.registerTool("perplexity_ask", {
|
|
484
|
+
title: "Ask Perplexity",
|
|
485
|
+
description: "Answer a question using web-grounded AI (Perplexity Agent API, " + ASK_PRESET + " preset). " +
|
|
486
|
+
"Best for: quick factual questions, summaries, explanations, and general Q&A. " +
|
|
487
|
+
"Returns a text response with numbered citations. Fastest and cheapest option. " +
|
|
488
|
+
"Supports filtering by recency (hour/day/week/month/year), domain restrictions, and search context size. " +
|
|
489
|
+
"For in-depth multi-source research, use perplexity_research instead. " +
|
|
490
|
+
"For step-by-step reasoning and analysis, use perplexity_reason instead.",
|
|
491
|
+
inputSchema: askAndReasonInputSchema,
|
|
492
|
+
outputSchema: responseOutputSchema,
|
|
493
|
+
annotations: {
|
|
494
|
+
readOnlyHint: true,
|
|
495
|
+
openWorldHint: true,
|
|
496
|
+
idempotentHint: false,
|
|
497
|
+
destructiveHint: false,
|
|
498
|
+
},
|
|
499
|
+
}, async (args, extra) => {
|
|
500
|
+
const { messages, search_recency_filter, search_domain_filter, search_context_size } = args;
|
|
501
|
+
validateMessages(messages, "perplexity_ask");
|
|
502
|
+
const options = {
|
|
503
|
+
...(search_recency_filter && { search_recency_filter }),
|
|
504
|
+
...(search_domain_filter && { search_domain_filter }),
|
|
505
|
+
...(search_context_size && { search_context_size }),
|
|
506
|
+
};
|
|
507
|
+
const result = await performAgentResponse(messages, ASK_PRESET, serviceOrigin, Object.keys(options).length > 0 ? options : undefined, buildHooks(extra));
|
|
508
|
+
return {
|
|
509
|
+
content: [{ type: "text", text: result }],
|
|
510
|
+
structuredContent: { response: result },
|
|
511
|
+
};
|
|
512
|
+
});
|
|
513
|
+
server.registerTool("perplexity_research", {
|
|
514
|
+
title: "Deep Research",
|
|
515
|
+
description: "Conduct deep, multi-source research on a topic (Perplexity Agent API, " + RESEARCH_PRESET + " preset). " +
|
|
516
|
+
"Best for: literature reviews, comprehensive overviews, investigative queries needing " +
|
|
517
|
+
"many sources. Returns a detailed response with numbered citations. " +
|
|
518
|
+
"Significantly slower than other tools (can take minutes). " +
|
|
519
|
+
"For quick factual questions, use perplexity_ask instead. " +
|
|
520
|
+
"For logical analysis and reasoning, use perplexity_reason instead.",
|
|
521
|
+
inputSchema: researchInputSchema,
|
|
522
|
+
outputSchema: responseOutputSchema,
|
|
523
|
+
annotations: {
|
|
524
|
+
readOnlyHint: true,
|
|
525
|
+
openWorldHint: true,
|
|
526
|
+
idempotentHint: false,
|
|
527
|
+
destructiveHint: false,
|
|
528
|
+
},
|
|
529
|
+
}, async (args, extra) => {
|
|
530
|
+
const { messages } = args;
|
|
531
|
+
validateMessages(messages, "perplexity_research");
|
|
532
|
+
const result = await performAgentResponse(messages, RESEARCH_PRESET, serviceOrigin, undefined, buildHooks(extra));
|
|
533
|
+
return {
|
|
534
|
+
content: [{ type: "text", text: result }],
|
|
535
|
+
structuredContent: { response: result },
|
|
536
|
+
};
|
|
537
|
+
});
|
|
538
|
+
server.registerTool("perplexity_reason", {
|
|
539
|
+
title: "Advanced Reasoning",
|
|
540
|
+
description: "Analyze a question using step-by-step reasoning with web grounding (Perplexity Agent API, " + REASON_PRESET + " preset). " +
|
|
541
|
+
"Best for: math, logic, comparisons, complex arguments, and tasks requiring chain-of-thought. " +
|
|
542
|
+
"Returns a reasoned response with numbered citations. " +
|
|
543
|
+
"Supports filtering by recency (hour/day/week/month/year), domain restrictions, and search context size. " +
|
|
544
|
+
"For quick factual questions, use perplexity_ask instead. " +
|
|
545
|
+
"For comprehensive multi-source research, use perplexity_research instead.",
|
|
546
|
+
inputSchema: askAndReasonInputSchema,
|
|
547
|
+
outputSchema: responseOutputSchema,
|
|
548
|
+
annotations: {
|
|
549
|
+
readOnlyHint: true,
|
|
550
|
+
openWorldHint: true,
|
|
551
|
+
idempotentHint: false,
|
|
552
|
+
destructiveHint: false,
|
|
553
|
+
},
|
|
554
|
+
}, async (args, extra) => {
|
|
555
|
+
const { messages, search_recency_filter, search_domain_filter, search_context_size } = args;
|
|
556
|
+
validateMessages(messages, "perplexity_reason");
|
|
557
|
+
const options = {
|
|
558
|
+
...(search_recency_filter && { search_recency_filter }),
|
|
559
|
+
...(search_domain_filter && { search_domain_filter }),
|
|
560
|
+
...(search_context_size && { search_context_size }),
|
|
561
|
+
};
|
|
562
|
+
const result = await performAgentResponse(messages, REASON_PRESET, serviceOrigin, Object.keys(options).length > 0 ? options : undefined, buildHooks(extra));
|
|
563
|
+
return {
|
|
564
|
+
content: [{ type: "text", text: result }],
|
|
565
|
+
structuredContent: { response: result },
|
|
566
|
+
};
|
|
567
|
+
});
|
|
568
|
+
const searchInputSchema = {
|
|
569
|
+
query: z.string().describe("Search query string"),
|
|
570
|
+
max_results: z.number().min(1).max(20).optional()
|
|
571
|
+
.describe("Maximum number of results to return (1-20, default: 10)"),
|
|
572
|
+
max_tokens_per_page: z.number().min(256).max(2048).optional()
|
|
573
|
+
.describe("Maximum tokens to extract per webpage (default: 1024)"),
|
|
574
|
+
country: z.string().optional()
|
|
575
|
+
.describe("ISO 3166-1 alpha-2 country code for regional results (e.g., 'US', 'GB')"),
|
|
576
|
+
search_recency_filter: searchRecencyFilterField,
|
|
577
|
+
search_domain_filter: searchDomainFilterField,
|
|
578
|
+
};
|
|
579
|
+
const searchOutputSchema = {
|
|
580
|
+
results: z.string().describe("Formatted search results, each with title, URL, snippet, and date"),
|
|
581
|
+
};
|
|
582
|
+
server.registerTool("perplexity_search", {
|
|
583
|
+
title: "Search the Web",
|
|
584
|
+
description: "Search the web and return a ranked list of results with titles, URLs, snippets, and dates. " +
|
|
585
|
+
"Best for: finding specific URLs, checking recent news, verifying facts, discovering sources. " +
|
|
586
|
+
"Returns formatted results (title, URL, snippet, date) with no AI synthesis. " +
|
|
587
|
+
"Supports recency filters and domain restrictions. " +
|
|
588
|
+
"For AI-generated answers with citations, use perplexity_ask instead.",
|
|
589
|
+
inputSchema: searchInputSchema,
|
|
590
|
+
outputSchema: searchOutputSchema,
|
|
591
|
+
annotations: {
|
|
592
|
+
readOnlyHint: true,
|
|
593
|
+
openWorldHint: true,
|
|
594
|
+
idempotentHint: false,
|
|
595
|
+
destructiveHint: false,
|
|
596
|
+
},
|
|
597
|
+
}, async (args) => {
|
|
598
|
+
const { query, max_results, max_tokens_per_page, country, search_recency_filter, search_domain_filter } = args;
|
|
599
|
+
const maxResults = typeof max_results === "number" ? max_results : 10;
|
|
600
|
+
const maxTokensPerPage = typeof max_tokens_per_page === "number" ? max_tokens_per_page : 1024;
|
|
601
|
+
const countryCode = typeof country === "string" ? country : undefined;
|
|
602
|
+
const filters = {
|
|
603
|
+
...(search_recency_filter && { search_recency_filter }),
|
|
604
|
+
...(search_domain_filter && { search_domain_filter }),
|
|
605
|
+
};
|
|
606
|
+
const result = await performSearch(query, maxResults, maxTokensPerPage, countryCode, filters, serviceOrigin);
|
|
607
|
+
return {
|
|
608
|
+
content: [{ type: "text", text: result }],
|
|
609
|
+
structuredContent: { results: result },
|
|
610
|
+
};
|
|
611
|
+
});
|
|
612
|
+
return server.server;
|
|
613
|
+
}
|