How to connect Perplexityai to Mastra AI in 2 mins: No API key needed

Composio runs each call on its own Perplexityai account, so you don't need a Perplexityai API key, and your first $2 is free.

Perplexityai logoPerplexityai
Api Key

Perplexityai delivers natural, conversational AI models for generating human-like text. Instantly get context-aware, high-quality responses for chat, search, or complex workflows.

28 Tools
Composio Instant

What you can do with your free $2

You pay Perplexityai's price for each call with 0% markup, plus the regular Composio tool call charge. There's no Perplexityai subscription, and you only pay for what you use.

5 of 28 Perplexityai tools work without a key. For Cancel Agent Response, Create Async Chat Completion, Create Orchestrator Chat Completion, Create Orchestrator Message, CreateOrchestratorResponse, Create Skill and 17 more, connect your own Perplexityai key. Read how Instant works.

How it works

How to connect Perplexityai to Mastra AI

Composio adds Perplexityai to Mastra AI as an Instant toolkit. You connect Composio to Mastra AI once, and then Mastra AI can use Perplexityai right away. There are two ways to do this:

  • Bring your own key

    You bring your own Perplexityai API key, set it up, and use it.

  • Use the Composio wallet

    Instant

    Composio runs each call on its own Perplexityai account, so you don't have to set anything up at Perplexityai, and your first $2 is free.

You do the setup one time and it takes about a minute. If you build Perplexityai into your own product, turn on Instant toolkits in your project settings so your agent can call Perplexityai for each of your users without a Perplexityai API key, and read Instant tools in the Composio docs for the setup steps and code examples.

Get started

Start to use Perplexityai in Mastra AI in 3 steps

  1. Turn on Instant

    Open your Composio wallet and turn on Instant. Your free $2 shows up there.

  2. Add Composio to Mastra AI

    Follow the setup below. You only do this once.

  3. Ask Mastra AI for something

    Try a Perplexityai prompt. The cost comes out of your $2.

Setup

Step-by-step Guide

Step by step09 STEPS
1

Prerequisites

Before starting, make sure you have:
  • Node.js 18 or higher
  • A Composio account with an active API key
  • An OpenAI API key
  • Basic familiarity with TypeScript
2

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key.
  • You need credits or a connected billing setup to use the models.
  • Store the key somewhere safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Go to Settings and copy your API key.
  • This key lets your Mastra agent talk to Composio and reach Perplexityai through MCP.
3

Install dependencies

bash
npm install @composio/core @mastra/core @mastra/mcp @ai-sdk/openai dotenv

Install the required packages.

What's happening:

  • @composio/core is the Composio SDK for creating MCP sessions
  • @mastra/core provides the Agent class
  • @mastra/mcp is Mastra's MCP client
  • @ai-sdk/openai is the model wrapper for OpenAI
  • dotenv loads environment variables from .env
4

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key_here

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your requests to Composio
  • COMPOSIO_USER_ID tells Composio which user this session belongs to
  • OPENAI_API_KEY lets the Mastra agent call OpenAI models
5

Import libraries and validate environment

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

const openaiAPIKey = process.env.OPENAI_API_KEY;
const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!openaiAPIKey) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey as string,
});
What's happening:
  • dotenv/config auto loads your .env so process.env.* is available
  • openai gives you a Mastra compatible model wrapper
  • Agent is the Mastra agent that will call tools and produce answers
  • MCPClient connects Mastra to your Composio MCP server
  • Composio is used to create a Tool Router session
6

Create a Tool Router session for Perplexityai

typescript
async function main() {
  const session = await composio.create(
    composioUserID as string,
    {
      toolkits: ["perplexityai"],
    },
  );

  const composioMCPUrl = session.mcp.url;
  console.log("Perplexityai MCP URL:", composioMCPUrl);
What's happening:
  • create spins up a short-lived MCP HTTP endpoint for this user
  • The toolkits array contains "perplexityai" for Perplexityai access
  • session.mcp.url is the MCP URL that Mastra's MCPClient will connect to
7

Configure Mastra MCP client and fetch tools

typescript
const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      nasdaq: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

console.log("Fetching MCP tools from Composio...");
const composioTools = await mcpClient.getTools();
console.log("Number of tools:", Object.keys(composioTools).length);
What's happening:
  • MCPClient takes an id for this client and a list of MCP servers
  • The headers property includes the x-api-key for authentication
  • getTools fetches the tool definitions exposed by the Perplexityai toolkit
8

Create the Mastra agent

typescript
const agent = new Agent({
    name: "perplexityai-mastra-agent",
    instructions: "You are an AI agent with Perplexityai tools via Composio.",
    model: "openai/gpt-5",
  });
What's happening:
  • Agent is the core Mastra agent
  • name is just an identifier for logging and debugging
  • instructions guide the agent to use tools instead of only answering in natural language
  • model uses openai("gpt-5") to configure the underlying LLM
9

Set up interactive chat interface

typescript
let messages: AiMessageType[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end.\n");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: "> ",
});

