Developer Preview: AI Agents currently support Mastra. OpenAI, Agno, and other providers are coming soon.

What you’ll build

  • A Mastra agent with tools/actions
  • The same agent connected to CometChat (Agent ID + Deployment URL)
  • A customized chat experience using Chat Builder
  • An export to React UI Kit code or Chat Widget for integration

Prerequisites

  • A CometChat account and an app: Create App
  • A Mastra agent (ID + public Deployment URL) — follow Mastra’s quickstart:
    Mastra Quickstart

Step 1 - Create your CometChat app

1

Create or open an app

Sign in at app.cometchat.com. Create a new app or open an existing one.
2

Copy credentials

Note your App ID, Region, and Auth Key (needed if you export the Chat Widget later).

Step 2 - Connect your Mastra Agent

Navigate to AI Agent → Get Started and then AI Agents → Add Agent.
1

Choose provider

Select Mastra.
2

Basic details

Provide:
  • Name and optional Icon
  • (Optional) Greeting and Introductory Message
  • (Optional) Suggested messages
3

Mastra configuration

Paste the following from your Mastra deployment:
  • Mastra Agent ID
  • Deployment URL (public URL that CometChat can reach)
4

Save & enable

Click Save, then ensure the agent’s toggle is ON in AI Agents list.
Tip: If you update your Mastra agent later (prompts, tools, routing), you won’t need to re-connect it in CometChat—just keep the Agent ID and Deployment URL the same.

Step 3 - Define Frontend Actions (Optional)

1

Add an action

Go to AI Agent → Actions and click Add to create a frontend action your agent can call (e.g., “Open Product,” “Start Demo,” “Book Slot”).
2

Define fields

Include:
  • Display Name — Shown to users (e.g., “Open Product Page”).
  • Execution Text — How the agent describes running it (e.g., “Opening product details for the user.”).
  • Name — A unique, code‑friendly key (e.g., open_product).
  • Description — What the tool does and when to use it.
  • Parameters — JSON Schema describing inputs (the agent will fill these).
3

Validate inputs (schema)

Example parameters JSON:
{
  "type": "object",
  "required": ["productId"],
  "properties": {
    "productId": {
      "type": "string",
      "description": "The internal product ID to open"
    },
    "utm": {
      "type": "string",
      "description": "Optional tracking code"
    }
  }
}
4

Handle in your UI

At runtime, listen for tool calls and execute them client‑side (e.g., route changes, modals, highlights).

Step 4 - Customize in Chat Builder

1

Open variant

From AI Agents click the variant (or Get Started) to enter Chat Builder.
2

Customize & Deploy

Select Customize and Deploy.
3

Adjust settings

Theme, layout, features; ensure the Mastra agent is attached.
4

Preview

Use live preview to validate responses & any tool triggers.

Step 5 - Export & Integrate

Choose how you’ll ship the experience (Widget or React UI Kit export).
The Mastra agent from Step 2 is included automatically in exported variants—no extra code needed for basic conversations.
1

Decide delivery mode

Pick Chat Widget (fastest) or export React UI Kit for code-level customization.
2

Widget path

Open Chat Builder → Get Embedded Code → copy script + credentials.
3

React UI Kit path

Export the variant as code (UI Kit) if you need deep theming or custom logic.
4

Verify agent inclusion

Preview: the Mastra agent should appear without extra config.

Step 6 - Deploy & Secure (Reference)

Don’t have a public Mastra agent yet? Use these reference blocks to define, expose, and deploy one securely.
Minimal agent definition. (Adjust imports per current Mastra release.)
// mastra/agent.ts
import { defineAgent } from "mastra";

export const supportAgent = defineAgent({
  name: "My Agent 1",
  instructions: `You are a helpful support agent for Acme. Use tools when appropriate.`,
  tools: [
    {
      name: "open_product",
      description: "Open a product by ID in the UI",
      parameters: {
        type: "object",
        required: ["productId"],
        properties: { productId: { type: "string" } }
      }
    }
  ]
});
// server.ts
import express from "express";
import { supportAgent } from "./mastra/agent";

const app = express();
app.use(express.json());

app.post("/mastra/agent", async (req, res) => {
  const { messages } = req.body;
  const result = await supportAgent.respond({ messages });
  res.json(result);
});

app.listen(process.env.PORT || 3000, () => {
  console.log("Mastra agent running");
});

Local Development

  1. npx mastra dev starts local API (commonly http://localhost:4111/api).
  2. Custom Express route? Keep path consistent in production.

Quick test (replace AGENT_ID):

curl -X POST http://localhost:4111/api/agents/AGENT_ID/generate \
  -H "Content-Type: application/json" \
  -d '{"messages":[{"role":"user","content":"ping"}]}'

Temporary Public Tunnel

ngrok http 4111
cloudflared tunnel --url http://localhost:4111
loca.lt --port 4111

Append route (e.g. /api/agents/chef/generate) to the forwarded HTTPS URL.

Production Patterns

  • Serverless: Single API route invoking the agent.
  • Container: Long‑lived Express/CLI process; add health checks.
  • Edge: Keep tools stateless; externalize persistence.

Vercel Example

// api/agents/chef/generate.ts
import type { VercelRequest, VercelResponse } from '@vercel/node'
import { chefAgent } from '../../mastra/agents/chef-agent'

export default async function handler(req: VercelRequest, res: VercelResponse) {
  if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })
  try {
    const { messages } = req.body || {}
    const result = await chefAgent.respond({ messages })
    return res.status(200).json(result)
  } catch (e:any) {
    return res.status(500).json({ error: e.message || 'Agent error' })
  }
}

Security

  • Rate limit by IP + user.
  • Add auth (Bearer / JWT) for non-public agents.
  • Log tool calls (id, latency) for observability.

CometChat Mapping

Use the final HTTPS URL + path for Deployment URL and the agent key (e.g. chef) for Mastra Agent ID.

Deploy (Vercel, Render, Fly, etc.) then copy the public URL as your Deployment URL and the Mastra Agent ID from config.

Docs: https://mastra.ai/agents

Test your setup

1

Enable the agent

In AI Agents, ensure your Mastra agent shows Enabled.
2

Preview in Chat Builder

Open Chat Builder and start a preview session.
3

Validate conversation

Send a message; confirm the agent responds.
4

Test actions

Trigger a Frontend Action and verify your UI handles the tool call.

Troubleshooting

  • Verify your Deployment URL is publicly reachable (no VPN/firewall).
  • Check server logs for 4xx/5xx errors.
  • Confirm the Action’s Name in CometChat exactly matches the tool name your UI listens for.
  • Validate the Parameters JSON Schema; the agent uses this to fill inputs.
  • Use authKey only for development. For production, implement a secure token flow for user login.