# Building a Medical Symptom Checker agent with Mastra and CometChat

A step-by-step guide to building a Medical Symptom Checker Agent using Mastra and CometChat. This tutorial walks through how to analyze free-text symptoms, determine urgency levels, route users to the right medical professional, and escalate to a human representative when needed. You’ll also learn how to plug the entire workflow into CometChat’s AI Agents so the symptom checker can operate naturally inside a chat experience.

## What You’ll Build

By the end of this tutorial, you’ll have:

- A **Symptom Checker LLM agent** that analyzes symptoms
- A set of **specialist sub-agents** (nurse, doctor, emergency, human rep)
- Automatic detection of urgency levels
- High-risk and escalation logic
- A /generate API endpoint that CometChat can call
- Optional human handoff inside chat UI

## How the System Works

This symptom-checker system works like an automated medical triage front desk. Users describe symptoms, the agent analyzes severity based on keywords, assigns urgency, and then routes the case to the correct provider- nurse, doctor, or emergency. If symptoms are unclear, unusual, or critical, the tool escalates to a **human representative**.

Each specialist is implemented as a small LLM agent with focused instructions. The routing is handled by a Mastra tool, and the workflow glues everything together into a single /generate endpoint.

## Step 1: Create the Symptom Checker Agent

This step sets up the main agent responsible for reading user symptoms and determining next steps. It defines the tone, instructions, safety disclaimers, and routing expectations. This is the agent that CometChat will ultimately call.

File: src/mastra/agents/symptom-checker-agent.ts

```javascript
export const symptomCheckerAgent = createAgent({
  name: "symptomCheckerAgent",
  instructions: `
You are a medical symptom assessment assistant.
Only respond when mentioned with @agent.
Assess symptoms, determine urgency, and route to nurse, doctor, emergency, or human rep.
Include medical disclaimers.
`,
  tools: {
    symptomCheckerTool,
  },
});
```

This agent uses the symptomCheckerTool to actually route requests.

## Step 2: Define Provider + Human Rep Agents

Each provider agent is small and dedicated to a single purpose. The symptom checker never makes final decisions, it delegates to one of these specialists depending on the user's symptoms. This modular design keeps the system flexible and easy to extend.

### Nurse Practitioner Agent

File: src/mastra/agents/nurse-practitioner-agent.ts

```javascript
export const nursePractitionerAgent = createAgent({
  name: "nursePractitionerAgent",
  instructions: `
You handle mild or common symptoms.
Provide safe, concise recommendations and appointment guidance.
`,
});
```

### Doctor Agent

File: src/mastra/agents/doctor-agent.ts

```javascript
export const doctorAgent = createAgent({
  name: "doctorAgent",
  instructions: `
You handle moderate to severe non-emergency symptoms.
Give structured medical guidance and bookable recommendations.
`,
});
```

### Emergency Agent

File: src/mastra/agents/emergency-agent.ts

```javascript
export const emergencyAgent = createAgent({
  name: "emergencyAgent",
  instructions: `
You handle severe or life-threatening symptoms.
Always recommend immediate emergency care.
`,
});
```

### Human Representative Agent

File: src/mastra/agents/human-rep-agent.ts

```javascript
export const humanRepAgent = createAgent({
  name: "humanRepAgent",
  instructions: `
You are a human support representative.
Take over when symptoms are unclear, conflicting, or require human review.
`,
});
```

## Step 3: Implement the Symptom Checker Tool

The tool is the heart of triage. It analyzes symptoms, checks for urgency keywords, and determines which specialist agent should handle the case. This is also where human handoff logic lives.

File: src/mastra/tools/symptom-checker-tool.ts

```javascript
export const symptomCheckerTool = createTool({
  id: "symptomCheckerTool",
  description: "Analyze symptoms and route to appropriate agent",
  inputSchema: z.object({
    userRequest: z.string(),
  }),
  async run({ userRequest }) {
    if (isEmergency(userRequest)) {
      return emergencyAgent.generate([{ role: "user", content: userRequest }]);
    }
    if (needsDoctor(userRequest)) {
      return doctorAgent.generate([{ role: "user", content: userRequest }]);
    }
    if (needsNurse(userRequest)) {
      return nursePractitionerAgent.generate([{ role: "user", content: userRequest }]);
    }
    return humanRepAgent.generate([{ role: "user", content: userRequest }]);
  },
});
```

This exact logic determines routing and escalation.

## Step 4: Build the Triage Workflow

The workflow wraps the tool logic in a clean execution pipeline. When the API endpoint is called, Mastra runs this workflow, which then calls the symptom checker tool.

File: src/mastra/workflows/symptom-checker-workflow.ts

```javascript
export const symptomCheckerWorkflow = createWorkflow({
  id: "symptomCheckerWorkflow",
  steps: {
    checkSymptoms: async ({ input, agents }) => {
      return agents.symptomCheckerAgent.tools.symptomCheckerTool.run({
        userRequest: input.message,
      });
    },
  },
});
```

## Step 5: Register Agents and Workflows

This step tells Mastra which agents/workflows to expose as API endpoints. Without registration, the system wouldn't know what to deploy.

File: src/mastra/index.ts

```javascript
export const mastra = new Mastra({
  agents: {
    symptomCheckerAgent,
  },
  workflows: {
    symptomCheckerWorkflow,
  },
});
```

This automatically generates:

POST /api/agents/symptomCheckerAgent/generate

## Step 6: Run the Agent Locally

Running locally ensures everything works before you integrate with CometChat. Mastra provides Swagger UI to help you test routing behavior and escalation paths.

```bash
npm install
npm run dev
```

Visit:

- Swagger UI → [http://localhost:4111/swagger-ui](http://localhost:4111/swagger-ui)
- Base API → [http://localhost:4111/api](http://localhost:4111/api)

## Step 7: Test the System

Before going live, simulate real symptoms. Test mild, moderate, severe, and unclear cases to confirm routing, urgency detection, and human handoff.

### Mild symptoms

```bash
curl -s -X POST http://localhost:4111/api/agents/symptomCheckerAgent/generate \
  -H 'Content-Type: application/json' \
  -d '{"messages":[{"role":"user","content":"@agent I have a mild headache and feel tired"}]}'
```

### Emergency

```bash
curl -s -X POST http://localhost:4111/api/agents/symptomCheckerAgent/generate \
  -H 'Content-Type: application/json' \
  -d '{"messages":[{"role":"user","content":"@agent I have severe chest pain"}]}'
```

### Doctor-level

```bash
curl -s -X POST http://localhost:4111/api/agents/symptomCheckerAgent/generate \
  -H 'Content-Type: application/json' \
  -d '{"messages":[{"role":"user","content":"@agent I have a fever over 102 and abdominal pain"}]}'
```

## Step 8: Connect to CometChat

Once your agent is running, integrating with CometChat takes only a few steps. CometChat simply forwards user messages to your Mastra /generate endpoint and displays your agent’s response.

Inside CometChat Dashboard → AI Agents:

- **Provider:** Mastra
- **Agent ID:** symptomCheckerAgent
- **Deployment URL:** your public /generate endpoint

Then attach this agent in Chat Builder and test in live preview.

## Conclusion

You’ve now built a complete **Medical Symptom Checker with Human Handoff** powered by Mastra. It can analyze symptoms, detect urgency, escalate to humans, and integrate seamlessly with CometChat.

You can extend this system with:

- Symptom severity scoring
- Insurance eligibility checks
- Appointment scheduling
- Medical content search
- Patient education modules

### Shrinithi Vijayaraghavan

Creative Storytelling , CometChat
