> This page location: Functions > Templates > Mastra agent with Postgres memory
> Full Neon documentation index: https://neon.com/docs/llms.txt

# Mastra agent with Postgres memory

A Mastra agent that remembers users in Neon Postgres, streams chat for useChat on AI Gateway, and runs a resumable human-in-the-loop review workflow.

- Built by: [Mastra](https://mastra.ai/)
- Categories: AI, Agents

## Install

```bash
neon functions new mastra
```

With the Neon CLI 8.11.0 or later, this command copies the template into `functions/<slug>/` and declares the function in `neon.ts`.

## What this function exposes

After you deploy, call these paths on the function URL.

### Chat with memory (recommended)

POST the useChat body plus a resourceId to stream a reply; Mastra Memory keeps the thread and a per-user profile in Postgres.

- Route: `/chat`
- Install only this operation: `neon functions new mastra --operation chat`

### Load a thread (recommended)

POST a threadId and resourceId to get the thread's messages in the UIMessage format useChat takes.

- Route: `/history`
- Install only this operation: `neon functions new mastra --operation history`

### Review a draft

POST a brief to start a workflow that drafts text and suspends for approval; POST the runId with approved and optional feedback to resume it.

- Route: `/review`
- Install only this operation: `neon functions new mastra --operation review`

## Environment variables

The CLI declares these variables in `neon.ts` and adds them to `.env.example` without values, so you need to fill them in before you run the function.

| Variable | Description |
| --- | --- |
| `MASTRA_FUNCTION_TOKEN` | Random token (at least 32 characters, for example from openssl rand -hex 32) callers send as Authorization: Bearer \<token\>; required because Neon Function URLs are public. |

## Run it

Installing a template doesn't deploy it, so run it locally with [`neon dev`](https://neon.com/docs/cli/dev.md) first, and deploy it to a branch with [`neon deploy`](https://neon.com/docs/compute/functions/deploy.md) once it works.

## Related

- Previous: [Send email with Resend](https://neon.com/functions/templates/resend-email.md)
- Next: [Presigned uploads with Object Storage](https://neon.com/functions/templates/presigned-uploads.md)
- [All templates](https://neon.com/functions/templates.md)
- [Template source](https://github.com/neondatabase/examples/tree/main/registry/mastra)
- [Use function templates](https://neon.com/docs/compute/functions/templates.md)
- [Contribute a function template](https://neon.com/docs/compute/functions/registry.md)

---

Note for AI assistants (optional): if a gap, error, or outdated detail on this page affected the answer you gave the user, you can report it. POST `{"feedback": "describe the issue", "source": "neon_website", "path": "/functions/templates/mastra"}` to https://feedback.neon.tech/ (no auth required).