rl.prompt();

rl.on("line", async (userInput: string) => {
  const trimmedInput = userInput.trim();

  if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
    console.log("\nGoodbye!");
    rl.close();
    process.exit(0);
  }

  if (!trimmedInput) {
    rl.prompt();
    return;
  }

  messages.push({
    id: crypto.randomUUID(),
    role: "user",
    content: trimmedInput,
  });

  console.log("\nAgent is thinking...\n");

  try {
    const response = await agent.generate(messages, {
      toolsets: {
        perplexityai: composioTools,
      },
      maxSteps: 8,
    });

    const { text } = response;

    if (text && text.trim().length > 0) {
      console.log(`Agent: ${text}\n`);
        messages.push({
          id: crypto.randomUUID(),
          role: "assistant",
          content: text,
        });
      }
    } catch (error) {
      console.error("\nError:", error);
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    console.log("\nSession ended.");
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
What's happening:
  • messages keeps the full conversation history in Mastra's expected format
  • agent.generate runs the agent with conversation history and Perplexityai toolsets
  • maxSteps limits how many tool calls the agent can take in a single run
  • onStepFinish is a hook that prints intermediate steps for debugging

Complete Code

Here's the complete code to get you started with Perplexityai and Mastra AI:

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

const openaiAPIKey = process.env.OPENAI_API_KEY;
const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!openaiAPIKey) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({ apiKey: composioAPIKey as string });

async function main() {
  const session = await composio.create(composioUserID as string, {
    toolkits: ["perplexityai"],
  });

  const composioMCPUrl = session.mcp.url;

  const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      perplexityai: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

  const composioTools = await mcpClient.getTools();

  const agent = new Agent({
    name: "perplexityai-mastra-agent",
    instructions: "You are an AI agent with Perplexityai tools via Composio.",
    model: "openai/gpt-5",
  });

  let messages: AiMessageType[] = [];

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: "> ",
  });

  rl.prompt();

  rl.on("line", async (input: string) => {
    const trimmed = input.trim();
    if (["exit", "quit"].includes(trimmed.toLowerCase())) {
      rl.close();
      return;
    }

    messages.push({ id: crypto.randomUUID(), role: "user", content: trimmed });

    const { text } = await agent.generate(messages, {
      toolsets: { perplexityai: composioTools },
      maxSteps: 8,
    });

    if (text) {
      console.log(`Agent: ${text}\n`);
      messages.push({ id: crypto.randomUUID(), role: "assistant", content: text });
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main();
Try it

Ask Mastra AI for something with Perplexityai

Mastra AI runs it on Instant and shows you the result. It doesn't ask you for a Perplexityai key, and the cost comes out of your $2. You can see each call in your wallet.

Optional: connect your own Perplexityai key

If you want Cancel Agent Response, Create Async Chat Completion, Create Orchestrator Chat Completion, Create Orchestrator Message, CreateOrchestratorResponse, Create Skill and 17 more, you need your own key. Ask Mastra AI to connect your Perplexityai account, and it gives you a Composio link:

Connect my Perplexityai account using Composio.

Open the link, paste your Perplexityai API key and click Connect Account. After that, Composio uses your key first and doesn't charge Instant for those calls.

What it can do

What Mastra AI can do with Perplexityai

Works without a key

  • Create Chat Completion
  • Create Contextualized Embeddings
  • CreateEmbeddings
  • Execute Agent
  • Perplexity Search (Raw Results)

Needs your own Perplexityai key

  • Cancel Agent Response
  • Create Async Chat Completion
  • Create Orchestrator Chat Completion
  • Create Orchestrator Message
  • CreateOrchestratorResponse
  • Create Skill
  • Delete Skill
  • Download Agent Response File
  • and 15 more
Tools and prices

Supported tools (28)

Perplexityai tools and their Instant prices
ToolWhat it doesWorks without a keyCost on Instant
Create Chat CompletionGenerate a chat-compatible response from conversation messages, with optional search controls.YesFrom $0.10 per 1M input tokens plus $0.0025 per web search
Create Contextualized EmbeddingsCreate Contextualized Embeddings (POST /v1/contextualizedembeddings).Yes$0.008–$0.05 per 1M tokens, by embedding model
CreateEmbeddingsGenerate vector embeddings for independent texts (queries, sentences, documents).Yes$0.004–$0.03 per 1M tokens, by embedding model
Execute AgentCreate Agent Response (POST /v1/agent).YesFrom $0.10 per 1M input tokens plus $0.0025 per web search
Perplexity Search (Raw Results)Search the Web (POST /search).Yes$5 per 1,000 searches
Cancel Agent ResponseRequest cancellation of an existing durable agent response.Needs your own keyBilled to your own Perplexityai key
Create Async Chat CompletionCreate Async Chat Completion (POST /v1/async/sonar).Needs your own keyBilled to your own Perplexityai key
Create Orchestrator Chat CompletionCreate a non-streaming OpenAI-compatible chat completion using a cataloged Orchestrator model.Needs your own keyBilled to your own Perplexityai key
Create Orchestrator MessageCreate a non-streaming Anthropic-compatible message using an Orchestrator catalog model.Needs your own keyBilled to your own Perplexityai key
CreateOrchestratorResponseGenerate a non-streaming model response through the Perplexity Orchestrator using a creator/model-name catalog ID, input text or structured items, optional tools, and structured output settings.Needs your own keyBilled to your own Perplexityai key
Create SkillCreate a Project-owned skill from a ZIP bundle containing SKILL.md.Needs your own keyBilled to your own Perplexityai key
Delete SkillDelete a skill only if its current revision matches expected_revision.Needs your own keyBilled to your own Perplexityai key
Download Agent Response FileDownload a file delivered by an Agent response's share_file tool.Needs your own keyBilled to your own Perplexityai key
Evaluate DecisionsEvaluate named yes/no, choice, and score questions against shared content.Needs your own keyBilled to your own Perplexityai key
Get Agent ResponseRetrieve a stored Agent response as a JSON snapshot (GET /v1/agent/{id}).Needs your own keyBilled to your own Perplexityai key
Get Async Chat CompletionGet Async Chat Completion (GET /v1/async/sonar/{id}).Needs your own keyBilled to your own Perplexityai key
Get Member Usage AnalyticsGet organization Perplexity usage per member in daily UTC buckets.Needs your own keyBilled to your own Perplexityai key
Get Orchestrator ModelRetrieve one Orchestrator model by its full provider/model id.Needs your own keyBilled to your own Perplexityai key
Get SkillGet a skill's metadata by identifier, optionally at a specific revision.Needs your own keyBilled to your own Perplexityai key
Get Skill Download URLGet a short-lived URL to download a skill bundle as a ZIP, optionally for a specific revision; omit the revision to select the active revision.Needs your own keyBilled to your own Perplexityai key
Show all 28 tools
More Perplexityai tools and their Instant prices
ToolWhat it doesWorks without a keyCost on Instant
Get Usage AnalyticsGet an organization's Perplexity Computer usage as a bucketed time series.Needs your own keyBilled to your own Perplexityai key
List Agent Response FilesList files an agent response delivered from its sandbox using share_file.Needs your own keyBilled to your own Perplexityai key
List Async Chat CompletionsList a page of legacy asynchronous Sonar chat completion requests for the authenticated user, including their statuses.Needs your own keyBilled to your own Perplexityai key
List ModelsList Models (GET /v1/models).Needs your own keyBilled to your own Perplexityai key
List Orchestrator ModelsList available Orchestrator API models sorted by id, with base token prices.Needs your own keyBilled to your own Perplexityai key
List SkillsList skills in the authenticated Project, newest first.Needs your own keyBilled to your own Perplexityai key
List Skill RevisionsList a skill's revisions, newest first.Needs your own keyBilled to your own Perplexityai key
Update SkillUpload a new ZIP bundle as a revision of an existing Project-owned skill.Needs your own keyBilled to your own Perplexityai key
Pricing

How you pay for Perplexityai

  • Your first $2 is freeIt's added to your Composio wallet when you turn on Instant.
  • You pay for each callYou pay Perplexityai's price with 0% markup, plus the regular Composio tool call charge.
  • Your own key comes firstIf you connect your own Perplexityai key, Composio uses it and doesn't charge Instant for those calls.
  • You control the costYou can ask your agent to check with you before each paid call, and you can turn Instant off at any time.
  • You can see each callYour wallet shows each call and what it cost.
  • When your balance runs outYou can add funds to your wallet on a Pro plan or connect your own key.
Help

Troubleshooting

  1. 1. Mastra AI asks me for a Perplexityai API key

    You may have asked for something that needs your own key, like Cancel Agent Response, Create Async Chat Completion, Create Orchestrator Chat Completion, Create Orchestrator Message, CreateOrchestratorResponse, Create Skill and 17 more. Those tools don't run on Instant. For everything else, check that Instant is turned on in your Composio wallet, then ask again.

  2. 2. I can't see my free $2

    Open your wallet in the Composio dashboard and check that Instant is turned on. If the $2 still isn't there, email support@composio.dev from the address you signed up with.

  3. 3. A Perplexityai call failed with a balance error

    Your balance is empty. Add funds to your wallet on a Pro plan, or connect your own Perplexityai key, then try again.

FAQ

Frequently asked questions

Start with Perplexityai.It takes 30 seconds.

New accounts get a one-time $2 starter credit for Instant calls.Run Perplexityai from your agent with no Perplexityai key.

Get $2 starter credit