> ## Documentation Index
> Fetch the complete documentation index at: https://www.cometchat.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Build Your Backend Tools Agent with Mastra

> Create a Mastra agent that performs secure backend actions (e.g., fetch deals) via server-side tools, then connect it to CometChat.

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.

***

## Quick links

* Repo: [mastra-backend-tools-agent](https://github.com/cometchat/ai-agent-mastra-examples/tree/main/mastra-backend-tools-agent)
* README: [Project README](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/README.md)
* Scripts: [package.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/package.json)

***

## 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):

* Environment
  * [.env.example](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/.env.example)
* Runtime & config
  * [package.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/package.json)
  * [tsconfig.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/tsconfig.json)
  * [README.md](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/README.md)
* Agent
  * [src/mastra/agents/deals-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/src/mastra/agents/deals-agent.ts)
* Tools
  * [src/mastra/tools/get-deals-tool.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/src/mastra/tools/get-deals-tool.ts)
  * [src/mastra/tools/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/src/mastra/tools/index.ts)
* Server
  * [src/mastra/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/src/mastra/index.ts)
* Workflows
  * [src/mastra/workflows/orchestrator-workflow.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/src/mastra/workflows/orchestrator-workflow.ts)

***

## Step 1 - Create the Agent

**`src/mastra/agents/deals-agent.ts`** ([view in repo](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/src/mastra/agents/deals-agent.ts)):

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](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/src/mastra/index.ts)):

* 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:*

* Scripts: [package.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/package.json)
* README: [Project README](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/README.md)

Expected local API base: `http://localhost:4111/api`

<Steps>
  <Step title="Install dependencies">Use the repo scripts to install dependencies.</Step>
  <Step title="Start the dev server">Run the local Mastra server as per the README.</Step>
  <Step title="Ask the agent">POST to <code>/api/agents/deals/generate</code> and verify the answer is backed by tool output.</Step>
</Steps>

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

<Steps>
  <Step title="Open Dashboard">Open the <a href="https://app.cometchat.com/" target="_blank" rel="noreferrer">CometChat Dashboard</a>.</Step>
  <Step title="Navigate">Go to your App → <b>AI Agents</b>.</Step>
  <Step title="Add agent">Set <b>Provider</b>=Mastra, <b>Agent ID</b>=<code>deals</code>, <b>Deployment URL</b>=your public generate endpoint.</Step>
  <Step title="(Optional) Tools">Server-side tools require no client code, but you can display structured results nicely in your UI.</Step>
  <Step title="Enable">Save and ensure the agent toggle shows <b>Enabled</b>.</Step>
</Steps>

> For more on CometChat AI Agents, see the docs: [Overview](/ai-agents/agent-builder/overview) · [Instructions](/ai-agents/agent-builder/instructions) · [Custom agents](/ai-agents/agent-builder/tools/overview)

***

## Step 6 - Customize in UI Kit Builder

<Steps>
  <Step title="Open variant">From <b>AI Agents</b> click the variant (or Get Started) to enter UI Kit Builder.</Step>
  <Step title="Customize & Deploy">Select <b>Customize and Deploy</b>.</Step>
  <Step title="Adjust settings">Theme, layout, features; ensure the Backend Tools agent is attached.</Step>
  <Step title="Preview">Use live preview to validate responses and scenarios that trigger backend actions.</Step>
</Steps>

***

## Step 7 - Integrate

Once your Backend Tools Agent is configured, you can integrate it into your app using the CometChat Widget Builder:

<CardGroup>
  <Card title="Widget Builder" icon={<img src="/docs/images/products/ai-agents.svg" alt="Widget" />} description="Embed / script" href="/widget/ai-agents" horizontal />

  <Card title="React UI Kit" icon={<img src="/docs/images/icons/react.svg" alt="React" />} href="https://www.cometchat.com/docs/ui-kit/react/ai-assistant-chat" horizontal>Pre Built UI Components</Card>
</CardGroup>

> **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

<Steps>
  <Step title="API generates response">POST to <code>/api/agents/deals/generate</code> returns a message backed by tool output.</Step>
  <Step title="Agent listed"><code>/api/agents</code> includes <code>"deals"</code>.</Step>
  <Step title="Tool invoked">Server logs show <code>get-deals</code> tool invoked when appropriate.</Step>
</Steps>

```bash theme={null}
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.
