# Directory Structure ``` ├── .gitignore ├── CHANGELOG.md ├── dummy ├── index.js ├── index.ts ├── package-lock.json ├── package.json ├── README.md └── tsconfig.json ``` # Files -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` memory-bank/ .clirules node_modules/ build/ ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown # Perplexity AI MCP Server This repository contains the source code for a Model Context Protocol (MCP) server that provides access to the Perplexity AI API. This server allows users to interact with Perplexity AI through various tools, including chatting, searching, and retrieving documentation. ## Purpose This server simplifies the integration of Perplexity AI into MCP-based systems. It provides a convenient and standardized way to access Perplexity AI's capabilities. ## Setup 1. **Install Node.js and npm:** Ensure you have Node.js and npm installed on your system. 2. **Clone the repository:** Clone this repository to your local machine. 3. **Install dependencies:** Navigate to the project directory and run `npm install`. 4. **Configure API Key:** Set the `PERPLEXITY_API_KEY` environment variable to your Perplexity API key. 5. **Run the server:** Run `npm start` to start the server. ## Usage The server exposes several tools that can be accessed through the MCP system. Refer to the MCP documentation for details on how to use these tools. ## Technologies Used * TypeScript * @modelcontextprotocol/sdk * axios ## Known Issues * The Perplexity API may be unreliable. Error handling is included to gracefully handle API failures. ## Contributing Contributions are welcome! Please open an issue or submit a pull request. ``` -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- ```json { "name": "perplexity-server", "version": "0.1.0", "description": "Perplexity AI MCP server", "main": "index.js", "type": "module", "scripts": { "build": "tsc && chmod +x build/index.js", "start": "node build/index.js" }, "dependencies": { "@modelcontextprotocol/sdk": "latest", "axios": "^1.6.0", "os": "^0.1.2", "path": "^0.12.7" }, "devDependencies": { "@types/node": "^20.17.17", "typescript": "^5.0.0" } } ``` -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- ```markdown # Changelog All notable changes to this project will be documented in this file. ## [0.1.0] - 2025-02-12 ### Added * Implemented Perplexity AI MCP server with tools for: * Chatting with Perplexity AI * Searching with Perplexity AI * Getting documentation for technologies, libraries, and APIs * Finding APIs * Checking for deprecated code ### Changed * Updated dependencies. * Improved error handling. * Moved server files from the `perplexity-server` directory to the root directory. ``` -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- ```typescript #!/usr/bin/env node import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, ListToolsRequestSchema, McpError, ErrorCode, } from "@modelcontextprotocol/sdk/types.js"; import axios from "axios"; import { writeFile, readFile } from "node:fs/promises"; import { join } from "path"; import { homedir } from "os"; const PERPLEXITY_API_KEY = process.env.PERPLEXITY_API_KEY; if (!PERPLEXITY_API_KEY) { throw new Error("PERPLEXITY_API_KEY environment variable is required"); } interface ChatMessage { role: "user" | "assistant"; content: string; } interface ChatHistory { [chatId: string]: ChatMessage[]; } class PerplexityServer { private server: Server; private axiosInstance; private chatHistoryFile: string; constructor() { this.server = new Server( { name: "perplexity-server", version: "0.1.0", }, { capabilities: { tools: {}, }, } ); this.axiosInstance = axios.create({ baseURL: "https://api.perplexity.ai", headers: { Authorization: `Bearer ${PERPLEXITY_API_KEY}`, "Content-Type": "application/json", }, }); this.chatHistoryFile = join(homedir(), ".perplexity-mcp", "chat_history.json"); this.setupToolHandlers(); // Error handling this.server.onerror = (error) => console.error("[MCP Error]", error); process.on("SIGINT", async () => { await this.server.close(); process.exit(0); }); } private async getChatHistory(): Promise<ChatHistory> { try { const data = await readFile(this.chatHistoryFile, "utf-8"); return JSON.parse(data); } catch (error: any) { if (error.code === "ENOENT") { // File does not exist, return empty history return {}; } throw error; } } private async saveChatHistory(history: ChatHistory) { await writeFile(this.chatHistoryFile, JSON.stringify(history, null, 2), "utf-8"); } private async getMessagesForChat(chatId: string): Promise<ChatMessage[]> { const history = await this.getChatHistory(); return history[chatId] || []; } private async addMessageToChat(chatId: string, message: ChatMessage) { const history = await this.getChatHistory(); if (!history[chatId]) { history[chatId] = []; } history[chatId].push(message); await this.saveChatHistory(history); } private setupToolHandlers() { this.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ { name: "chat_perplexity", description: "Maintains ongoing conversations with Perplexity AI. Creates new chats or continues existing ones with full history context.", inputSchema: { type: "object", properties: { message: { type: "string", description: "The message to send to Perplexity AI", }, chat_id: { type: "string", description: "Optional: ID of an existing chat to continue. If not provided, a new chat will be created.", }, }, required: ["message"], }, }, { name: "search", description: "Perform a general search query to get comprehensive information on any topic", inputSchema: { type: "object", properties: { query: { type: "string", description: "The search query or question", }, detail_level: { type: "string", description: "Optional: Desired level of detail (brief, normal, detailed)", enum: ["brief", "normal", "detailed"], }, }, required: ["query"], }, }, { name: "get_documentation", description: "Get documentation and usage examples for a specific technology, library, or API", inputSchema: { type: "object", properties: { query: { type: "string", description: "The technology, library, or API to get documentation for", }, context: { type: "string", description: "Additional context or specific aspects to focus on", }, }, required: ["query"], }, }, { name: "find_apis", description: "Find and evaluate APIs that could be integrated into a project", inputSchema: { type: "object", properties: { requirement: { type: "string", description: "The functionality or requirement you're looking to fulfill", }, context: { type: "string", description: "Additional context about the project or specific needs", }, }, required: ["requirement"], }, }, { name: "check_deprecated_code", description: "Check if code or dependencies might be using deprecated features", inputSchema: { type: "object", properties: { code: { type: "string", description: "The code snippet or dependency to check", }, technology: { type: "string", description: "The technology or framework context (e.g., 'React', 'Node.js')", }, }, required: ["code"], }, }, ], })); this.server.setRequestHandler(CallToolRequestSchema, async (request) => { try { switch (request.params.name) { case "chat_perplexity": { const { message, chat_id = crypto.randomUUID() } = request.params.arguments as { message: string; chat_id?: string; }; // Get chat history const history = await this.getMessagesForChat(chat_id); // Add new user message const userMessage: ChatMessage = { role: "user", content: message }; await this.addMessageToChat(chat_id, userMessage); // Prepare messages array with history const messages = [...history, userMessage]; // Call Perplexity API const response = await this.axiosInstance.post("/chat/completions", { model: "sonar-medium-online", messages, }); // Save assistant's response const assistantMessage: ChatMessage = { role: "assistant", content: response.data.choices[0].message.content, }; await this.addMessageToChat(chat_id, assistantMessage); return { content: [ { type: "text", text: JSON.stringify( { chat_id, response: assistantMessage.content, }, null, 2 ), }, ], }; } case "get_documentation": { const { query, context = "" } = request.params.arguments as { query: string; context?: string; }; const response = await this.axiosInstance.post('/search', { query: `documentation ${query} ${context}` }); return { content: [ { type: "text", text: JSON.stringify(response.data, null, 2), }, ], }; } case "search": { const { query, detail_level = "normal" } = request.params.arguments as { query: string; detail_level?: string; }; // Map detail level to model const model = detail_level === "detailed" ? "sonar-reasoning-pro" : // Most expensive, best reasoning detail_level === "brief" ? "sonar" : // Basic, cheapest at $1/$1 "sonar-reasoning"; // Middle ground at $1/$5 // System prompt optimized for Claude const systemPrompt = `You are providing search results to Claude, an AI assistant. Skip unnecessary explanations - Claude can interpret and explain the data itself.`; // Call Perplexity API // Note: max_tokens could be increased for detailed responses, but consider cost implications // sonar-reasoning-pro can use >1000 tokens and does multiple searches console.error('Sending request:', JSON.stringify({ model, messages: [ { role: "system", content: systemPrompt }, { role: "user", content: query } ], max_tokens: 1000, temperature: 0.2, top_p: 0.9 }, null, 2)); const response = await this.axiosInstance.post('/chat/completions', { model, messages: [ { role: "system", content: systemPrompt }, { role: "user", content: query } ], max_tokens: 1000, temperature: 0.2, top_p: 0.9 }); console.error('Got response:', response.data); return { content: [ { type: "text", text: JSON.stringify(response.data, null, 2), }, ], }; } case "find_apis": { const { requirement, context = "" } = request.params .arguments as { requirement: string; context?: string; }; const response = await this.axiosInstance.post('/search', { query: `API for ${requirement} ${context}` }); return { content: [ { type: "text", text: JSON.stringify(response.data, null, 2), }, ], }; } case "check_deprecated_code": { const { code, technology = "" } = request.params.arguments as { code: string; technology?: string; }; const response = await this.axiosInstance.post('/search', { query: `deprecated code ${code} ${technology}` }); return { content: [ { type: "text", text: JSON.stringify(response.data, null, 2), }, ], }; } default: throw new McpError( ErrorCode.MethodNotFound, `Tool not found: ${request.params.name}` ); } } catch (error: any) { console.error("Error calling Perplexity API:", error); throw new McpError( ErrorCode.InternalError, `Perplexity API error: ${error.message}` ); } }); } async run() { const transport = new StdioServerTransport(); await this.server.connect(transport); console.error("Perplexity MCP server running on stdio"); } } const server = new PerplexityServer(); server.run().catch(console.error); ``` -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- ```json { "compilerOptions": { /* Visit https://aka.ms/tsconfig to read more about this file */ /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ /* Language and Environment */ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ // "jsx": "preserve", /* Specify what JSX code is generated. */ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ /* Modules */ "module": "NodeNext", /* Specify what module code is generated. */ // "rootDir": "./", /* Specify the root folder within your source files. */ "moduleResolution": "nodenext", /* Specify how TypeScript looks up a file from a given module specifier. */ "outDir": "build", /* Specify an output folder for all emitted files. */ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ // "types": [], /* Specify type package names to be included without being referenced in a source file. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ // "noUncheckedSideEffectImports": true, /* Check side effect imports. */ // "resolveJsonModule": true, /* Enable importing .json files. */ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */ /* JavaScript Support */ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ /* Emit */ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ // "declarationMap": true, /* Create sourcemaps for d.ts files. */ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ // "noEmit": true, /* Disable emitting files from a compilation. */ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ // "outDir": "./", /* Specify an output folder for all emitted files. */ // "removeComments": true, /* Disable emitting comments. */ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ // "newLine": "crlf", /* Set the newline character for emitting files. */ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ /* Interop Constraints */ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ /* Type Checking */ "strict": true, /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ /* Completeness */ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ "skipLibCheck": true /* Skip type checking all .d.ts files. */ } } ``` -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- ```javascript #!/usr/bin/env node var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, ListToolsRequestSchema, McpError, ErrorCode, } from "@modelcontextprotocol/sdk/types.js"; import axios from "axios"; import { writeFile, readFile } from "node:fs/promises"; import { join } from "path"; import { homedir } from "os"; const PERPLEXITY_API_KEY = process.env.PERPLEXITY_API_KEY; if (!PERPLEXITY_API_KEY) { throw new Error("PERPLEXITY_API_KEY environment variable is required"); } class PerplexityServer { constructor() { this.server = new Server({ name: "perplexity-server", version: "0.1.0", }, { capabilities: { tools: {}, }, }); this.axiosInstance = axios.create({ baseURL: "https://api.perplexity.ai", headers: { Authorization: `Bearer ${PERPLEXITY_API_KEY}`, "Content-Type": "application/json", }, }); this.chatHistoryFile = join(homedir(), ".perplexity-mcp", "chat_history.json"); this.setupToolHandlers(); // Error handling this.server.onerror = (error) => console.error("[MCP Error]", error); process.on("SIGINT", () => __awaiter(this, void 0, void 0, function* () { yield this.server.close(); process.exit(0); })); } getChatHistory() { return __awaiter(this, void 0, void 0, function* () { try { const data = yield readFile(this.chatHistoryFile, "utf-8"); return JSON.parse(data); } catch (error) { if (error.code === "ENOENT") { // File does not exist, return empty history return {}; } throw error; } }); } saveChatHistory(history) { return __awaiter(this, void 0, void 0, function* () { yield writeFile(this.chatHistoryFile, JSON.stringify(history, null, 2), "utf-8"); }); } getMessagesForChat(chatId) { return __awaiter(this, void 0, void 0, function* () { const history = yield this.getChatHistory(); return history[chatId] || []; }); } addMessageToChat(chatId, message) { return __awaiter(this, void 0, void 0, function* () { const history = yield this.getChatHistory(); if (!history[chatId]) { history[chatId] = []; } history[chatId].push(message); yield this.saveChatHistory(history); }); } setupToolHandlers() { this.server.setRequestHandler(ListToolsRequestSchema, () => __awaiter(this, void 0, void 0, function* () { return ({ tools: [ { name: "chat_perplexity", description: "Maintains ongoing conversations with Perplexity AI. Creates new chats or continues existing ones with full history context.", inputSchema: { type: "object", properties: { message: { type: "string", description: "The message to send to Perplexity AI", }, chat_id: { type: "string", description: "Optional: ID of an existing chat to continue. If not provided, a new chat will be created.", }, }, required: ["message"], }, }, { name: "search", description: "Perform a general search query to get comprehensive information on any topic", inputSchema: { type: "object", properties: { query: { type: "string", description: "The search query or question", }, detail_level: { type: "string", description: "Optional: Desired level of detail (brief, normal, detailed)", enum: ["brief", "normal", "detailed"], }, }, required: ["query"], }, }, { name: "get_documentation", description: "Get documentation and usage examples for a specific technology, library, or API", inputSchema: { type: "object", properties: { query: { type: "string", description: "The technology, library, or API to get documentation for", }, context: { type: "string", description: "Additional context or specific aspects to focus on", }, }, required: ["query"], }, }, { name: "find_apis", description: "Find and evaluate APIs that could be integrated into a project", inputSchema: { type: "object", properties: { requirement: { type: "string", description: "The functionality or requirement you're looking to fulfill", }, context: { type: "string", description: "Additional context about the project or specific needs", }, }, required: ["requirement"], }, }, { name: "check_deprecated_code", description: "Check if code or dependencies might be using deprecated features", inputSchema: { type: "object", properties: { code: { type: "string", description: "The code snippet or dependency to check", }, technology: { type: "string", description: "The technology or framework context (e.g., 'React', 'Node.js')", }, }, required: ["code"], }, }, ], }); })); this.server.setRequestHandler(CallToolRequestSchema, (request) => __awaiter(this, void 0, void 0, function* () { try { switch (request.params.name) { case "chat_perplexity": { const { message, chat_id = crypto.randomUUID() } = request.params.arguments; // Get chat history const history = yield this.getMessagesForChat(chat_id); // Add new user message const userMessage = { role: "user", content: message }; yield this.addMessageToChat(chat_id, userMessage); // Prepare messages array with history const messages = [...history, userMessage]; // Call Perplexity API const response = yield this.axiosInstance.post("/chat/completions", { model: "sonar-reasoning-pro", messages, }); // Save assistant's response const assistantMessage = { role: "assistant", content: response.data.choices[0].message.content, }; yield this.addMessageToChat(chat_id, assistantMessage); return { content: [ { type: "text", text: JSON.stringify({ chat_id, response: assistantMessage.content, }, null, 2), }, ], }; } case "get_documentation": { const { query, context = "" } = request.params.arguments; const response = yield this.axiosInstance.get(`/search?q=documentation ${query} ${context}`); return { content: [ { type: "text", text: JSON.stringify(response.data, null, 2), }, ], }; } case "search": { const { query, detail_level = "normal" } = request.params.arguments; const response = yield this.axiosInstance.get(`/search?q=${query}&details=${detail_level}`); return { content: [ { type: "text", text: JSON.stringify(response.data, null, 2), }, ], }; } case "find_apis": { const { requirement, context = "" } = request.params .arguments; const response = yield this.axiosInstance.get(`/search?q=API for ${requirement} ${context}`); return { content: [ { type: "text", text: JSON.stringify(response.data, null, 2), }, ], }; } case "check_deprecated_code": { const { code, technology = "" } = request.params.arguments; const response = yield this.axiosInstance.get(`/search?q=deprecated code ${code} ${technology}`); return { content: [ { type: "text", text: JSON.stringify(response.data, null, 2), }, ], }; } default: throw new McpError(ErrorCode.MethodNotFound, `Tool not found: ${request.params.name}`); } } catch (error) { console.error("Error calling Perplexity API:", error); throw new McpError(ErrorCode.InternalError, `Perplexity API error: ${error.message}`); } })); } run() { return __awaiter(this, void 0, void 0, function* () { const transport = new StdioServerTransport(); yield this.server.connect(transport); console.error("Perplexity MCP server running on stdio"); }); } } const server = new PerplexityServer(); server.run().catch(console.error); ```