Run a Mastra agent with tools and Postgres-backed memory inside a TypeScript service, keep the model key in a secret, and deploy it to your own cloud.

Mastra is a TypeScript framework for agents: an Agent with instructions, a model and tools, plus memory, workflows and a local Studio for testing. Getting an agent to answer in Studio takes a few minutes. Getting it in front of users means a database for its memory, a model API key stored outside .env, authentication so one user cannot read another user's threads, and somewhere to run it.
This guide builds a small order-support agent with @mastra/core 1.x and deploys it to your own AWS or GCP account. The agent's memory lives in Postgres through Mastra's own PostgresStore, and its tool reads from the same database.
One service called support with:
orders table the agent can query through a tool.Agent with one tool, lookup-order, and Memory backed by PostgresStore.POST /chat/:threadId, an authenticated endpoint that sends the user's message to the agent and returns the reply, with history scoped to that user.Mastra's deployment docs describe two broad routes, and the choice decides how much infrastructure you own.
The rest of this guide takes the second route, which suits a support agent that has to read order data and sit behind the same auth as the rest of the app. The first route is covered in the DIY section further down.
You need Node.js 22.13 or later, which Mastra lists as its minimum, Docker for the local database, and the Encore CLI. Install the CLI with the command for your operating system, create an app from the Empty app template, and add the Mastra packages:
Run in your terminal to get started locally.
// support/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("support");
Encore is the safe way for AI agents to ship backend changes to your cloud. Here it supplies the two things the Mastra agent needs from outside its own code. The Postgres database is declared in TypeScript, encore run starts it locally in Docker, and a deploy creates it as RDS or Cloud SQL. The OpenAI key is a secret, set once per environment and stored in your cloud's secret manager rather than in the repository, so a coding agent working in the repo cannot read the production value. A local override in .secrets.local.cue is readable if it is present.
The migration only creates the app's own table. Mastra creates its memory tables itself on first use.
-- support/migrations/1_create_orders.up.sql
CREATE TABLE orders (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
status TEXT NOT NULL,
carrier TEXT,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX orders_user ON orders (user_id);
// support/db.ts
import { SQLDatabase } from "encore.dev/storage/sqldb";
export const db = new SQLDatabase("support", { migrations: "./migrations" });
db.connectionString returns the connection string for whichever environment the code runs in, which is how ORMs and other libraries connect to an Encore database. Mastra's PostgresStore uses it the same way.
createTool takes an id, a description the model reads, a Zod input schema and an execute function. In Mastra 1.x, execute receives the parsed input as its first argument and an execution context as its second.
The tool only returns orders that belong to the signed-in user. The model chooses the order ID, so the ownership check has to happen in code rather than in the prompt.
// support/tools.ts
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
import { db } from "./db";
export function lookupOrderTool(userId: string) {
return createTool({
id: "lookup-order",
description: "Look up the status and carrier of one of the user's orders by order ID.",
inputSchema: z.object({ orderId: z.string() }),
outputSchema: z.object({
found: z.boolean(),
status: z.string().optional(),
carrier: z.string().optional(),
updatedAt: z.string().optional(),
}),
execute: async ({ orderId }) => {
const row = await db.queryRow<{ status: string; carrier: string | null; updated_at: Date }>`
SELECT status, carrier, updated_at FROM orders
WHERE id = ${orderId} AND user_id = ${userId}`;
if (!row) return { found: false };
return {
found: true,
status: row.status,
carrier: row.carrier ?? undefined,
updatedAt: row.updated_at.toISOString(),
};
},
});
}
The model key is a secret. Secret values are read at runtime, so the provider is created inside a function rather than at module load. Memory keeps the last 20 messages of each thread and stores them through PostgresStore, which points at the service's own database.
// support/agent.ts
import { Agent } from "@mastra/core/agent";
import { Memory } from "@mastra/memory";
import { PostgresStore } from "@mastra/pg";
import { createOpenAI } from "@ai-sdk/openai";
import { secret } from "encore.dev/config";
import { db } from "./db";
import { lookupOrderTool } from "./tools";
const openaiKey = secret("OpenAIKey");
let memory: Memory | undefined;
function getMemory(): Memory {
memory ??= new Memory({
storage: new PostgresStore({ id: "support-memory", connectionString: db.connectionString }),
options: { lastMessages: 20 },
});
return memory;
}
export function supportAgent(userId: string): Agent {
const openai = createOpenAI({ apiKey: openaiKey() });
return new Agent({
id: "support-agent",
name: "Order support",
instructions:
"You help customers with questions about their orders. " +
"Always call lookup-order before describing an order. " +
"If the order is not found, say so and ask the customer to check the ID.",
model: openai("gpt-5-mini"),
tools: { lookupOrder: lookupOrderTool(userId) },
memory: getMemory(),
});
}
The agent is built per request so the tool is bound to the caller's user ID. The Memory instance, and with it the Postgres connection pool, is created once and shared.
An auth handler validates the Authorization header before any endpoint marked auth: true runs. The example checks a token against a secret, which is enough to try the flow. Replace it with your real session or JWT check.
// support/auth.ts
import { APIError, Gateway, Header } from "encore.dev/api";
import { authHandler } from "encore.dev/auth";
import { secret } from "encore.dev/config";
const demoToken = secret("DemoToken");
interface AuthParams {
authorization: Header<"Authorization">;
}
interface AuthData {
userID: string;
}
export const auth = authHandler<AuthParams, AuthData>(async (params) => {
// Demo only: "Bearer <token>:<userID>". Swap in your session or JWT check.
const [token, userID] = params.authorization.replace("Bearer ", "").split(":");
if (token !== demoToken() || !userID) {
throw APIError.unauthenticated("invalid token");
}
return { userID };
});
export const gateway = new Gateway({ authHandler: auth });
The chat endpoint passes the user ID from the auth data as Mastra's resource and builds the thread ID from the user ID plus the ID in the path. Mastra loads history by thread, so prefixing it with the user ID keeps one user from reading another user's conversation by guessing a thread ID.
// support/chat.ts
import { api } from "encore.dev/api";
import { getAuthData } from "~encore/auth";
import { supportAgent } from "./agent";
interface ChatRequest {
threadId: string;
message: string;
}
interface ChatResponse {
reply: string;
}
export const chat = api(
{ expose: true, auth: true, method: "POST", path: "/chat/:threadId" },
async ({ threadId, message }: ChatRequest): Promise<ChatResponse> => {
const { userID } = getAuthData()!;
const result = await supportAgent(userID).generate(message, {
memory: { thread: `${userID}:${threadId}`, resource: userID },
maxSteps: 5,
});
return { reply: result.text };
},
);
Set the secrets for local development, then start the app. encore run starts Postgres in Docker, applies the migration, and serves the API on port 4000 with a local dashboard for traces.
Insert a test order with encore db shell support and ask about it:
A second message on t1 such as "Which carrier was that again?" is answered from memory, because Mastra loads the earlier turns for that thread and resource. The trace in the local dashboard shows the HTTP request and the SQL queries, including the ones PostgresStore runs against its own tables.
Set the production values, then push:
In the Encore dashboard, connect your AWS or GCP account and create an environment on it. For this app, a deploy creates one Postgres database (RDS on AWS, Cloud SQL on GCP), stores both secrets in Secrets Manager or Secret Manager, and runs the service as a container on ECS Fargate or Cloud Run. Encore provisions an IAM role for the service, or a service account on GCP. A deploy fails if a secret the code uses has no value in that environment, so a missing key shows up before traffic does.
If you prefer the standalone server, the work splits into the same pieces, owned by you:
mastra build writes a Node.js server to .mastra/output. Wrap it in a Dockerfile on a Node.js 22.13 or later base image and push it to ECR or Artifact Registry.PostgresStore. The Mastra server guide warns against keeping a SQLite database file in the folder that gets copied into the build output.This is a reasonable amount of Terraform or console work for one agent, and it is repeated for each environment. The difference with the Encore route is where the database and secrets are declared, not what gets created in your account.
PostgresStore creates and alters its tables on first use. For tighter control, set disableInit: true and run storage.init() from your deploy pipeline instead.lookup-order does, and keep write tools behind explicit confirmation.maxSteps: 5 on the generate call caps the loop. Keep a cap and return a clear error when the model provider is slow.@ai-sdk/anthropic and an AnthropicKey secret.Either build the standalone Mastra server with mastra build and run the output as a container on ECS, Cloud Run or a VM, with a Postgres database and a secret store you set up yourself, or call the agent from an API endpoint in an existing TypeScript backend and deploy that backend. Both need a Postgres database for memory and a secret for the model API key.
Memory needs a storage adapter. PostgresStore from @mastra/pg takes a connection string and creates its own tables on first use, so production memory can live in the same Postgres database as the rest of your data. Pass a thread and a resource on each generate call so history is grouped per conversation and per user.
No. Mastra ships a Hono-based server you can build with mastra build, but an Agent is a plain TypeScript object. You can construct it in any Node.js process and call agent.generate from your own HTTP handlers.
Mastra's deployment docs list Node.js 22.13.0 or later, Bun, Deno and Cloudflare as supported runtimes.
Yes. With Encore the database and the API key secret are declared in the TypeScript code next to the agent, encore run starts Postgres locally, and a git push provisions RDS or Cloud SQL and Secrets Manager or Secret Manager in your own AWS or GCP account.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.