Let an agent take real actions on the server: call APIs, query services, and return results—safely and without exposing secrets to the browser.

What You’ll Build

  • A Mastra agent that can perform backend actions using server-side tools.
  • A tool (e.g., get-deals) that calls an external service/DB and returns structured data.
  • An API endpoint to chat with the agent and receive results grounded in tool output.
  • Integration into CometChat chats.

Prerequisites

  • A Mastra project (npx create-mastra@latest my-mastra-app).
  • Node.js installed.
  • OpenAI API key in .env as OPENAI_API_KEY.
  • A CometChat app.


How it works

This example demonstrates a “backend actions” pattern:
  • The agent (e.g., deals) decides to use a server-side tool like get-deals when it needs live data.
  • The tool runs securely on the server (with keys/env), calls your service, and returns structured results.
  • The agent composes a concise answer grounded in tool output; sensitive details never leave the server.
  • Your UI just renders responses—no secrets or privileged calls in the browser.
Key components (source-linked below): the agent, the get-deals tool, server entry, and workflows.

Project Structure

Core files and folders for the Backend Tools Agent (browse source on GitHub):

Step 1 - Create the Agent

src/mastra/agents/deals-agent.ts (view in repo): Checklist for the agent:
  • Set name to something like “deals” so the API path is /api/agents/deals/*.
  • Describe when to use the get-deals tool (e.g., when user asks about deals, pricing, or promos).
  • Keep responses short, cite the latest results, and avoid hallucinations.
  • Ensure tool results are summarized clearly for end-users.

Step 2 - Register the Agent in Mastra

src/mastra/index.ts (view in repo):
  • Register the agent with key “deals” → API path /api/agents/deals/*.
  • Keep config and logger settings as per the repo README.

Step 3 - Run the Agent

Dev scripts & server details are in your repo: Expected local API base: http://localhost:4111/api
1

Install dependencies

Use the repo scripts to install dependencies.
2

Start the dev server

Run the local Mastra server as per the README.
3

Ask the agent

POST to /api/agents/deals/generate and verify the answer is backed by tool output.
API endpoints exposed by this example:
  • POST /api/agents/deals/generate — chat with the agent and retrieve action-backed responses

Step 4 - Deploy the API

Ensure your public route: /api/agents/deals/generate is reachable.

Step 5 - Configure in CometChat

1

Open Dashboard

2

Navigate

Go to your App → AI Agents.
3

Add agent

Set Provider=Mastra, Agent ID=deals, Deployment URL=your public generate endpoint.
4

(Optional) Tools

Server-side tools require no client code, but you can display structured results nicely in your UI.
5

Enable

Save and ensure the agent toggle shows Enabled.
For more on CometChat AI Agents, see the docs: Overview · Instructions · Custom agents

Step 6 - 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 Backend Tools agent is attached.
4

Preview

Use live preview to validate responses and scenarios that trigger backend actions.

Step 7 - Integrate

Once your Backend Tools Agent is configured, you can integrate it into your app using the CometChat No Code - Widget:
Note: The Backend Tools agent you connected in earlier steps is already part of the exported configuration, so your end-users will chat with that agent immediately.

Step 8 - Test Your Setup

1

API generates response

POST to /api/agents/deals/generate returns a message backed by tool output.
2

Agent listed

/api/agents includes “deals”.
3

Tool invoked

Server logs show get-deals tool invoked when appropriate.
curl -X POST http://localhost:4111/api/agents/deals/generate \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      { "role": "user", "content": "@agent what are the current deals?" }
    ]
  }'

Security & production checklist

  • Protect endpoints with auth (API key/JWT) and restrict CORS to trusted origins.
  • Add rate limiting and request size limits to the generate route.
  • Validate inputs, sanitize logs/responses, and handle upstream timeouts/retries.
  • Keep secrets in server-side env only; never expose them to the client.

Troubleshooting

  • No tool runs: confirm the agent is configured to use get-deals and the tool is registered.
  • Upstream errors: inspect server logs and add retry/backoff to the tool.
  • Agent not found: confirm the server registers the agent with key deals.

Next Steps

  • Add more backend tools (e.g., get-order, create-ticket) and guard with RBAC.
  • Stream responses or add partial updates for long-running actions.
  • Instrument and log tool invocations for tuning and observability.