@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.
Files changed (143) hide show
  1. package/.claude-plugin/marketplace.json +49 -0
  2. package/LICENSE +21 -201
  3. package/README.md +105 -157
  4. package/dist/http.d.ts +15 -0
  5. package/dist/http.js +190 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/index.js +23 -0
  8. package/dist/logger.d.ts +19 -0
  9. package/dist/logger.js +82 -0
  10. package/dist/server.d.ts +61 -0
  11. package/dist/server.js +613 -0
  12. package/dist/types.d.ts +93 -0
  13. package/dist/types.js +1 -0
  14. package/dist/validation.d.ts +1063 -0
  15. package/dist/validation.js +62 -0
  16. package/package.json +67 -155
  17. package/compat.d.mts +0 -58
  18. package/compat.d.mts.map +0 -1
  19. package/compat.d.ts +0 -58
  20. package/compat.d.ts.map +0 -1
  21. package/compat.js +0 -387
  22. package/compat.js.map +0 -1
  23. package/compat.mjs +0 -378
  24. package/compat.mjs.map +0 -1
  25. package/dynamic-tools.d.mts +0 -12
  26. package/dynamic-tools.d.mts.map +0 -1
  27. package/dynamic-tools.d.ts +0 -12
  28. package/dynamic-tools.d.ts.map +0 -1
  29. package/dynamic-tools.js +0 -135
  30. package/dynamic-tools.js.map +0 -1
  31. package/dynamic-tools.mjs +0 -132
  32. package/dynamic-tools.mjs.map +0 -1
  33. package/filtering.d.mts +0 -2
  34. package/filtering.d.mts.map +0 -1
  35. package/filtering.d.ts +0 -2
  36. package/filtering.d.ts.map +0 -1
  37. package/filtering.js +0 -20
  38. package/filtering.js.map +0 -1
  39. package/filtering.mjs +0 -13
  40. package/filtering.mjs.map +0 -1
  41. package/headers.d.mts +0 -4
  42. package/headers.d.mts.map +0 -1
  43. package/headers.d.ts +0 -4
  44. package/headers.d.ts.map +0 -1
  45. package/headers.js +0 -22
  46. package/headers.js.map +0 -1
  47. package/headers.mjs +0 -18
  48. package/headers.mjs.map +0 -1
  49. package/http.d.mts +0 -9
  50. package/http.d.mts.map +0 -1
  51. package/http.d.ts +0 -9
  52. package/http.d.ts.map +0 -1
  53. package/http.js +0 -108
  54. package/http.js.map +0 -1
  55. package/http.mjs +0 -100
  56. package/http.mjs.map +0 -1
  57. package/index.d.mts +0 -3
  58. package/index.d.mts.map +0 -1
  59. package/index.d.ts +0 -3
  60. package/index.d.ts.map +0 -1
  61. package/index.js +0 -91
  62. package/index.js.map +0 -1
  63. package/index.mjs +0 -89
  64. package/index.mjs.map +0 -1
  65. package/options.d.mts +0 -18
  66. package/options.d.mts.map +0 -1
  67. package/options.d.ts +0 -18
  68. package/options.d.ts.map +0 -1
  69. package/options.js +0 -415
  70. package/options.js.map +0 -1
  71. package/options.mjs +0 -408
  72. package/options.mjs.map +0 -1
  73. package/server.d.mts +0 -35
  74. package/server.d.mts.map +0 -1
  75. package/server.d.ts +0 -35
  76. package/server.d.ts.map +0 -1
  77. package/server.js +0 -166
  78. package/server.js.map +0 -1
  79. package/server.mjs +0 -152
  80. package/server.mjs.map +0 -1
  81. package/src/compat.ts +0 -483
  82. package/src/dynamic-tools.ts +0 -159
  83. package/src/filtering.ts +0 -14
  84. package/src/headers.ts +0 -23
  85. package/src/http.ts +0 -127
  86. package/src/index.ts +0 -108
  87. package/src/options.ts +0 -453
  88. package/src/server.ts +0 -201
  89. package/src/stdio.ts +0 -13
  90. package/src/tools/chat/completions/create-chat-completions.ts +0 -1323
  91. package/src/tools/index.ts +0 -73
  92. package/src/tools/search/create-search.ts +0 -89
  93. package/src/tools/types.ts +0 -103
  94. package/src/tools.ts +0 -1
  95. package/src/tsconfig.json +0 -11
  96. package/stdio.d.mts +0 -3
  97. package/stdio.d.mts.map +0 -1
  98. package/stdio.d.ts +0 -3
  99. package/stdio.d.ts.map +0 -1
  100. package/stdio.js +0 -14
  101. package/stdio.js.map +0 -1
  102. package/stdio.mjs +0 -10
  103. package/stdio.mjs.map +0 -1
  104. package/tools/chat/completions/create-chat-completions.d.mts +0 -45
  105. package/tools/chat/completions/create-chat-completions.d.mts.map +0 -1
  106. package/tools/chat/completions/create-chat-completions.d.ts +0 -45
  107. package/tools/chat/completions/create-chat-completions.d.ts.map +0 -1
  108. package/tools/chat/completions/create-chat-completions.js +0 -1320
  109. package/tools/chat/completions/create-chat-completions.js.map +0 -1
  110. package/tools/chat/completions/create-chat-completions.mjs +0 -1316
  111. package/tools/chat/completions/create-chat-completions.mjs.map +0 -1
  112. package/tools/index.d.mts +0 -10
  113. package/tools/index.d.mts.map +0 -1
  114. package/tools/index.d.ts +0 -10
  115. package/tools/index.d.ts.map +0 -1
  116. package/tools/index.js +0 -57
  117. package/tools/index.js.map +0 -1
  118. package/tools/index.mjs +0 -50
  119. package/tools/index.mjs.map +0 -1
  120. package/tools/search/create-search.d.mts +0 -45
  121. package/tools/search/create-search.d.mts.map +0 -1
  122. package/tools/search/create-search.d.ts +0 -45
  123. package/tools/search/create-search.d.ts.map +0 -1
  124. package/tools/search/create-search.js +0 -86
  125. package/tools/search/create-search.js.map +0 -1
  126. package/tools/search/create-search.mjs +0 -82
  127. package/tools/search/create-search.mjs.map +0 -1
  128. package/tools/types.d.mts +0 -51
  129. package/tools/types.d.mts.map +0 -1
  130. package/tools/types.d.ts +0 -51
  131. package/tools/types.d.ts.map +0 -1
  132. package/tools/types.js +0 -46
  133. package/tools/types.js.map +0 -1
  134. package/tools/types.mjs +0 -42
  135. package/tools/types.mjs.map +0 -1
  136. package/tools.d.mts +0 -2
  137. package/tools.d.mts.map +0 -1
  138. package/tools.d.ts +0 -2
  139. package/tools.d.ts.map +0 -1
  140. package/tools.js +0 -18
  141. package/tools.js.map +0 -1
  142. package/tools.mjs +0 -2
  143. package/tools.mjs.map +0 -1
