Join our Newsletter — 33% off our NHI Course
Home› Guides› Mastra Agent Framework Security Guide: Locking Down Tools,…
Guide MCP, Protocols & Agent Platforms

Mastra Agent Framework Security Guide: Locking Down Tools, Memory, Sandboxes and Servers

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 18 November 2026 16 min read
On this page

Mastra makes it quick to turn a TypeScript application into an agent platform, and that speed means its security defaults, from open server routes to an unisolated local sandbox, need deliberate attention before anything reaches production. This guide walks through the parts of a Mastra deployment that carry the most identity and data risk: authentication on the generated server, tool and sandbox execution, memory scoping, guardrail processors, the MCP and A2A surfaces, Studio and traces, and the credentials an agent holds. It is written for platform engineers, application security teams and identity teams who own Mastra services or are about to approve one.

If you need a product overview first (what Mastra is, its licence, versions and pricing), read our What Is Mastra? TypeScript Agent Framework Explained guide. This page assumes you know the basics and focuses on hardening.

This is an independent guide from NHI Mgmt Group, based on Mastra's public documentation as of November 2026. It is not sponsored or reviewed by Mastra. Product features change, so confirm settings against Mastra's current documentation.

Key takeaways

  • Authentication in Mastra is optional. Mastra's documentation states that if no auth is configured, all routes and Studio are publicly accessible. Treat a missing server.auth block as a release blocker.
  • The default protected pattern covers /api/*. If you change server.apiPrefix, you must update server.auth.protected and server.auth.public or the built-in agent and workflow routes fall outside protection.
  • LocalSandbox runs commands on the host with the application's permissions and is not isolated by default. Use native isolation (seatbelt or bwrap) or a remote container sandbox for anything an agent generates.
  • Memory isolation depends entirely on correct resource and thread IDs. Derive them on the server from the authenticated user, never from the request body.
  • Guardrail processors such as PromptInjectionDetector and PIIDetector default to errorStrategy: 'warn' when the guardrail model fails. Set 'strict' where unchecked content must not proceed.
  • Environment variables passed to a sandbox are visible to code running there, and Mastra has no backend-neutral credential broker. Give agents narrowly scoped, short-lived credentials.

The Mastra attack surface in one view

A typical Mastra application registers agents, tools, workflows and memory on a Mastra instance, then runs mastra build to produce a Hono-based server. According to the server documentation, that server exposes registered agents and workflows as API endpoints, a built-in MCP server at /api/mcp, A2A agent cards and task streams, and experimental OpenAI-compatible Responses and Conversations routes. Studio, the developer console, sits alongside and can show traces of every request.

From a non-human identity point of view, each of those surfaces is a door into the same agent, and the agent in turn holds credentials for models, databases, storage and third-party APIs. The security questions are therefore familiar ones:

  • Who can call the agent, and is that caller authenticated on every route?
  • What can the agent do when it acts, through tools, sandboxes and workspace filesystems?
  • What does the agent remember, and can one user's memory leak into another user's session?
  • Which secrets does the agent process hold, and where can they surface?
  • What evidence is recorded, and who can read it?
SurfaceMain riskPrimary control in Mastra
Generated API routesUnauthenticated agent and workflow executionserver.auth, protected and public patterns
MCP server at /api/mcpTool exposure to any MCP clientSame auth and permissions as the HTTP API
Tools and sandboxesCommand execution on the hostSandbox isolation, requireApproval, tool enablement
MemoryCross-user data leakage, memory poisoningresource and thread scoping, server-side scopes
Model input and outputPrompt injection, PII and system prompt leakageInput, output and hybrid processors
Studio and tracesSensitive prompts and observations visible to staffstudio.auth, RBAC provider

Authenticate every route before anything else

The single most important setting in a Mastra deployment is server.auth. The auth documentation is explicit that authentication is optional and that with no provider configured, all routes and Studio are open. A developer laptop on localhost hides that risk; a container bound to 0.0.0.0 behind a public load balancer does not.

Mastra ships two built-in providers. Simple Auth maps tokens to users and is described as intended for development and API keys. JSON Web Token verifies HMAC-signed JWTs. Third-party integrations are documented for Auth0, Better Auth, Clerk, Firebase, Google, Neon, Okta, Supabase and WorkOS, and Composite Auth lets you combine providers. A Custom Provider option exists if none fit.

Once a provider is set, it protects both Studio and API routes by default. The documented defaults protect /api/*, treat /api and /api/auth/* as public, and keep GET /api/auth/capabilities public so Studio can detect login state. Three practical points follow:

  • Custom prefixes. If you set a custom server.apiPrefix, update server.auth.protected and server.auth.public to match. Otherwise built-in routes such as the agents and workflows endpoints fall outside the protected pattern.
  • Public custom routes. Custom routes can opt out with requiresAuth: false. Review every instance in code review and keep a list; an opt-out on a route that calls an agent is equivalent to anonymous agent access.
  • Studio separation. Setting studio.auth gives Studio its own provider, and Studio requests then use it exclusively while other requests keep using server.auth. This is a useful way to put Studio behind workforce SSO while API clients use service tokens.

Our recommendation: use a real identity provider or JWT verification in production, reserve Simple Auth for local work, and add an automated test that calls each built-in route without a token and expects a rejection. The Agent Identity and Access Guide covers how to give each calling service its own identity rather than a shared token.

Tools, sandboxes and command execution

Tools are where an agent stops talking and starts acting. Mastra's createTool() pattern makes it easy to wrap any function, and workspaces add generated tools for filesystems and sandboxes. The sandbox documentation lists execute_command, get_process_output and kill_process as generated tools, with execute_command able to run in the background.

Choose the right sandbox

Mastra documents a LocalSandbox and a long list of remote or container providers, including AgentCore, Apple Container, Blaxel, Cloudflare Sandbox, Daytona, Docker, E2B, Modal, Railway, Fly.io Sprites, Vercel and a Mastra platform sandbox. The documentation warns that LocalSandbox runs commands on the host by default and is not isolated or secure. It offers native isolation through isolation: 'seatbelt' on macOS and 'bwrap' on Linux, with nativeSandbox options such as allowNetwork and readOnlyPaths, and LocalSandbox.detectIsolation() to check what is available.

For any agent that runs model-generated code, the safe baseline is a remote or container sandbox. If you must run locally, turn on native isolation, set allowNetwork to false unless the task needs it, and mark source and configuration paths read-only. Our AI Agent Sandboxing and Code Execution Guide explains the isolation trade-offs in more depth.

Separate sandboxes per user

A static sandbox is shared by every request and memory thread that uses the agent. Mastra recommends a resolver for per-user or per-thread separation. Sandboxes created by a resolver are your application's responsibility: workspace.destroy() does not destroy them, so your code must destroy them and call clearSandboxCache(). Build that clean-up into session end and into a scheduled sweep, or orphaned sandboxes will keep credentials and files alive.

Network and ports

Network defaults vary by backend. The documentation notes that Daytona allows outbound access unless you configure a restriction, using settings such as networkBlockAll, domainAllowList and networkAllowList. Ports exposed through getPortUrl() may be reachable by others depending on the backend's access controls. Apply an egress allowlist for every sandbox and avoid exposing ports unless a human needs them; see the Agent Egress Control and Network Isolation Guide.

Approval and tool enablement

Workspace tool configuration supports a top-level requireApproval option that applies to every generated sandbox tool unless a per-tool entry overrides it. Individual tools can also be disabled or renamed through constants such as WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND, and per-tool enabled flags override a global setting. A sound pattern is to disable every generated tool the agent does not need, require approval on command execution and file writes, and leave read-only tools unapproved. The Human-in-the-Loop for AI Agents Guide covers how to design approvals that people actually read.

Memory scoping and isolation

Mastra memory combines message history (on by default), Observational Memory (background compression of older messages), working memory (structured facts injected as a system message) and semantic recall (retrieval of relevant past content, including from other threads). All of it lives in a storage provider you configure.

The isolation model is ID-based. A resource identifies a user or entity, and a thread isolates a conversation. The memory documentation states that working memory and semantic recall default to scope: 'resource', Observational Memory defaults to scope: 'thread', and agents sharing a resourceId share working memory and embeddings across threads. It does not describe a separate access-control model; isolation depends on assigning IDs correctly.

That makes ID assignment a security control. Recommended practice:

  • Derive the resource ID from the authenticated subject on the server, for example the verified JWT subject plus tenant, never from a client field.
  • Use the server-side scope mechanisms. Mastra's documentation says clients cannot send scopes in request bodies and that scopes must come from the request context, the agent's scopes resolver or trusted middleware using MASTRA_SCOPES_KEY.
  • Remember that request bodies can set unreserved request context keys. Any resolver input that decides scope should come from server code, not from that context.
  • For multi-tenant products, include the tenant in the resource ID so semantic recall cannot match content across organisations.
  • Note that subagents in delegation get a fresh thread per call and a resource ID of {parentResourceId}-{agentName}, so different subagents do not share memory through delegation. Do not override this without a reason.

Memory is also a persistence channel for attacks. Content an agent reads from a tool or document can be written into working memory and replayed in every future session. Treat memory writes as untrusted input, keep retention short and give users a way to clear their memory. Our AI Agent Memory Security Guide and AI Agent Memory Poisoning Guide go further.

Guardrail processors and their failure modes

Mastra implements guardrails as processors that run before input reaches the model, after the model responds, or both. The documented built-ins include:

  • Input: UnicodeNormalizer, PromptInjectionDetector (an LLM-based classifier for injection, jailbreak and system override attempts) and LanguageDetector.
  • Output: BatchPartsProcessor and SystemPromptScrubber, which redacts system prompts and internal instructions.
  • Hybrid: ModerationProcessor, PIIDetector and TokenCostControl, which enforces a cumulative cost limit with maxCost, scope and window.

Strategies include block, warn, detect, redact, rewrite and translate. Only block calls abort() and stops the request; most other strategies let the request continue. Blocked requests surface as result.tripwire from generate() or as tripwire chunks in a stream, and an onViolation callback receives the processor ID and details.

Two settings matter most:

  • Fail closed where it counts. Model-backed processors, apart from ClassifierProcessor, default to errorStrategy: 'warn'. If the guardrail model times out, content proceeds unchecked. Set errorStrategy: 'strict' for injection detection on agents with write tools.
  • Log violations. Wire onViolation to your security log pipeline. The documentation notes it does not fire for every case (for example ModerationProcessor warnings), so also record tripwire results.

Processors reduce risk but do not remove it. An LLM-based injection detector is probabilistic, and indirect injection can arrive through tool results rather than user input. Pair processors with least-privilege tools and approvals, as described in Prompt Guardrails vs Policy Engines for AI Agent Actions. TokenCostControl is described as approximate and needs observability storage that supports metric aggregates, so keep provider-side spending limits as well.

MCP, A2A and other protocol surfaces

The server documentation states that the built-in MCP server at /api/mcp uses the same auth and permissions as the HTTP API, and that A2A exposes agent cards, task streams and push notifications. The experimental Responses and Conversations routes run requests through a selected agent and can continue stored turns.

Every protocol surface multiplies the number of clients that can reach an agent's tools. Before enabling them:

  • Confirm the MCP and A2A paths sit inside your protected route pattern, especially if you changed the API prefix.
  • Expose through MCP only the tools you intend external clients to call. A tool that is safe behind a curated chat interface may not be safe for an arbitrary MCP client.
  • Review what A2A agent cards disclose, and restrict push notification targets to known endpoints.
  • Treat experimental routes as off in production until you have tested their auth behaviour.

If your Mastra agents consume external MCP servers as clients, the same supply chain concerns apply as for any MCP deployment; see the MCP Security Guide and MCP Server Security Checklist.

Credentials and non-human identities held by agents

A Mastra agent process typically holds model provider keys, a storage connection string, vector store credentials, and API tokens used by tools. Those are non-human identities, and they deserve the same lifecycle treatment as any service account.

  • Sandbox environment variables. The sandbox documentation warns that environment variables passed to a sandbox are visible to code running there, and that Mastra has no backend-neutral credential broker. Never pass the application's own model or database keys into a sandbox. Issue a separate, narrowly scoped credential per task.
  • Tool credentials. Resolve credentials inside the tool implementation from a secrets manager at call time, scoped to the calling user where the downstream API supports delegation. Avoid putting tokens into prompts or instructions; see Runtime Secrets Injection for AI Agents Without Prompt Exposure.
  • Stream redaction. The server documentation says stream data redaction removes system prompts, tool definitions, API keys and similar data from each chunk and is on by default, configurable only through server adapters. Leave it on, and test that a deliberately leaked test key does not appear in client streams.
  • Storage credentials. Memory requires a storage provider, which then holds every conversation. Give the application its own database role with no administrative rights and rotate it on the same schedule as other service credentials.

Build an inventory that lists each Mastra service, the credentials it holds, the owner and the rotation date. The Secrets in Prompts vs Brokered Credentials guide explains why brokered access is the target state.

Studio, traces and deployment hygiene

Studio is useful precisely because it shows everything: prompts, messages, observations and tool calls. The memory documentation advises reviewing access to Studio because traces may contain sensitive content. Treat Studio as a privileged administrative console.

  • Put Studio behind workforce SSO using studio.auth, and configure an RBAC provider so Studio enforces role-based access for what each team member can see and do.
  • Decide whether Studio runs in production at all. If it does, restrict it to a private network or VPN.
  • OpenAPI (/api/openapi.json) and Swagger UI (/swagger-ui) are disabled in production by default according to the server documentation. Keep them off, or protect them if you enable them with server.build.openAPIDocs or server.build.swaggerUI.
  • The server binds to localhost by default through MASTRA_HOST; binding to 0.0.0.0 should be a conscious decision backed by auth and a network policy.
  • Pin Mastra package versions and review dependency updates. Agent frameworks are high-value supply chain targets, and a lockfile plus provenance checks limit the blast radius of a compromised release.
  • Send traces to an observability backend with its own access control and retention limits, and redact PII where your processors have not already done so. See the AI Agent Observability and Incident Response Guide.

Common failure patterns

  • No auth provider in production. The service works in testing, ships with no server.auth, and every agent and workflow route is open to the internet.
  • Prefix drift. A team changes server.apiPrefix for routing reasons and leaves the protected pattern on /api/*, silently exposing built-in routes.
  • Local sandbox in a container. LocalSandbox without isolation is assumed safe because "it is in a container", while the container also holds the application's model and database keys.
  • Client-controlled resource IDs. The front end sends a user ID that becomes the memory resource, letting one user read another's working memory by changing a field.
  • Guardrails that fail open. The injection detector model is rate-limited under load and the default warn error strategy lets unchecked input through to an agent with write tools.
  • Shared static sandbox. One sandbox serves every user, so files and processes from one session are visible to the next.
  • Studio on the public internet. Traces with customer conversations and system prompts are readable by anyone who finds the URL.

Practitioner checklist

  • Configure server.auth with a production identity provider or JWT verification and test every built-in route without credentials.
  • Align server.auth.protected and server.auth.public with any custom server.apiPrefix, and list every requiresAuth: false route with an owner.
  • Use a remote or container sandbox, or native isolation, for any command execution; disable network access and expose no ports by default.
  • Use a sandbox resolver for per-user or per-thread separation and implement destruction plus clearSandboxCache().
  • Set requireApproval on command execution and write tools, and disable generated tools the agent does not need.
  • Derive memory resource and thread IDs from authenticated server-side identity, including tenant.
  • Set errorStrategy: 'strict' on injection and PII processors for agents with write tools, and route onViolation and tripwire events to security logging.
  • Keep stream redaction on, pass only task-scoped credentials into sandboxes, and inventory every credential each Mastra service holds.
  • Protect Studio with studio.auth and RBAC, keep it off the public internet, and keep OpenAPI and Swagger off in production.
  • Pin Mastra dependencies and review updates before deploying them.

Standards and references

Related NHI Mgmt Group resources: What Is Mastra? TypeScript Agent Framework Explained · Agent Identity and Access Guide · AI Agent Sandboxing and Code Execution Guide · Agent Egress Control and Network Isolation Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.