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

> Create a Mastra Knowledge Agent that answers documentation questions when invoked, then connect it to CometChat.

Imagine an agent that answers policy, product, and FAQ questions by looking them up in your docs—concise, cited, and available right inside chat without derailing the conversation.

***

## What You’ll Build

* A **Mastra agent** that can participate in conversations as a documentation expert.
* Triggered only when explicitly mentioned (e.g., `@agent`).
* Can fetch knowledge from your docs and return short, sourced answers.
* Integrated 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-knowledge-agent](https://github.com/cometchat/ai-agent-mastra-examples/tree/main/mastra-knowledge-agent)
* Quickstart: [Knowledge Agent Quickstart](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/README.md#knowledge-agent-quickstart)
* Swagger UI (local): [http://localhost:4111/swagger-ui](http://localhost:4111/swagger-ui)
* Environment variables: [README#environment-variables](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/README.md#environment-variables)

***

## How it works

This example implements a retrieval-augmented Knowledge Agent that:

* Ingests sources (URLs, files, or raw text) into a local knowledge folder per <code>namespace</code> using the <b>ingestSources</b> tool. Parsed content is stored under <code>knowledge/\<namespace></code> for repeatable retrieval.
* Retrieves relevant snippets with the <b>docsRetriever</b> tool. It scans your <code>knowledge/\<namespace></code> content, chunks and ranks results, and returns the best matches with source metadata.
* Generates answers using only retrieved context. The agent replies when invoked (e.g., <code>@agent</code>), composes a concise answer, and appends a short “Sources” list with citations.
* Handles errors defensively. Server utilities sanitize errors before returning responses.

Key components (source-linked below): the agent, docs retriever tool, ingest endpoints, and server routes.

***

## 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 the agent">
    Add a <b>knowledge</b> agent that answers from retrieved docs only, and responds when explicitly mentioned (e.g., <code>@agent</code>).
  </Step>

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

  <Step title="Ingest knowledge">
    Choose a <code>namespace</code> (e.g., <code>docs</code>) and POST sources to <code>/api/tools/ingestSources</code>. Use URLs, file paths, or raw text. Request shape is documented in the README Quickstart.
  </Step>

  <Step title="Ask the agent">
    Send chat turns to <code>/api/agents/knowledge/generate</code> with a <code>messages</code> array. Optionally pass <code>toolParams.namespace</code> to scope retrieval.
  </Step>

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

  <Step title="Deploy & observe">
    Make the API public, verify via Swagger UI, and re-run ingestion when docs change.
  </Step>
</Steps>

***

## Project Structure

Core files and folders for the Knowledge Agent (browse source on GitHub):

* Environment
  * [.env.example](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/.env.example)
* Runtime & config
  * [package.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/package.json)
  * [tsconfig.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/tsconfig.json)
  * [README.md](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/README.md)
* Agent
  * [src/mastra/agents/knowledge-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/agents/knowledge-agent.ts)
  * [src/mastra/agents/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/agents/index.ts)
* Tools
  * [src/mastra/tools/docs-retriever.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/tools/docs-retriever.ts)
  * [src/mastra/tools/ingest-sources.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/tools/ingest-sources.ts)
  * [src/mastra/tools/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/tools/index.ts)
* Server
  * [src/mastra/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/index.ts)
  * [src/mastra/server/routes.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/server/routes.ts)
  * [src/mastra/server/routes/ingest.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/server/routes/ingest.ts)
  * [src/mastra/server/routes/searchDocs.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/server/routes/searchDocs.ts)
  * [src/mastra/server/util/safeErrorMessage.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/server/util/safeErrorMessage.ts)
* Workflows
  * [src/mastra/workflows/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/workflows/index.ts)
* Knowledge base (sample)
  * [knowledge/default/raw/Acme-Enterprises-FAQ.pdf](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/knowledge/default/raw/Acme-Enterprises-FAQ.pdf)
  * [knowledge/default/acme-enterprises-faq-pdf.md](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/knowledge/default/acme-enterprises-faq-pdf.md)

***

## Step 1 - Create the Agent

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

* Agent file: [src/mastra/agents/knowledge-agent.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/agents/knowledge-agent.ts)
* Docs retriever tool: [src/mastra/tools/docs-retriever.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/tools/docs-retriever.ts)
* Knowledge folder: [knowledge](https://github.com/cometchat/ai-agent-mastra-examples/tree/main/mastra-knowledge-agent/knowledge)

Checklist for the agent:

* Set `name` to **"knowledge"** so the API path is `/api/agents/knowledge/*`.
* Respond **only when mentioned** (e.g., `@agent`).
* Answer **from retrieved docs** and include a short **“Sources:”** list.
* Register `docsRetriever`.

***

## 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-knowledge-agent/src/mastra/index.ts)):

* Server entry: [src/mastra/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/src/mastra/index.ts)
* Ensure the agent is registered with key **"knowledge"** → API path `/api/agents/knowledge/*`.
* Storage/logger configuration as per repo [README.md](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/README.md).

***

## Step 3 - Run the Agent

*Dev script & local server details are tracked in your repo:*

* Scripts: [package.json](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/package.json)
* Quickstart: [Knowledge Agent Quickstart](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/README.md#knowledge-agent-quickstart)

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

<Steps>
  <Step title="Install dependencies">
    Use the commands in the Quickstart (kept in the repository).
  </Step>

  <Step title="Start the dev server">
    Follow the Quickstart to run the local Mastra server.
  </Step>

  <Step title="Ingest sources">
    POST to <code>/api/tools/ingestSources</code> with a <code>namespace</code>. Example commands are in the README Quickstart.
  </Step>

  <Step title="Ask the knowledge agent">
    POST to <code>/api/agents/knowledge/generate</code>. See the README Quickstart for request bodies and examples.
  </Step>
</Steps>

API endpoints exposed by this example (see [Swagger UI](http://localhost:4111/swagger-ui)):

* POST `/api/tools/ingestSources` — ingest URLs/files/text into `knowledge/<namespace>`
* POST `/api/tools/searchDocs` — retrieve relevant snippets from `knowledge/<namespace>`
* POST `/api/agents/knowledge/generate` — chat with the agent

***

## Step 4 - Deploy the API

* [Swagger UI (local)](http://localhost:4111/swagger-ui)
* [Environment variables](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-knowledge-agent/README.md#environment-variables)

Ensure the public route: **`/api/agents/knowledge/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>knowledge</code>, <b>Deployment URL</b>=your public generate endpoint.</Step>
  <Step title="(Optional) Enhancements">Add greeting, prompts, and configure actions/tools if you use frontend tools.</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 Mastra Knowledge agent is attached.</Step>
  <Step title="Preview">Use live preview to validate responses & any tool triggers.</Step>
</Steps>

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b/2U5tVIzH12dbbFtr/images/ai-agent-chat-builder-preview.png?fit=max&auto=format&n=2U5tVIzH12dbbFtr&q=85&s=7e5a476c0f779f984406b979ed12f972" width="5760" height="3200" data-path="images/ai-agent-chat-builder-preview.png" />
</Frame>

***

## Step 7 - Integrate

Once your Knowledge 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 **Mastra Knowledge 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/knowledge/generate</code> returns a doc-grounded answer.</Step>
  <Step title="Agent listed"><code>/api/agents</code> includes <code>"knowledge"</code>.</Step>
  <Step title="Tool action works">UI handles <code>docsRetriever</code> tool invocation.</Step>
  <Step title="Full sample test (run curl)">See curl command below.</Step>
</Steps>

```bash theme={null}
curl -X POST http://localhost:4111/api/agents/knowledge/generate \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      { "role": "user", "content": "@agent where is the refund policy documented?" }
    ]
  }'
```

***

## Security & production checklist

* Protect endpoints with auth (API key/JWT) and restrict CORS to trusted origins.
* Add basic rate limiting and request size limits to ingestion and generate routes.
* Validate inputs: enforce allowed namespaces, URL/file whitelists, and payload schemas.
* Monitor logs and errors; sanitize responses using server utilities.
* For public deploys, keep your OpenAI key in server-side env only; never expose it to the client.

## Troubleshooting

* **Agent talks too much**: tighten instructions to only respond when mentioned and to answer from docs.
* **No results**: ensure `/knowledge` contains `.md/.mdx` files or your ingestion job populated the store.
* **Not visible in chat**: verify the agent is added as a user in CometChat and enabled in the Dashboard.
* **404 / Agent not found**: check that the server registers the agent with key `knowledge`.

***

## Next Steps

* Add tools like `summarize-doc`, `fetch-policy`, or `link-to-source`.
* Use embeddings + chunking for better retrieval.
* Restrict answers to whitelisted folders or domains.
* Inspect and try endpoints via Swagger UI (`/swagger-ui`).
* Set up CI/CD in your own repo as needed.
