Skip to main content

mountRestrictedAgentControllerOnMastra()

beta

Breaking changes may occur without a major version bump until the API is stable.

The mountRestrictedAgentControllerOnMastra() function creates a Mastra Code controller without reading local environment files, settings, authentication caches, repository instructions, Git metadata, or installed binaries. Use it when a credentialed server must define the complete authority available to the controller.

Import this function from the dedicated @mastra/code-sdk/restricted entry point. The main package entry point loads the local Mastra Code factory and its discovery features.

Usage example
Direct link to Usage example

Create the model, workspace, and storage with credentials and providers owned by the embedding server:

src/mastra/index.ts
import { createOpenAI } from '@ai-sdk/openai'
import { mountRestrictedAgentControllerOnMastra } from '@mastra/code-sdk/restricted'

const openai = createOpenAI({ apiKey: tenantCredentials.openaiApiKey })

const { mastra, controller } = await mountRestrictedAgentControllerOnMastra({
project: {
resourceId: project.id,
name: project.name,
rootPath: project.workspacePath,
gitBranch: project.branch,
},
model: openai('gpt-5.6'),
instructions: 'Work only through the tools and workspace provided by this server.',
modes: [
{
id: 'build',
name: 'Build',
metadata: { default: true },
},
],
allowedTools: ['view', 'write_file', 'execute_command', 'lookup_ticket'],
tools: {
lookup_ticket: ticketTools.lookup,
},
workspace: remoteWorkspace,
storage: tenantStorage,
memory: tenantMemory,
})

const session = await controller.createSession({ resourceId: tenant.id })

The allowlist applies to every mode. A mode can narrow its own access with availableTools, but it can't add a tool that isn't in allowedTools. Tools omitted from the allowlist remain hidden even if session state changes later.

Security boundary
Direct link to Security boundary

The factory prevents Mastra Code itself from discovering ambient host capabilities. The model, workspace, storage, memory, tools, processors, routes, and callbacks you inject are trusted host code and remain responsible for their own filesystem, process, credential, and network access. In particular, allowedTools controls which tools the model can see and call. It doesn't sandbox the implementation of an allowed tool.

Session state can't turn on automatic tool approval. yolo stays false, and permissionRules keeps an allow policy only when initialState.permissionRules already sets that tool or category to allow. Clients can still set ask or deny and answer approval prompts, including approving every call in a category from a prompt. Session tags are seeded into session state, so createSession() rejects a tag that names a state field, such as skipGlobalInstructions, projectPath, or an observer model, and the session route answers 400. Use other tag names to scope threads.

The backing codeAgent isn't registered on the Mastra instance, so mastra.listAgents() and the standard /agents routes can't list it or run it outside the controller's tool approval. For the same reason, notifications sent to a session are persisted but never delivered to the agent, because deferred deliveries and retries run through Mastra's notification dispatcher, outside the controller.

The Mastra server itself isn't restricted. Its standard routes, such as GET /agents/providers, report which model providers have API keys in the server's environment variables. Keep tenant credentials out of the process environment, or protect those routes with server authentication.

Disabled capabilities
Direct link to Disabled capabilities

The restricted factory doesn't register these capabilities:

  • Authentication storage or provider login
  • Built-in model gateways on the controller, so listAvailableModels() returns an empty catalog
  • Browser automation
  • GitHub polling or cross-agent signals
  • Goal judging
  • Project or global hook, plugin, and Model Context Protocol (MCP) discovery
  • Local or global instruction files
  • Observational memory model selection. The observer and reflector model fields in session state stay unset and reject client selections, so configure those models on the injected memory
  • Provider-side fallback models. Selecting a model such as claude-fable-5 in a session doesn't add a fallback to another model
  • Subagents
  • Workflow creation, loading, or execution

The factory also skips gateway synchronization, local thread locks, model usage persistence, built-in web tools, and default workspace tools outside the injected workspace. Add a capability only through a future restricted configuration field that documents its authority boundary. A remote workspace alone isn't an isolation boundary for the standard factory.

Parameters
Direct link to Parameters

project:

RestrictedProjectMetadata
Explicit resource id, display name, workspace path, and optional branch. The factory does not verify these values against the host.

model:

RestrictedModel
Pre-resolved model instance or resolver. Construct the model with host-owned credentials.

instructions:

AgentConfig["instructions"]
Complete system instructions. Repository and global instruction files are not appended.

modes:

RestrictedMode[]
Explicit controller modes. At least one mode is required. A mode can't define its own agent, because it would replace the host model, instructions, and tools.

allowedTools:

string[]
Global allowlist for host and workspace tools. An empty array creates a tool-free agent.

tools?:

RestrictedToolProvider
Host-supplied non-workspace tools. Entries outside allowedTools are removed.

workspace:

Workspace
Host-supplied workspace. The factory has no local workspace fallback.

storage:

MastraCompositeStore
Host-supplied storage. The factory has no settings-based storage fallback.

memory:

AgentControllerConfig["memory"] | false
Host-supplied memory, or false to disable memory.

initialState?:

Partial<MastraCodeState>
Host-supplied initial state. Values in project take precedence over matching state fields. The factory always sets yolo to false, skips global instructions, clears plugin paths, and disables observational memory model selection. Session state can only use the allow permission rules set here.

inputProcessors?:

InputProcessor[]
Trusted host-supplied input processors. No processors are discovered or added by default.

postToolObserver?:

(context: ToolAfterHookContext) => void | Promise<void>
Trusted host callback invoked after tool calls. It cannot add or replace tools.

pubsub?:

PubSub
Host-supplied event transport.

idGenerator?:

AgentControllerConfig["idGenerator"]
Host-supplied identifier generator for controller resources.

mastra?:

Mastra
Existing Mastra instance to mount onto. When omitted, the function creates one.

controllerId?:

string
Registration key for the controller. Defaults to the controller id.

buildApiRoutes?:

(deps: { controller: AgentController }) => ApiRoute[]
Builds explicit server API routes from the restricted controller. Ignored when mastra is provided.

buildServerConfig?:

(deps: { controller: AgentController }) => ServerConfig
Builds additional server configuration from the restricted controller. Ignored when mastra is provided.

Returns
Direct link to Returns

The function returns the initialized controller, its mastra instance, and the exact injected storage, memory, and workspace. It also returns allowedTools, projectPath, and the backing codeAgent.

Use createRestrictedMastraCodeAgentController() from the same entry point when the host owns controller registration and initialization.