> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-restapi-chatapi-quotedmessages.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Build Your Multi-agent Orchestration Agent with Mastra

> Create a Mastra coordinator (relay) agent that routes queries to the right specialist agent (billing, support, tech), then connect it to CometChat.

Give users the right help fast: a coordinator/orchestrator agent that triages each request and forwards it to the best-fit specialist (billing, support, tech support, manager, or a human rep).

***

## What You’ll Build

* A **Mastra coordinator/relay agent** that classifies intent and routes to specialist agents.
* Specialist agents (billing, support, tech-support, manager, human-rep).
* A routing tool and workflow that coordinate handoffs.
* 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-coordinator-agent](https://github.com/cometchat/ai-agent-mastra-examples/tree/main/mastra-coordinator-agent)
* README: [Project README](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/README.md)
* Scripts: [package.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/package.json)

***

## How it works

This example demonstrates a “multi-agent orchestration (relay)” pattern:

* The primary agent (e.g., `relay`) understands the user request and decides which specialist should respond.
* The routing tool and workflow handle the handoff, preserving context.
* The selected specialist (billing/support/tech/manager/human-rep) answers, and the relay returns the final response.
* This keeps logic modular and makes it easy to add or refine specialist agents.

Key components (source-linked below): the coordinator/relay agent, specialist agents, relay route tool, and relay workflow.

***

## Setup

<Steps>
  <Step title="Prepare project">
    Create a Mastra app and add <code>OPENAI\_API\_KEY</code> in <code>.env</code>. See the repository README for exact steps.
  </Step>

  <Step title="Define relay + specialists">
    Add a <b>relay</b> agent and specialist agents (billing, support, tech, manager, human-rep).
  </Step>

  <Step title="Add routing">
    Implement a routing tool and workflow that determine the best specialist for a request.
  </Step>

  <Step title="Register in server">
    Register the agents and expose <code>/api/agents/relay/generate</code> (see <a href="https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/index.ts" target="_blank" rel="noreferrer">server entry</a>).
  </Step>

  <Step title="Ask the relay">
    POST to <code>/api/agents/relay/generate</code> with a <code>messages</code> array and verify routed answers.
  </Step>

  <Step title="Connect to CometChat">
    In Dashboard → AI Agents, set Provider=Mastra, Agent ID=<code>relay</code>, and point Deployment URL to your public generate endpoint.
  </Step>

  <Step title="Deploy & observe">
    Make the API public and monitor which specialist is selected in logs.
  </Step>
</Steps>

***

## Project Structure

Core files and folders for the Multi-agent Orchestration Agent (browse source on GitHub):

* Environment
  * [.env.example](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/.env.example)
* Runtime & config
  * [package.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/package.json)
  * [tsconfig.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/tsconfig.json)
  * [README.md](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/README.md)
* Agents
  * [src/mastra/agents/relay-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/relay-agent.ts)
  * [src/mastra/agents/billing-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/billing-agent.ts)
  * [src/mastra/agents/support-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/support-agent.ts)
  * [src/mastra/agents/tech-support-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/tech-support-agent.ts)
  * [src/mastra/agents/manager-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/manager-agent.ts)
  * [src/mastra/agents/human-rep-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/human-rep-agent.ts)
* Tools
  * [src/mastra/tools/relay-route-tool.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/tools/relay-route-tool.ts)
* Workflows
  * [src/mastra/workflows/relay-workflow.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/workflows/relay-workflow.ts)
* Server
  * [src/mastra/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/index.ts)

***

## Step 1 - Create the Relay and Specialist Agents

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

Checklist for the relay:

* Set `name` to **"relay"** so the API path is `/api/agents/relay/*`.
* Detect intents (billing, support, tech, manager, human rep).
* Use the routing tool/workflow to hand off.
* Compose a concise final reply.

Specialists (configure as needed):

* Billing: [billing-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/billing-agent.ts)
* Support: [support-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/support-agent.ts)
* Tech Support: [tech-support-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/tech-support-agent.ts)
* Manager: [manager-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/manager-agent.ts)
* Human Rep: [human-rep-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/human-rep-agent.ts)
* Billing: [billing-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/billing-agent.ts)
* Support: [support-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/support-agent.ts)
* Tech Support: [tech-support-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/tech-support-agent.ts)
* Manager: [manager-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/manager-agent.ts)
* Human Rep: [human-rep-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/agents/human-rep-agent.ts)

***

## Step 2 - Routing Tool and Workflow

* Routing tool: [relay-route-tool.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/tools/relay-route-tool.ts)
* Workflow: [relay-workflow.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/src/mastra/workflows/relay-workflow.ts)

Ensure the coordinator/relay agent calls the tool/workflow with the correct context, and specialists are discoverable by key.

***

## Step 3 - Register the Agents in Mastra

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

* Register the relay with key **"relay"** → API path `/api/agents/relay/*`.
* Register specialist agents and expose only the relay externally.
* Keep config and logger settings as per the repo README.

***

## Step 4 - Run the Relay

*Dev scripts & server details are in your repo:*

* Scripts: [package.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-agent/package.json)
* README: [Project README](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-coordinator-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 orchestrator (relay) agent">POST to <code>/api/agents/relay/generate</code> and verify the routed specialist answers.</Step>
  <Step title="Observe routing">Check logs to see which specialist was chosen.</Step>
</Steps>

API endpoints exposed by this example:

* POST `/api/agents/relay/generate` — chat with the relay and get routed responses

***

## Step 5 - Deploy the API

Ensure your public route: **`/api/agents/relay/generate`** is reachable.

***

## Step 6 - 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>relay</code>, <b>Deployment URL</b>=your public generate endpoint.</Step>
  <Step title="(Optional) Routing">Adjust specialist prompts and routing rules as needed.</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/overview) · [Instructions](/ai-agents/instructions) · [Custom agents](/ai-agents/custom-agents)

***

## Step 7 - Customize in Chat Builder

<Steps>
  <Step title="Open variant">From <b>AI Agents</b> click the variant (or Get Started) to enter Chat Builder.</Step>
  <Step title="Customize & Deploy">Select <b>Customize and Deploy</b>.</Step>
  <Step title="Adjust settings">Theme, layout, features; ensure the Multi-agent Orchestration (relay) agent is attached.</Step>
  <Step title="Preview">Use live preview to validate routing and responses.</Step>
</Steps>

***

## Step 8 - Integrate

Once your Multi-agent Orchestration Agent is configured, you can integrate it into your app using the CometChat No Code - Widget:

<CardGroup>
  <Card title="No Code - Widget" 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 **Orchestrator (relay) agent** you connected in earlier steps is already part of the exported configuration, so your end-users will chat with that agent immediately.

***

## Step 9 - Test Your Setup

<Steps>
  <Step title="Relay responds">POST to <code>/api/agents/relay/generate</code> returns an answer from the chosen specialist.</Step>
  <Step title="Agent listed"><code>/api/agents</code> includes <code>"relay"</code>.</Step>
  <Step title="Routing visible">Logs show which specialist handled the request.</Step>
</Steps>

```bash
curl -X POST http://localhost:4111/api/agents/relay/generate \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      { "role": "user", "content": "@agent I need help with my invoice charges" }
    ]
  }'
```

***

## 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 monitor routing distribution.
* Keep secrets in server-side env only; never expose them to the client.

## Troubleshooting

* **Wrong specialist**: refine relay prompts, add explicit routing criteria, or fallbacks.
* **No response**: verify relay and specialists are registered and reachable.
* **Agent not found**: confirm the server registers the agent with key `relay`.

***

## Next Steps

* Add more specialists (sales, onboarding) or escalation rules.
* Add audit logs for routed conversations.
* Implement handoff to a human rep based on confidence thresholds.
