@perplexity-ai/mcp-server 1.0.0 → 1.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.
@@ -6,14 +6,14 @@
6
6
  },
7
7
  "metadata": {
8
8
  "description": "Official Perplexity AI plugin providing real-time web search, reasoning, and research capabilities",
9
- "version": "1.0.0"
9
+ "version": "1.2.0"
10
10
  },
11
11
  "plugins": [
12
12
  {
13
13
  "name": "perplexity",
14
14
  "source": "./",
15
15
  "description": "Real-time web search, reasoning, and research through Perplexity's API",
16
- "version": "1.0.0",
16
+ "version": "1.2.0",
17
17
  "author": {
18
18
  "name": "Perplexity AI",
19
19
  "email": "api@perplexity.ai"
package/README.md CHANGED
@@ -13,7 +13,7 @@ The official MCP server implementation for the Perplexity API Platform, providin
13
13
  ## Available Tools
14
14
 
15
15
  ### **perplexity_search**
16
- Direct web search using the Perplexity Search API. Returns ranked search results with metadata, perfect for finding current information.
16
+ Direct web search using the Perplexity Search API. Returns ranked search results with metadata, perfect for finding current information. Supports recency filters (`search_recency_filter`) and domain restrictions (`search_domain_filter`).
17
17
 
18
18
  ### **perplexity_ask**
19
19
  General-purpose conversational AI with real-time web search, backed by the Agent API `fast` preset. Great for quick questions and everyday searches.
@@ -147,6 +147,26 @@ npm install && npm run build && npm run start:http
147
147
 
148
148
  The server will be accessible at `http://localhost:8080/mcp`
149
149
 
150
+ ## Use as a Library
151
+
152
+ The package also exports the server factory for embedding in your own Node process:
153
+
154
+ ```ts
155
+ import { createPerplexityServer } from "@perplexity-ai/mcp-server";
156
+
157
+ // Single-tenant: reads PERPLEXITY_API_KEY from the environment.
158
+ const server = createPerplexityServer("my-service");
159
+
160
+ // Multi-tenant hosts resolve the key per call instead. When a provider is
161
+ // set, the environment variable is never consulted, and a provider that
162
+ // returns no key fails the call rather than falling back.
163
+ const tenantServer = createPerplexityServer("my-service", {
164
+ apiKey: () => currentRequestApiKey,
165
+ });
166
+ ```
167
+
168
+ Mount the returned server on any MCP transport (stdio, streamable HTTP, in-memory).
169
+
150
170
  ## Troubleshooting
151
171
 
152
172
  - **API Key Issues**: Ensure `PERPLEXITY_API_KEY` is set correctly
package/dist/http.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import { type Express } from "express";
3
+ export interface HttpAppOptions {
4
+ port: number;
5
+ bindAddress: string;
6
+ allowedOrigins: string[];
7
+ allowedHosts: Set<string>;
8
+ }
9
+ /**
10
+ * Build the Express app for the HTTP transport. Exported so tests can
11
+ * exercise the same wiring used in production.
12
+ */
13
+ export declare function createHttpApp(options: HttpAppOptions): Express;
14
+ /** Build the Host header allowlist from PORT + ALLOWED_HOSTS. */
15
+ export declare function buildAllowedHosts(port: number, extra: string[]): Set<string>;
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Simple structured logger for the Perplexity MCP Server
3
+ * Outputs to stderr to avoid interfering with STDIO transport
4
+ */
5
+ export declare enum LogLevel {
6
+ DEBUG = 0,
7
+ INFO = 1,
8
+ WARN = 2,
9
+ ERROR = 3
10
+ }
11
+ /**
12
+ * Structured logger interface
13
+ */
14
+ export declare const logger: {
15
+ debug(message: string, meta?: Record<string, unknown>): void;
16
+ info(message: string, meta?: Record<string, unknown>): void;
17
+ warn(message: string, meta?: Record<string, unknown>): void;
18
+ error(message: string, meta?: Record<string, unknown>): void;
19
+ };
@@ -0,0 +1,62 @@
1
+ import type { Message, AgentResponse, AgentToolOptions, AgentCallHooks, ApiKeyProvider, PerplexityServerOptions, SearchResponse } from "./types.js";
2
+ export type { ApiKeyProvider, PerplexityServerOptions } from "./types.js";
3
+ export declare const ASK_PRESET = "fast";
4
+ export declare const REASON_PRESET = "medium";
5
+ export declare const RESEARCH_PRESET = "high";
6
+ export declare function getProxyUrl(): string | undefined;
7
+ export declare function proxyAwareFetch(url: string, options?: RequestInit): Promise<Response>;
8
+ export declare function validateMessages(messages: unknown, toolName: string): asserts messages is Message[];
9
+ /** Best-effort cancellation of an agent run so an abandoned request stops billing. */
10
+ export declare function cancelAgentResponse(responseId: string, serviceOrigin?: string, apiKey?: ApiKeyProvider): Promise<void>;
11
+ /**
12
+ * Consume an Agent API SSE stream and return the final response object.
13
+ * Emits progress via hooks.onProgress as reasoning events arrive.
14
+ */
15
+ export declare function consumeAgentStream(response: Response, hooks?: AgentCallHooks, serviceOrigin?: string, deadlineSignal?: AbortSignal, apiKey?: ApiKeyProvider): Promise<AgentResponse>;
16
+ export declare function extractAgentText(response: AgentResponse): string;
17
+ /**
18
+ * Append the "Citations:" block ("[n] url" lines) to the answer text, keyed
19
+ * by the numeric search-result ids that inline references point at. The
20
+ * answer body is never modified: bracketed tokens also appear in code, LaTeX,
21
+ * and slice syntax, so any rewrite risks corrupting the answer. If ids are
22
+ * missing or ambiguous, all unique source URLs are appended with positional
23
+ * numbering instead.
24
+ */
25
+ export declare function formatAgentResponseText(response: AgentResponse): string;
26
+ export declare function performAgentResponse(messages: Message[], preset: string, serviceOrigin?: string, options?: AgentToolOptions, hooks?: AgentCallHooks, apiKey?: ApiKeyProvider): Promise<string>;
27
+ export declare function formatSearchResults(data: SearchResponse): string;
28
+ export declare function performSearch(query: string, maxResults?: number, maxTokensPerPage?: number, country?: string, filters?: Pick<AgentToolOptions, "search_recency_filter" | "search_domain_filter">, serviceOrigin?: string, apiKey?: ApiKeyProvider): Promise<string>;
29
+ export declare function createPerplexityServer(serviceOrigin?: string, serverOptions?: PerplexityServerOptions): import("@modelcontextprotocol/sdk/server/index.js").Server<{
30
+ method: string;
31
+ params?: {
32
+ [x: string]: unknown;
33
+ _meta?: {
34
+ [x: string]: unknown;
35
+ progressToken?: string | number | undefined;
36
+ "io.modelcontextprotocol/related-task"?: {
37
+ taskId: string;
38
+ } | undefined;
39
+ } | undefined;
40
+ } | undefined;
41
+ }, {
42
+ method: string;
43
+ params?: {
44
+ [x: string]: unknown;
45
+ _meta?: {
46
+ [x: string]: unknown;
47
+ progressToken?: string | number | undefined;
48
+ "io.modelcontextprotocol/related-task"?: {
49
+ taskId: string;
50
+ } | undefined;
51
+ } | undefined;
52
+ } | undefined;
53
+ }, {
54
+ [x: string]: unknown;
55
+ _meta?: {
56
+ [x: string]: unknown;
57
+ progressToken?: string | number | undefined;
58
+ "io.modelcontextprotocol/related-task"?: {
59
+ taskId: string;
60
+ } | undefined;
61
+ } | undefined;
62
+ }>;
package/dist/server.js CHANGED
@@ -4,7 +4,7 @@ import { fetch as undiciFetch, ProxyAgent } from "undici";
4
4
  import { AgentResponseSchema, SearchResponseSchema } from "./validation.js";
5
5
  const PERPLEXITY_API_KEY = process.env.PERPLEXITY_API_KEY;
6
6
  const PERPLEXITY_BASE_URL = process.env.PERPLEXITY_BASE_URL || "https://api.perplexity.ai";
7
- const VERSION = "1.0.0";
7
+ const VERSION = "1.2.0";
8
8
  // Agent API presets backing each tool: https://docs.perplexity.ai/docs/agent-api/presets
9
9
  export const ASK_PRESET = "fast";
10
10
  export const REASON_PRESET = "medium";
@@ -45,9 +45,21 @@ export function validateMessages(messages, toolName) {
45
45
  }
46
46
  }
47
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");
48
+ async function makeApiRequest(endpoint, body, serviceOrigin, signal, apiKey) {
49
+ // A configured provider fully replaces the env var: falling back would let
50
+ // a multi-tenant misconfiguration silently bill the process-wide key.
51
+ let resolvedApiKey;
52
+ if (apiKey) {
53
+ resolvedApiKey = apiKey();
54
+ if (!resolvedApiKey) {
55
+ throw new Error("API key provider returned no key");
56
+ }
57
+ }
58
+ else {
59
+ resolvedApiKey = PERPLEXITY_API_KEY;
60
+ if (!resolvedApiKey) {
61
+ throw new Error("PERPLEXITY_API_KEY environment variable is required");
62
+ }
51
63
  }
52
64
  // Read timeout fresh each time to respect env var changes
53
65
  const TIMEOUT_MS = parseInt(process.env.PERPLEXITY_TIMEOUT_MS || "300000", 10);
@@ -67,7 +79,7 @@ async function makeApiRequest(endpoint, body, serviceOrigin, signal) {
67
79
  try {
68
80
  const headers = {
69
81
  "Content-Type": "application/json",
70
- "Authorization": `Bearer ${PERPLEXITY_API_KEY}`,
82
+ "Authorization": `Bearer ${resolvedApiKey}`,
71
83
  "User-Agent": `perplexity-mcp/${VERSION}`,
72
84
  "X-Source": "pplx-mcp-server",
73
85
  };
@@ -106,9 +118,9 @@ async function makeApiRequest(endpoint, body, serviceOrigin, signal) {
106
118
  return response;
107
119
  }
108
120
  /** Best-effort cancellation of an agent run so an abandoned request stops billing. */
109
- export async function cancelAgentResponse(responseId, serviceOrigin) {
121
+ export async function cancelAgentResponse(responseId, serviceOrigin, apiKey) {
110
122
  try {
111
- await makeApiRequest(`v1/agent/${encodeURIComponent(responseId)}/cancel`, {}, serviceOrigin);
123
+ await makeApiRequest(`v1/agent/${encodeURIComponent(responseId)}/cancel`, {}, serviceOrigin, undefined, apiKey);
112
124
  }
113
125
  catch {
114
126
  // The run may already be terminal; nothing actionable either way.
@@ -118,7 +130,7 @@ export async function cancelAgentResponse(responseId, serviceOrigin) {
118
130
  * Consume an Agent API SSE stream and return the final response object.
119
131
  * Emits progress via hooks.onProgress as reasoning events arrive.
120
132
  */
121
- export async function consumeAgentStream(response, hooks, serviceOrigin, deadlineSignal) {
133
+ export async function consumeAgentStream(response, hooks, serviceOrigin, deadlineSignal, apiKey) {
122
134
  const body = response.body;
123
135
  if (!body) {
124
136
  throw new Error("Response body is null");
@@ -228,7 +240,7 @@ export async function consumeAgentStream(response, hooks, serviceOrigin, deadlin
228
240
  if (hooks?.signal?.aborted || deadlineSignal?.aborted) {
229
241
  if (responseId) {
230
242
  // Stop the server-side run so an abandoned request stops billing.
231
- void cancelAgentResponse(responseId, serviceOrigin);
243
+ void cancelAgentResponse(responseId, serviceOrigin, apiKey);
232
244
  }
233
245
  if (hooks?.signal?.aborted) {
234
246
  throw new Error("Request cancelled");
@@ -239,7 +251,7 @@ export async function consumeAgentStream(response, hooks, serviceOrigin, deadlin
239
251
  }
240
252
  if (hooks?.signal?.aborted) {
241
253
  if (responseId) {
242
- void cancelAgentResponse(responseId, serviceOrigin);
254
+ void cancelAgentResponse(responseId, serviceOrigin, apiKey);
243
255
  }
244
256
  throw new Error("Request cancelled");
245
257
  }
@@ -338,7 +350,7 @@ function buildWebSearchTool(options) {
338
350
  // No override means the preset's own web_search config stays in effect.
339
351
  return Object.keys(tool).length > 1 ? tool : undefined;
340
352
  }
341
- export async function performAgentResponse(messages, preset, serviceOrigin, options, hooks) {
353
+ export async function performAgentResponse(messages, preset, serviceOrigin, options, hooks, apiKey) {
342
354
  const webSearchTool = buildWebSearchTool(options);
343
355
  const body = {
344
356
  preset,
@@ -368,8 +380,8 @@ export async function performAgentResponse(messages, preset, serviceOrigin, opti
368
380
  }
369
381
  }
370
382
  try {
371
- const response = await makeApiRequest("v1/agent", body, serviceOrigin, deadline.signal);
372
- const agentResponse = await consumeAgentStream(response, hooks, serviceOrigin, deadline.signal);
383
+ const response = await makeApiRequest("v1/agent", body, serviceOrigin, deadline.signal, apiKey);
384
+ const agentResponse = await consumeAgentStream(response, hooks, serviceOrigin, deadline.signal, apiKey);
373
385
  return formatAgentResponseText(agentResponse);
374
386
  }
375
387
  catch (error) {
@@ -404,14 +416,16 @@ export function formatSearchResults(data) {
404
416
  });
405
417
  return formattedResults;
406
418
  }
407
- export async function performSearch(query, maxResults = 10, maxTokensPerPage = 1024, country, serviceOrigin) {
419
+ export async function performSearch(query, maxResults = 10, maxTokensPerPage = 1024, country, filters, serviceOrigin, apiKey) {
408
420
  const body = {
409
421
  query: query,
410
422
  max_results: maxResults,
411
423
  max_tokens_per_page: maxTokensPerPage,
412
424
  ...(country && { country }),
425
+ ...(filters?.search_recency_filter && { search_recency_filter: filters.search_recency_filter }),
426
+ ...(filters?.search_domain_filter && { search_domain_filter: filters.search_domain_filter }),
413
427
  };
414
- const response = await makeApiRequest("search", body, serviceOrigin);
428
+ const response = await makeApiRequest("search", body, serviceOrigin, undefined, apiKey);
415
429
  let data;
416
430
  try {
417
431
  const json = await response.json();
@@ -442,13 +456,13 @@ function buildHooks(extra) {
442
456
  : undefined,
443
457
  };
444
458
  }
445
- export function createPerplexityServer(serviceOrigin) {
459
+ export function createPerplexityServer(serviceOrigin, serverOptions) {
446
460
  const server = new McpServer({
447
461
  name: "ai.perplexity/mcp-server",
448
462
  version: VERSION,
449
463
  }, {
450
464
  instructions: "Perplexity AI server for web-grounded search, research, and reasoning, backed by the Perplexity Agent API. " +
451
- "Use perplexity_search for finding URLs, facts, and recent news. " +
465
+ "Use perplexity_search for finding URLs, facts, and recent news. Supports recency filters and domain restrictions. " +
452
466
  "Use perplexity_ask for quick AI-answered questions with citations. Supports recency filters, domain restrictions, and search context size control. " +
453
467
  "Use perplexity_research for in-depth multi-source investigation (slow, can take minutes). " +
454
468
  "Use perplexity_reason for complex analysis requiring step-by-step logic. Supports recency filters, domain restrictions, and search context size control. " +
@@ -502,7 +516,7 @@ export function createPerplexityServer(serviceOrigin) {
502
516
  ...(search_domain_filter && { search_domain_filter }),
503
517
  ...(search_context_size && { search_context_size }),
504
518
  };
505
- const result = await performAgentResponse(messages, ASK_PRESET, serviceOrigin, Object.keys(options).length > 0 ? options : undefined, buildHooks(extra));
519
+ const result = await performAgentResponse(messages, ASK_PRESET, serviceOrigin, Object.keys(options).length > 0 ? options : undefined, buildHooks(extra), serverOptions?.apiKey);
506
520
  return {
507
521
  content: [{ type: "text", text: result }],
508
522
  structuredContent: { response: result },
@@ -527,7 +541,7 @@ export function createPerplexityServer(serviceOrigin) {
527
541
  }, async (args, extra) => {
528
542
  const { messages } = args;
529
543
  validateMessages(messages, "perplexity_research");
530
- const result = await performAgentResponse(messages, RESEARCH_PRESET, serviceOrigin, undefined, buildHooks(extra));
544
+ const result = await performAgentResponse(messages, RESEARCH_PRESET, serviceOrigin, undefined, buildHooks(extra), serverOptions?.apiKey);
531
545
  return {
532
546
  content: [{ type: "text", text: result }],
533
547
  structuredContent: { response: result },
@@ -557,7 +571,7 @@ export function createPerplexityServer(serviceOrigin) {
557
571
  ...(search_domain_filter && { search_domain_filter }),
558
572
  ...(search_context_size && { search_context_size }),
559
573
  };
560
- const result = await performAgentResponse(messages, REASON_PRESET, serviceOrigin, Object.keys(options).length > 0 ? options : undefined, buildHooks(extra));
574
+ const result = await performAgentResponse(messages, REASON_PRESET, serviceOrigin, Object.keys(options).length > 0 ? options : undefined, buildHooks(extra), serverOptions?.apiKey);
561
575
  return {
562
576
  content: [{ type: "text", text: result }],
563
577
  structuredContent: { response: result },
@@ -571,6 +585,8 @@ export function createPerplexityServer(serviceOrigin) {
571
585
  .describe("Maximum tokens to extract per webpage (default: 1024)"),
572
586
  country: z.string().optional()
573
587
  .describe("ISO 3166-1 alpha-2 country code for regional results (e.g., 'US', 'GB')"),
588
+ search_recency_filter: searchRecencyFilterField,
589
+ search_domain_filter: searchDomainFilterField,
574
590
  };
575
591
  const searchOutputSchema = {
576
592
  results: z.string().describe("Formatted search results, each with title, URL, snippet, and date"),
@@ -580,6 +596,7 @@ export function createPerplexityServer(serviceOrigin) {
580
596
  description: "Search the web and return a ranked list of results with titles, URLs, snippets, and dates. " +
581
597
  "Best for: finding specific URLs, checking recent news, verifying facts, discovering sources. " +
582
598
  "Returns formatted results (title, URL, snippet, date) with no AI synthesis. " +
599
+ "Supports recency filters and domain restrictions. " +
583
600
  "For AI-generated answers with citations, use perplexity_ask instead.",
584
601
  inputSchema: searchInputSchema,
585
602
  outputSchema: searchOutputSchema,
@@ -590,11 +607,15 @@ export function createPerplexityServer(serviceOrigin) {
590
607
  destructiveHint: false,
591
608
  },
592
609
  }, async (args) => {
593
- const { query, max_results, max_tokens_per_page, country } = args;
610
+ const { query, max_results, max_tokens_per_page, country, search_recency_filter, search_domain_filter } = args;
594
611
  const maxResults = typeof max_results === "number" ? max_results : 10;
595
612
  const maxTokensPerPage = typeof max_tokens_per_page === "number" ? max_tokens_per_page : 1024;
596
613
  const countryCode = typeof country === "string" ? country : undefined;
597
- const result = await performSearch(query, maxResults, maxTokensPerPage, countryCode, serviceOrigin);
614
+ const filters = {
615
+ ...(search_recency_filter && { search_recency_filter }),
616
+ ...(search_domain_filter && { search_domain_filter }),
617
+ };
618
+ const result = await performSearch(query, maxResults, maxTokensPerPage, countryCode, filters, serviceOrigin, serverOptions?.apiKey);
598
619
  return {
599
620
  content: [{ type: "text", text: result }],
600
621
  structuredContent: { results: result },
@@ -0,0 +1,108 @@
1
+ import type { ProxyAgent } from "undici";
2
+ export interface Message {
3
+ role: string;
4
+ content: string;
5
+ }
6
+ export interface AgentInputMessage {
7
+ type: "message";
8
+ role: string;
9
+ content: string;
10
+ }
11
+ export interface AgentAnnotation {
12
+ type?: string | null;
13
+ url?: string | null;
14
+ title?: string | null;
15
+ }
16
+ export interface AgentContentPart {
17
+ type: string;
18
+ text?: string | null;
19
+ annotations?: AgentAnnotation[] | null;
20
+ }
21
+ export interface AgentSearchResult {
22
+ id?: number | null;
23
+ url?: string | null;
24
+ title?: string | null;
25
+ snippet?: string | null;
26
+ date?: string | null;
27
+ }
28
+ export interface AgentOutputItem {
29
+ type: string;
30
+ role?: string | null;
31
+ content?: AgentContentPart[] | null;
32
+ results?: AgentSearchResult[] | null;
33
+ }
34
+ export interface AgentCost {
35
+ total_cost?: number;
36
+ currency?: string;
37
+ }
38
+ export interface AgentUsage {
39
+ input_tokens?: number;
40
+ output_tokens?: number;
41
+ total_tokens?: number;
42
+ cost?: AgentCost;
43
+ }
44
+ export interface AgentResponse {
45
+ id?: string | null;
46
+ status?: string | null;
47
+ model?: string | null;
48
+ output: AgentOutputItem[];
49
+ usage?: AgentUsage;
50
+ error?: {
51
+ message?: string | null;
52
+ type?: string | null;
53
+ } | null;
54
+ }
55
+ export interface SearchResult {
56
+ title: string;
57
+ url: string;
58
+ snippet?: string;
59
+ date?: string;
60
+ score?: number;
61
+ }
62
+ export interface SearchUsage {
63
+ tokens?: number;
64
+ }
65
+ export interface SearchResponse {
66
+ results: SearchResult[];
67
+ query?: string;
68
+ usage?: SearchUsage;
69
+ }
70
+ export interface SearchRequestBody {
71
+ query: string;
72
+ max_results: number;
73
+ max_tokens_per_page: number;
74
+ country?: string;
75
+ }
76
+ export interface AgentToolOptions {
77
+ search_recency_filter?: "hour" | "day" | "week" | "month" | "year";
78
+ search_domain_filter?: string[];
79
+ search_context_size?: "low" | "medium" | "high";
80
+ }
81
+ export interface AgentProgressUpdate {
82
+ message: string;
83
+ }
84
+ /**
85
+ * Resolves the API key for an upstream Perplexity API call. Invoked once per
86
+ * request, so a closure over per-request state (e.g. an inbound Authorization
87
+ * header) gives each embedded server instance its own key.
88
+ */
89
+ export type ApiKeyProvider = () => string | undefined;
90
+ export interface PerplexityServerOptions {
91
+ /**
92
+ * Per-call API key resolution for embedders hosting the server for more
93
+ * than one key (multi-tenant). When set, the PERPLEXITY_API_KEY environment
94
+ * variable is never consulted: a provider that returns no key fails the
95
+ * call rather than silently falling back to the process-wide key.
96
+ */
97
+ apiKey?: ApiKeyProvider;
98
+ }
99
+ export interface AgentCallHooks {
100
+ /** Abort signal from the MCP request; triggers server-side cancellation. */
101
+ signal?: AbortSignal;
102
+ /** Called with human-readable progress while the agent run is in flight. */
103
+ onProgress?: (update: AgentProgressUpdate) => void;
104
+ }
105
+ export interface UndiciRequestOptions {
106
+ [key: string]: unknown;
107
+ dispatcher?: ProxyAgent;
108
+ }