
How do I expose a Mastra agent/workflow as a REST endpoint for my product backend?
Most teams hit the same wall: you’ve got a Mastra agent or workflow working locally, but now you need to expose it as a REST endpoint your product backend can call reliably. The good news is that Mastra was designed for this—your agents and workflows live in your TypeScript codebase, right next to your existing API routes.
Quick Answer: You expose a Mastra agent or workflow as a REST endpoint by importing it into your backend framework (Next.js API route, Express, Hono, etc.), wiring a handler that calls
Agent.run()/Agent.stream()orworkflow.run(), and returning the result as JSON or a streaming response.
Frequently Asked Questions
How do I expose a Mastra agent as a REST API endpoint in my backend?
Short Answer: Import your Agent into an API route (Next.js, Express, Hono, or any Node server), call .run() or .stream() inside the handler, and return the result as a standard HTTP response.
Expanded Explanation:
In Mastra, agents are just TypeScript objects (Agent instances) that you can call from any server-side context. To expose them over REST, you don’t need a separate “platform”—you define a normal HTTP route, instantiate or import your agent, and forward the request body or query params into agent.run() (for simple calls) or agent.stream() (for chat-like streaming).
This keeps your Mastra agent as part of your product infrastructure: it sits in the same codebase, uses your existing auth, logging, and deployment pipeline, and returns JSON that any client (web app, mobile app, other services) can consume.
Key Takeaways:
- Mastra agents are first-class TypeScript objects you can call from any server-side framework.
- Exposing a REST endpoint is just wiring an HTTP route that calls
agent.run()oragent.stream()and returns the result.
What’s the process to wrap a Mastra workflow as a REST endpoint?
Short Answer: Import your workflow and call workflow.run() inside your route handler, passing in request data as the workflow input, then return the final result as JSON.
Expanded Explanation:
Mastra workflows are designed for multi-step, reliable execution, but the entry point is still a simple function call. You can expose workflow.run(input) behind any REST route. Your backend handles request validation and auth; the workflow handles orchestration, branching, and calls to tools/agents.
If you need background execution (long-running workflows), you can keep the REST endpoint as a “trigger” and delegate execution to a worker (or to a platform like Inngest). For synchronous flows, your API handler can await the workflow’s result directly and send it back to the client.
Steps:
- Define your workflow in your Mastra workspace (e.g.,
src/mastra/workflows/reportWorkflow.ts). - Create an API route in your backend framework (e.g.,
/api/report). - Call
workflow.run()in the route handler with validated request data and return the result as JSON.
What’s the difference between exposing an agent vs a workflow as an endpoint?
Short Answer: Expose an agent when you want conversational or single-step behavior; expose a workflow when you need multi-step orchestration, branching, retries, or background execution behind the endpoint.
Expanded Explanation:
Both agents and workflows are easy to wire to REST, but they serve different roles in your backend:
- An
Agentendpoint is ideal for “ask/answer” or chat-style interactions: one main model call, optional tools, and a structured response. - A
Workflowendpoint is better when you need multiple distinct steps—call APIs, write to a database, then summarize results—possibly with retries, conditional logic, or suspend/resume.
In practice, you might combine them: a workflow step can call an agent, and your REST route simply triggers the workflow.
Comparison Snapshot:
- Agent: Direct prompt-in → response-out; best for chat, question answering, or tools that feel like a single “brain.”
- Workflow: Multi-step orchestrated logic; best for complex flows, pipelines, or anything that might need retries/monitoring.
- Best for: Use an agent endpoint for interactive UX; use a workflow endpoint for business processes and back-office operations.
How do I implement a REST endpoint for a Mastra agent or workflow in Next.js / Express / Hono?
Short Answer: In any framework, create a route, parse the request, call your agent/workflow, and return JSON or a streaming response. The details differ slightly by framework, but the pattern is the same.
Expanded Explanation:
Because Mastra is just TypeScript, you plug it directly into your existing server stack. Below are minimal patterns for Next.js (App Router), Express, and Hono. In each case, you treat the agent or workflow like any other service in your backend.
What You Need:
- A Mastra workspace with an
Agentor workflow defined. - A server-side runtime (Next.js route, Express app, Hono app, serverless function, etc.) where you can import and call Mastra.
Next.js App Router example (Agent endpoint)
// app/api/assistant/route.ts
import { NextRequest } from "next/server";
import { Agent } from "@mastra/core/agent";
// Define your agent in a separate module or here
const assistant = new Agent({
id: "support-agent",
name: "Support Assistant",
description: "Helps answer product questions",
// ...model + tools config
});
export async function POST(req: NextRequest) {
const { message } = await req.json();
const result = await assistant.run({
input: message,
// You can pass any structured context here
});
return new Response(JSON.stringify({ reply: result.output }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
To stream responses to the client:
export async function POST(req: NextRequest) {
const { message } = await req.json();
const stream = await assistant.stream({
input: message,
});
// stream.body is a ReadableStream
return new Response(stream.body, {
status: 200,
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
},
});
}
Express example (Agent endpoint)
// src/server.ts
import express from "express";
import bodyParser from "body-parser";
import { Agent } from "@mastra/core/agent";
const app = express();
app.use(bodyParser.json());
const assistant = new Agent({
id: "support-agent",
name: "Support Assistant",
description: "Helps answer product questions",
// ...model + tools config
});
app.post("/api/assistant", async (req, res) => {
try {
const { message } = req.body;
const result = await assistant.run({
input: message,
});
res.json({ reply: result.output });
} catch (err) {
console.error(err);
res.status(500).json({ error: "Agent execution failed" });
}
});
app.listen(3000, () => {
console.log("Server listening on http://localhost:3000");
});
Hono example (Workflow endpoint)
// src/server.ts
import { Hono } from "hono";
import { Workflow } from "@mastra/core/workflow";
const app = new Hono();
// Define or import your workflow
const reportWorkflow = new Workflow({
id: "weekly-report",
description: "Generate a weekly analytics report",
// define steps here
});
app.post("/api/report", async (c) => {
try {
const body = await c.req.json<{
startDate: string;
endDate: string;
userId: string;
}>();
const result = await reportWorkflow.run({
input: body,
});
return c.json({ report: result.output });
} catch (err) {
console.error(err);
return c.json({ error: "Workflow execution failed" }, 500);
}
});
export default app;
How should I design REST endpoints for Mastra agents/workflows to be safe, scalable, and maintainable?
Short Answer: Treat agent/workflow endpoints like any other core backend surface: validate input, enforce auth, control cost, and instrument observability so you can debug behavior and track performance over time.
Expanded Explanation:
Mastra assumes agents and workflows are part of your infrastructure, not throwaway demos. When you expose them as REST endpoints, you’re opening a critical path into your product. You want the same discipline you’d use for any production API: schema validation, auth/authorization, rate-limiting, logging, and observability.
Mastra gives you control surfaces—processors, evals, observability—to keep these endpoints predictable and cost-aware. You can add processors to sanitize inputs, evals to monitor quality, and observability to trace token usage, latency, and tool calls for each request. For high-traffic setups, back these traces with a durable store (e.g., ClickHouse) instead of an in-memory or local file database.
Why It Matters:
- Safety & cost: Without validation, guardrails, and rate-limiting, a single endpoint can trigger expensive model calls or unsafe tool actions.
- Debuggability & reliability: With observability and evals, you can trace every agent/workflow run, understand failures, and iteratively improve prompts, tools, and flows.
Quick Recap
To expose a Mastra agent or workflow as a REST endpoint for your product backend, you don’t need a new platform—you wire it into your existing server stack. Import your Agent or Workflow, define an HTTP route, pass in validated request data, and return the result as JSON or a streaming response. Use agents for conversational, single-step behavior; use workflows for multi-step orchestration and background work. Treat these endpoints like core infrastructure: secure them, observe them, and iterate as you would any other production service.