package/dist/http.js ADDED
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env node
2
+ import express from "express";
3
+ import cors from "cors";
4
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
5
+ import { createPerplexityServer } from "./server.js";
6
+ import { logger } from "./logger.js";
7
+ /**
8
+ * Build the Express app for the HTTP transport. Exported so tests can
9
+ * exercise the same wiring used in production.
10
+ */
11
+ export function createHttpApp(options) {
12
+ const { port, bindAddress, allowedOrigins, allowedHosts } = options;
13
+ const allowsAllOrigins = allowedOrigins.includes("*");
14
+ // One-shot startup banners. Written directly to stderr (bypassing the
15
+ // level-gated logger) so they are visible at the default log level.
16
+ if (bindAddress === "0.0.0.0" || bindAddress === "::") {
17
+ console.error(`[mcp-server] BIND_ADDRESS=${bindAddress} exposes the server on all ` +
18
+ `network interfaces. See SECURITY.md.`);
19
+ }
20
+ if (allowsAllOrigins) {
21
+ console.error(`[mcp-server] ALLOWED_ORIGINS contains "*". See SECURITY.md.`);
22
+ }
23
+ const app = express();
24
+ // Host header allowlist. Runs before CORS.
25
+ app.use((req, res, next) => {
26
+ const hostHeader = req.headers.host;
27
+ if (!hostHeader || !allowedHosts.has(hostHeader.toLowerCase())) {
28
+ logger.warn("Rejected request with disallowed Host header", {
29
+ host: hostHeader,
30
+ path: req.path,
31
+ });
32
+ res.status(421).json({
33
+ jsonrpc: "2.0",
34
+ error: { code: -32000, message: "Misdirected request" },
35
+ id: null,
36
+ });
37
+ return;
38
+ }
39
+ next();
40
+ });
41
+ // Sentinel error type so the CORS error handler can distinguish disallowed-
42
+ // origin rejections from other downstream errors.
43
+ class CorsOriginNotAllowedError extends Error {
44
+ constructor(origin) {
45
+ super(`Origin ${origin} not allowed by CORS`);
46
+ this.origin = origin;
47
+ this.name = "CorsOriginNotAllowedError";
48
+ }
49
+ }
50
+ // CORS configuration for browser-based MCP clients.
51
+ // - A missing Origin header (same-origin or non-browser caller) is allowed.
52
+ // - A literal "null" Origin requires explicit opt-in via ALLOWED_ORIGINS.
53
+ // - "*" in ALLOWED_ORIGINS is honored but logs a startup warning.
54
+ app.use(cors({
55
+ origin: (origin, callback) => {
56
+ if (!origin)
57
+ return callback(null, true);
58
+ if (origin === "null") {
59
+ if (allowedOrigins.includes("null")) {
60
+ return callback(null, true);
61
+ }
62
+ return callback(new CorsOriginNotAllowedError("null"));
63
+ }
64
+ if (allowsAllOrigins) {
65
+ return callback(null, true);
66
+ }
67
+ if (allowedOrigins.includes(origin)) {
68
+ return callback(null, true);
69
+ }
70
+ return callback(new CorsOriginNotAllowedError(origin));
71
+ },
72
+ exposedHeaders: ["Mcp-Session-Id", "mcp-protocol-version"],
73
+ allowedHeaders: ["Content-Type", "mcp-session-id"],
74
+ }));
75
+ // Translate CORS origin-rejection errors into an explicit 403 with a
76
+ // JSON-RPC error body, mirroring the 421 emitted by the Host check. This
77
+ // runs immediately after the cors middleware so other errors still fall
78
+ // through to Express's default handler unchanged.
79
+ app.use((err, req, res, next) => {
80
+ if (err instanceof CorsOriginNotAllowedError) {
81
+ logger.warn("Rejected request with disallowed Origin", {
82
+ origin: err.origin,
83
+ path: req.path,
84
+ });
85
+ res.status(403).json({
86
+ jsonrpc: "2.0",
87
+ error: { code: -32000, message: "Origin not allowed" },
88
+ id: null,
89
+ });
90
+ return;
91
+ }
92
+ next(err);
93
+ });
94
+ app.use(express.json());
95
+ app.all("/mcp", async (req, res) => {
96
+ try {
97
+ // Stateless mode: a Protocol instance supports one transport, so build
98
+ // a fresh server + transport pair per request.
99
+ const transport = new StreamableHTTPServerTransport({
100
+ sessionIdGenerator: undefined,
101
+ enableJsonResponse: true,
102
+ });
103
+ const mcpServer = createPerplexityServer();
104
+ res.on("close", () => {
105
+ transport.close();
106
+ mcpServer.close();
107
+ });
108
+ await mcpServer.connect(transport);
109
+ await transport.handleRequest(req, res, req.body);
110
+ }
111
+ catch (error) {
112
+ logger.error("Error handling MCP request", { error: String(error) });
113
+ if (!res.headersSent) {
114
+ res.status(500).json({
115
+ jsonrpc: "2.0",
116
+ error: { code: -32603, message: "Internal server error" },
117
+ id: null,
118
+ });
119
+ }
120
+ }
121
+ });
122
+ app.get("/health", (req, res) => {
123
+ res.json({ status: "ok", service: "perplexity-mcp-server" });
124
+ });
125
+ // Mark the port as used so a no-op consumer doesn't make TS unhappy if PORT
126
+ // is only consumed by the listener in main().
127
+ void port;
128
+ return app;
129
+ }
130
+ /** Parse a comma-separated env var into a trimmed, non-empty string list. */
131
+ function parseList(value) {
132
+ if (!value)
133
+ return [];
134
+ return value
135
+ .split(",")
136
+ .map((v) => v.trim())
137
+ .filter((v) => v.length > 0);
138
+ }
139
+ /** Build the Host header allowlist from PORT + ALLOWED_HOSTS. */
140
+ export function buildAllowedHosts(port, extra) {
141
+ return new Set([
142
+ `localhost:${port}`,
143
+ `127.0.0.1:${port}`,
144
+ `[::1]:${port}`,
145
+ "localhost",
146
+ "127.0.0.1",
147
+ "[::1]",
148
+ ...extra,
149
+ ].map((h) => h.toLowerCase()));
150
+ }
151
+ function main() {
152
+ const PERPLEXITY_API_KEY = process.env.PERPLEXITY_API_KEY;
153
+ if (!PERPLEXITY_API_KEY) {
154
+ logger.error("PERPLEXITY_API_KEY environment variable is required");
155
+ process.exit(1);
156
+ }
157
+ const PORT = parseInt(process.env.PORT || "8080", 10);
158
+ // Defaults are loopback-only with no allowed cross-origin browsers.
159
+ // Set BIND_ADDRESS and ALLOWED_ORIGINS to opt in to remote / browser access.
160
+ // See SECURITY.md.
161
+ const BIND_ADDRESS = process.env.BIND_ADDRESS || "127.0.0.1";
162
+ const ALLOWED_ORIGINS = parseList(process.env.ALLOWED_ORIGINS);
163
+ const ALLOWED_HOSTS = buildAllowedHosts(PORT, parseList(process.env.ALLOWED_HOSTS));
164
+ const app = createHttpApp({
165
+ port: PORT,
166
+ bindAddress: BIND_ADDRESS,
167
+ allowedOrigins: ALLOWED_ORIGINS,
168
+ allowedHosts: ALLOWED_HOSTS,
169
+ });
170
+ app
171
+ .listen(PORT, BIND_ADDRESS, () => {
172
+ // Startup banner — written directly to stderr so it is visible at the
173
+ // default log level.
174
+ console.error(`[mcp-server] listening on http://${BIND_ADDRESS}:${PORT}/mcp`);
175
+ console.error(`[mcp-server] allowed origins: ${ALLOWED_ORIGINS.length > 0
176
+ ? ALLOWED_ORIGINS.join(", ")
177
+ : "(none — cross-origin browser requests will be rejected)"}`);
178
+ })
179
+ .on("error", (error) => {
180
+ logger.error("Server error", { error: String(error) });
181
+ process.exit(1);
182
+ });
183
+ }
184
+ // Only auto-start when invoked as a script (preserves test importability).
185
+ const invokedAsScript = import.meta.url === `file://${process.argv[1]}` ||
186
+ process.argv[1]?.endsWith("/http.js") ||
187
+ process.argv[1]?.endsWith("/http.ts");
188
+ if (invokedAsScript) {
189
+ main();
190
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { createPerplexityServer } from "./server.js";
4
+ const PERPLEXITY_API_KEY = process.env.PERPLEXITY_API_KEY;
5
+ if (!PERPLEXITY_API_KEY) {
6
+ console.error("Error: PERPLEXITY_API_KEY environment variable is required");
7
+ process.exit(1);
8
+ }
9
+ async function main() {
10
+ try {
11
+ const server = createPerplexityServer("local-mcp");
12
+ const transport = new StdioServerTransport();
13
+ await server.connect(transport);
14
+ }
15
+ catch (error) {
16
+ console.error("Fatal error running server:", error);
17
+ process.exit(1);
18
+ }
19
+ }
20
+ main().catch((error) => {
21
+ console.error("Fatal error running server:", error);
22
+ process.exit(1);
23
+ });
@@ -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
+ };
package/dist/logger.js ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Simple structured logger for the Perplexity MCP Server
3
+ * Outputs to stderr to avoid interfering with STDIO transport
4
+ */
5
+ export var LogLevel;
6
+ (function (LogLevel) {
7
+ LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
8
+ LogLevel[LogLevel["INFO"] = 1] = "INFO";
9
+ LogLevel[LogLevel["WARN"] = 2] = "WARN";
10
+ LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
11
+ })(LogLevel || (LogLevel = {}));
12
+ const LOG_LEVEL_NAMES = {
13
+ [LogLevel.DEBUG]: "DEBUG",
14
+ [LogLevel.INFO]: "INFO",
15
+ [LogLevel.WARN]: "WARN",
16
+ [LogLevel.ERROR]: "ERROR",
17
+ };
18
+ /**
19
+ * Gets the configured log level from environment variable
20
+ * Defaults to ERROR to minimize noise in production
21
+ */
22
+ function getLogLevel() {
23
+ const level = process.env.PERPLEXITY_LOG_LEVEL?.toUpperCase();
24
+ switch (level) {
25
+ case "DEBUG":
26
+ return LogLevel.DEBUG;
27
+ case "INFO":
28
+ return LogLevel.INFO;
29
+ case "WARN":
30
+ return LogLevel.WARN;
31
+ case "ERROR":
32
+ return LogLevel.ERROR;
33
+ default:
34
+ return LogLevel.ERROR;
35
+ }
36
+ }
37
+ const currentLogLevel = getLogLevel();
38
+ function safeStringify(obj) {
39
+ try {
40
+ return JSON.stringify(obj);
41
+ }
42
+ catch {
43
+ return "[Unstringifiable]";
44
+ }
45
+ }
46
+ /**
47
+ * Formats a log message with timestamp and level
48
+ */
49
+ function formatMessage(level, message, meta) {
50
+ const timestamp = new Date().toISOString();
51
+ const levelName = LOG_LEVEL_NAMES[level];
52
+ if (meta && Object.keys(meta).length > 0) {
53
+ return `[${timestamp}] ${levelName}: ${message} ${safeStringify(meta)}`;
54
+ }
55
+ return `[${timestamp}] ${levelName}: ${message}`;
56
+ }
57
+ /**
58
+ * Logs a message if the configured log level allows it
59
+ */
60
+ function log(level, message, meta) {
61
+ if (level >= currentLogLevel) {
62
+ const formatted = formatMessage(level, message, meta);
63
+ console.error(formatted); // Use stderr to avoid interfering with STDIO
64
+ }
65
+ }
66
+ /**
67
+ * Structured logger interface
68
+ */
69
+ export const logger = {
70
+ debug(message, meta) {
71
+ log(LogLevel.DEBUG, message, meta);
72
+ },
73
+ info(message, meta) {
74
+ log(LogLevel.INFO, message, meta);
75
+ },
76
+ warn(message, meta) {
77
+ log(LogLevel.WARN, message, meta);
78
+ },
79
+ error(message, meta) {
80
+ log(LogLevel.ERROR, message, meta);
81
+ },
82
+ };
@@ -0,0 +1,61 @@
1
+ import type { Message, AgentResponse, AgentToolOptions, AgentCallHooks, SearchResponse } from "./types.js";
2
+ export declare const ASK_PRESET = "fast";
3
+ export declare const REASON_PRESET = "medium";
4
+ export declare const RESEARCH_PRESET = "high";
5
+ export declare function getProxyUrl(): string | undefined;
6
+ export declare function proxyAwareFetch(url: string, options?: RequestInit): Promise<Response>;
7
+ export declare function validateMessages(messages: unknown, toolName: string): asserts messages is Message[];
8
+ /** Best-effort cancellation of an agent run so an abandoned request stops billing. */
9
+ export declare function cancelAgentResponse(responseId: string, serviceOrigin?: string): Promise<void>;
10
+ /**
11
+ * Consume an Agent API SSE stream and return the final response object.
12
+ * Emits progress via hooks.onProgress as reasoning events arrive.
13
+ */
14
+ export declare function consumeAgentStream(response: Response, hooks?: AgentCallHooks, serviceOrigin?: string, deadlineSignal?: AbortSignal): Promise<AgentResponse>;
15
+ export declare function extractAgentText(response: AgentResponse): string;
16
+ /**
17
+ * Append the "Citations:" block ("[n] url" lines) to the answer text, keyed
18
+ * by the numeric search-result ids that inline references point at. The
19
+ * answer body is never modified: bracketed tokens also appear in code, LaTeX,
20
+ * and slice syntax, so any rewrite risks corrupting the answer. If ids are
21
+ * missing or ambiguous, all unique source URLs are appended with positional
22
+ * numbering instead.
23
+ */
24
+ export declare function formatAgentResponseText(response: AgentResponse): string;
25
+ export declare function performAgentResponse(messages: Message[], preset: string, serviceOrigin?: string, options?: AgentToolOptions, hooks?: AgentCallHooks): Promise<string>;
26
+ export declare function formatSearchResults(data: SearchResponse): string;
27
+ export declare function performSearch(query: string, maxResults?: number, maxTokensPerPage?: number, country?: string, filters?: Pick<AgentToolOptions, "search_recency_filter" | "search_domain_filter">, serviceOrigin?: string): Promise<string>;
28
+ export declare function createPerplexityServer(serviceOrigin?: string): import("@modelcontextprotocol/sdk/server/index.js").Server<{
29
+ method: string;
30
+ params?: {
31
+ [x: string]: unknown;
32
+ _meta?: {
33
+ [x: string]: unknown;
34
+ progressToken?: string | number | undefined;
35
+ "io.modelcontextprotocol/related-task"?: {
36
+ taskId: string;
37
+ } | undefined;
38
+ } | undefined;
39
+ } | undefined;
40
+ }, {
41
+ method: string;
42
+ params?: {
43
+ [x: string]: unknown;
44
+ _meta?: {
45
+ [x: string]: unknown;
46
+ progressToken?: string | number | undefined;
47
+ "io.modelcontextprotocol/related-task"?: {
48
+ taskId: string;
49
+ } | undefined;
50
+ } | undefined;
51
+ } | undefined;
52
+ }, {
53
+ [x: string]: unknown;
54
+ _meta?: {
55
+ [x: string]: unknown;
56
+ progressToken?: string | number | undefined;
57
+ "io.modelcontextprotocol/related-task"?: {
58
+ taskId: string;
59
+ } | undefined;
60
+ } | undefined;
61
+ }>;