> ## 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 Orchestrator Agent with Mastra

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

Give users the right help fast: an 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 orchestrator 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-orchestrator-agent](https://github.com/cometchat/ai-agent-mastra-examples/tree/main/mastra-orchestrator-agent)
* README: [Project README](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/README.md)
* Scripts: [package.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/package.json)

***

## How it works

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

* The primary agent (the orchestrator) 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 orchestrator returns the final response.
* This keeps logic modular and makes it easy to add or refine specialist agents.

Key components (source-linked below): the orchestrator agent, specialist agents, orchestrator tool, and orchestrator 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 orchestrator + specialists">
    Add an <b>orchestrator</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/orchestratorAgent/generate</code> (see <a href="https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/src/mastra/index.ts" target="_blank" rel="noreferrer">server entry</a>).
  </Step>

  <Step title="Ask the orchestrator">
    POST to <code>/api/agents/orchestratorAgent/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>orchestratorAgent</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 Orchestrator Agent (browse source on GitHub):

* Environment
  * Use <code>.env</code> with <code>OPENAI\_API\_KEY</code>
* Runtime & config
  * [package.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/package.json)
  * [tsconfig.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/tsconfig.json)
  * [README.md](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/README.md)
* Agents
  * [src/mastra/agents/orchestrator-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/src/mastra/agents/orchestrator-agent.ts)
  * [src/mastra/agents/billing-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/src/mastra/agents/billing-agent.ts)
  * [src/mastra/agents/support-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-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-orchestrator-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-orchestrator-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-orchestrator-agent/src/mastra/agents/human-rep-agent.ts)
* Tools
  * [src/mastra/tools/orchestrator-tool.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/src/mastra/tools/orchestrator-tool.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)
* Server
  * [src/mastra/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/src/mastra/index.ts)

***

## Step 1 - Create the Orchestrator and Specialist Agents

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

Checklist for the orchestrator:

* Register the agent with key **"orchestratorAgent"** so the API path is `/api/agents/orchestratorAgent/*`.
* 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-orchestrator-agent/src/mastra/agents/billing-agent.ts)
* Support: [support-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/src/mastra/agents/support-agent.ts)
* Tech Support: [tech-support-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/src/mastra/agents/tech-support-agent.ts)
* Manager: [manager-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/src/mastra/agents/manager-agent.ts)
* Human Rep: [human-rep-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/src/mastra/agents/human-rep-agent.ts)

***

## Step 2 - Routing Tool and Workflow

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

Ensure the orchestrator 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-orchestrator-agent/src/mastra/index.ts)):

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

***

## Step 4 - Run the Orchestrator

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

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

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

<Steps>
  <Step title="Install dependencies">Run <code>npm install</code>.</Step>
  <Step title="Start the dev server">Run <code>npx mastra dev</code> (or <code>npm run dev</code>).</Step>
  <Step title="Ask the orchestrator agent">POST to <code>/api/agents/orchestratorAgent/generate</code> and verify the routed specialist answers.</Step>
  <Step title="Observe routing">Responses end with <code>(\[routedTo] | escalated: yes/no)</code>; check logs for which specialist was chosen.</Step>
</Steps>

API endpoints exposed by this example:

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

***

## Step 5 - Deploy the API

Ensure your public route: **`/api/agents/orchestratorAgent/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>orchestratorAgent</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/agent-builder/overview) · [Instructions](/ai-agents/agent-builder/instructions) · [Custom agents](/ai-agents/agent-builder/tools/overview)

***

## Step 7 - 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 Orchestrator agent is attached.</Step>
  <Step title="Preview">Use live preview to validate routing and responses.</Step>
</Steps>

***

## Step 8 - Integrate

Once your Orchestrator 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 **Orchestrator 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="Orchestrator responds">POST to <code>/api/agents/orchestratorAgent/generate</code> returns an answer from the chosen specialist and ends with routing metadata.</Step>
  <Step title="Agent listed"><code>/api/agents</code> includes <code>"orchestratorAgent"</code>.</Step>
  <Step title="Routing visible">Logs show which specialist handled the request.</Step>
</Steps>

```bash theme={null}
curl -X POST http://localhost:4111/api/agents/orchestratorAgent/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 orchestrator prompts, add explicit routing criteria, or fallbacks.
* **No response**: verify orchestrator and specialists are registered and reachable.
* **Agent not found**: confirm the server registers the agent with key `orchestratorAgent`.

***

## 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.
