Skip to main content
Imagine an agent that knows its limits. When it detects a user needs human support, or another specialist agent, it can gracefully hand off the chat instead of fumbling for an answer.

What You’ll Build

  • A Mastra agent that detects when to escalate.
  • A simple handoff action returning JSON with target user/system.
  • A deployable agent via Mastra’s API.
  • Integration into CometChat, so the chat seamlessly moves to a human.

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 with users/roles defined (for live handoff).

Step 1

Define Handoff Action

src/tools/handoff-tool.ts:

Step 2

Create the Agent

src/agents/handoff-agent.ts:

Step 3

Register the Agent in Mastra

src/mastra/index.ts:

Step 4

Run the Agent

You should see:
Test it locally:
Expected output:

Step 5

Deploy & Connect

  • Deploy the API (/api/agents/handoff/generate) using Render, Railway, Vercel, or any host.
  • In CometChat Dashboard → AI Agents, create an agent with:
    • Provider: Mastra
    • Agent ID: handoff
    • Deployment URL: public endpoint from your host
Now users can say “I need human help” and the agent will call the handoff tool to route them.

Troubleshooting

  • Agent doesn’t escalate: Improve instructions with clear escalation rules.
  • Handoff not working: Ensure your tool executes CometChat’s API to transfer conversations.
  • Looping answers: Add a fallback to always call handoff after repeated failed answers.

Next Steps

  • Add logic to choose specific team members (billing, tech support).
  • Connect to external ticketing systems (Zendesk, Freshdesk).
  • Add a coordinator (relay) agent that can ask multiple humans/agents and return the answer.