mastra-workspace-sandbox
Skill2 starsChanged 29 days agoApache-2.0View on GitHub
Give Mastra agents a Workspace: a filesystem for reading, writing, and searching files, a sandbox for shell commands and background processes, computer-use desktop control, LSP code inspection, BM25 or vector search, and filesystem-backed skills. Use this skill whenever the user wants an agent to run code, execute shell commands, clone and test a repo, edit files, keep files between runs, mount S3 or GCS into a sandbox, isolate each user or thread in its own sandbox, or control a remote desktop. Triggers on Workspace, @mastra/core/workspace, LocalSandbox, LocalFilesystem, WORKSPACE_TOOLS, execute_command, mounts, CompositeFilesystem, sandboxCacheKey, autoIndexPaths, E2BSandbox, DaytonaSandbox, DockerSandbox, VercelSandbox, ModalSandbox, RailwaySandbox, PlatformSandbox, S3Filesystem, GCSFilesystem, seatbelt, bwrap, computer use, lsp_inspect. Also triggers for coding agents, code interpreters, and file-processing agents even if the user never says workspace.
- Reads credentials
In this repository46 other files it gives its agents.
- mastra-a2a-acpSkill
- mastra-agent-approval-hitlSkill
- mastra-agentic-uiSkill
- mastra-agent-skillsSkill
- mastra-agentsSkill
- mastra-authSkill
- mastra-browserSkill
- mastra-build-playbookSkill
- mastra-channelsSkill
- mastra-classifierSkill
- mastra-cli-apiSkill
- mastra-client-sdkSkill
- mastra-datasets-experimentsSkill
- mastra-deploymentSkill
- mastra-evalsSkill
- mastra-file-based-agentsSkill
- mastra-framework-integrationSkill
- mastra-guideSkill
- mastra-harnessSkill
- mastra-knowledgeSkill
- mastra-mcpSkill
- mastra-memorySkill
- mastra-migrationsSkill
- mastra-modelsSkill
- mastra-multi-agentSkill
- mastra-observabilitySkill
- mastra-observational-memorySkill
- mastra-platformSkill
- mastra-processors-guardrailsSkill
- mastra-project-setupSkill
- mastra-ragSkill
- mastra-schedulesSkill
- mastra-semantic-recallSkill
- mastra-serverSkill
- mastra-signalsSkill
- mastra-storageSkill
- mastra-streamingSkill
- mastra-structured-outputSkill
- mastra-studio-editorSkill
- mastra-tool-integrationsSkill
- mastra-toolsSkill
- mastra-troubleshootingSkill
- mastra-vector-storesSkill
- mastra-voiceSkill
- mastra-workflowsSkill
- mastra-workflow-suspend-resumeSkill
The file
We split this skill into the rules it gives an agent
6 rules. About 0 are common, 0 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 51
If the code is untrusted, never default to an unisolated LocalSandbox.
- Very specific: line 98
Verify the API: If node_modules/@mastra/ exists, read node_modules/@mastra/core/dist/docs/ and the installed Workspace types, plus the …
- Very specific: line 105
Plan the lifecycle: Call workspace.init() at startup only when you want early errors or autoIndexPaths.
- Very specific: line 145
If the agent's workspace option is a function, keep it cheap.
- Very specific: line 154
Static
mountswith a sandbox resolver: Not supported. Mount inside the resolver with sandbox.mount(fs, path). - Very specific: line 162
Passing
process.envto the sandbox: Every command sees every secret.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Mastra Workspace and Sandbox
Configure a Workspace so an agent can read and write files, run commands in an isolated environment, search indexed content, and inspect code, with the right isolation and lifecycle.
When to use
- An agent must run shell commands, tests, builds, or scripts (
execute_command) - An agent must read, write, edit, or grep files in a directory or bucket
- Files must outlive an ephemeral sandbox (mount S3, GCS, or Azure Blob into it)
- Each user, tenant, or memory thread needs its own sandbox or storage prefix
- Picking a sandbox provider (local, Docker, E2B, Daytona, Vercel, Modal, Railway, Mastra Platform, others)
- Restricting workspace tools: approval, read-before-write, renaming, disabling, hooks
- Keyword or semantic search over workspace files (
bm25,vectorStore,autoIndexPaths) - Type-aware code inspection (
lsp) or desktop control (computer use)
When NOT to use
- Web browsing with browser tools (use
mastra-browser) - Defining skills in agent code with
createSkill(), or skill format details (usemastra-agent-skills) - Writing custom tools with
createTool(usemastra-tools) - Generic tool approval flows and resuming suspended runs (use
mastra-agent-approval-hitl) - RAG pipelines with chunking and vector query tools (use
mastra-rag) - Choosing a vector database (use
mastra-vector-stores) - Durable coding-agent runtimes and background tasks (use
mastra-harness) - Delegating to an external coding agent such as Claude Code over ACP (use
mastra-a2a-acp)
Required inputs
- What the agent does with the workspace: files only, commands, or both
- Trust level of the code it runs (trusted dev scripts vs untrusted user code)
- Scope: one shared environment, or one per user, tenant, or thread
- Where files must persist (local disk, S3, GCS, Azure, Google Drive, Platform bucket)
- Network policy: which outbound hosts commands may reach
- Which credentials commands need, and their minimum scope
If the code is untrusted, never default to an unisolated LocalSandbox.
The framework: filesystem plus sandbox, attached to an agent
A Workspace combines up to four capabilities. Each one adds agent tools automatically.
| Config | Adds tools | Notes |
filesystem or mounts | mastra_workspace_read_file, write_file, edit_file, list_files, delete, file_stat, mkdir, grep (ast_edit, apply_patch opt-in) | Configure one, never both (INVALID_CONFIG) |
sandbox | mastra_workspace_execute_command, get_process_output, kill_process | Process tools need a process manager |
bm25 and/or vectorStore + embedder | mastra_workspace_search, mastra_workspace_index | Index is separate from files |
lsp | mastra_workspace_lsp_inspect | Needs a static sandbox with a process manager |
skills | skill, skill_read, skill_search | See mastra-agent-skills |
import { Agent } from '@mastra/core/agent'
import { LocalFilesystem, LocalSandbox, Workspace } from '@mastra/core/workspace'
export const codingAgent = new Agent({
id: 'coding-agent',
name: 'Coding agent',
instructions: 'Use the sandbox to complete coding tasks.',
model: 'openai/gpt-6.1-sol',
workspace: new Workspace({
filesystem: new LocalFilesystem({ basePath: './workspace' }),
sandbox: new LocalSandbox({ workingDirectory: './workspace' }),
}),
})Attach a workspace to one agent (workspace option), or to the Mastra instance (new Mastra({ workspace })). Agents without their own workspace inherit the Mastra-level one.
Who shares a sandbox
| Configuration | Shared by |
| Mastra-level | Every agent that inherits it |
| Agent-level static sandbox | Every request and thread of that agent |
Resolver + sandboxCacheKey on user ID | One sandbox per user |
Resolver + sandboxCacheKey on thread ID | One sandbox per memory thread |
Workflow
- Verify the API. If
node_modules/@mastra/exists, readnode_modules/@mastra/core/dist/docs/and the installedWorkspacetypes, plus the provider package docs (for examplenode_modules/@mastra/e2b/dist/docs/). Otherwise fetchhttps://mastra.ai/docs/sandbox/overview.mdandhttps://mastra.ai/reference/workspace/workspace-class.md. Trust these over memory. - Pick the capability set. Files only:
filesystem. Commands: addsandbox. Programs need the files by path: usemountswith a mount-capable sandbox. - Pick providers.
LocalSandboxfor trusted local work, a container or remote sandbox for untrusted code (seereferences/providers.md). Install the provider package and set its env vars. - Set isolation and network. For
LocalSandbox, setisolation: 'seatbelt'(macOS) or'bwrap'(Linux), check withLocalSandbox.detectIsolation(). For remote sandboxes, apply the provider's network restriction at creation. - Scope it. Static for a shared environment. For per-user or per-thread, use a
sandboxresolver plussandboxCacheKey, and mount storage inside the resolver. - Set tool policies.
requireApprovalglobally or per tool,requireReadBeforeWriteon write tools,enabled: falseon tools you do not want,maxOutputTokenson noisy tools. - Pass only needed secrets.
LocalSandboxexposes onlyPATHby default. Use per-commandenvorsetEnv()for scoped tokens. - Plan the lifecycle. Call
workspace.init()at startup only when you want early errors orautoIndexPaths. Destroy resolver-returned sandboxes yourself and callworkspace.clearSandboxCache(key). - Register and test. Register the agent on
Mastra, runnpx mastra dev, and ask the agent to list files and run a harmless command in Studio.
Deep dive: per-thread sandbox with persistent storage
Static mounts cannot be combined with a sandbox resolver. Mount inside the resolver instead:
import { MASTRA_THREAD_ID_KEY, type RequestContext } from '@mastra/core/request-context'
import { Workspace } from '@mastra/core/workspace'
import { DaytonaSandbox } from '@mastra/daytona'
import { S3Filesystem } from '@mastra/s3'
const getThreadId = (requestContext: RequestContext) =>
requestContext.get(MASTRA_THREAD_ID_KEY) as string
const createThreadFilesystem = (threadId: string) =>
new S3Filesystem({
bucket: process.env.S3_BUCKET!,
region: process.env.S3_REGION!,
prefix: `threads/${threadId}`,
})
const workspace = new Workspace({
filesystem: ({ requestContext }) => createThreadFilesystem(getThreadId(requestContext)),
sandbox: async ({ requestContext }) => {
const threadId = getThreadId(requestContext)
const sandbox = new DaytonaSandbox({ id: `thread-${threadId}`, language: 'typescript' })
await sandbox.start()
await sandbox.mount(createThreadFilesystem(threadId), '/workspace')
return sandbox
},
sandboxCacheKey: ({ requestContext }) => getThreadId(requestContext),
})Your application owns resolver-returned sandboxes. When the thread ends, call destroy() on the sandbox and then workspace.clearSandboxCache(threadId). workspace.destroy() and mastra.shutdown() do not destroy them.
If the agent's workspace option is a function, keep it cheap. Mastra calls it for metadata routes (GET /api/agents) and startup too. Return a workspace with resolvers instead of starting infrastructure inside it.
Failure patterns
- Unisolated
LocalSandboxfor untrusted code. It runs on the host with app permissions. Enableisolation, or use Docker, E2B, Daytona, or another remote sandbox. - Relative paths resolving to odd places. Under
mastra dev,./workspaceresolves insidesrc/mastra/public/. Undermastra start, inside.mastra/output/. Use an absolute path from an env var. - Configuring both
filesystemandmounts. ThrowsWorkspaceErrorINVALID_CONFIG. Pick one. - Static
mountswith a sandbox resolver. Not supported. Mount inside the resolver withsandbox.mount(fs, path). - Write approval on
write_fileonly. Commands can still write the same mounted path. Disableexecute_commandif files must change only through file tools. - Expecting
autoIndexPathsto index on registration. It runs duringworkspace.init(). Awaitworkspace.init()once at startup. - Expecting writes to update the search index. File and index mutations are independent. Call
workspace.index(path, content)after writing. - Leaking per-user sandboxes. Resolver sandboxes keep running. Destroy them and call
clearSandboxCache. - Starting a sandbox inside an agent
workspacefunction. It runs on every metadata request. Use resolvers. - Missing process tools. A static sandbox without a process manager exposes no
get_process_outputorkill_process. With a resolver, an unsupported call throwsSandboxFeatureNotSupportedError. - No computer tools with a resolver. Computer tools register only for a static
DaytonaSandbox(computerUse: true) orE2BDesktopSandbox. - Passing
process.envto the sandbox. Every command sees every secret. Pass only the variables a command needs. - Read-only filesystem resolver still lists write tools. Expected. The provider rejects writes at runtime.
Output format
A finished workspace delivery contains:
- The workspace module (for example
src/mastra/workspace.ts) and its attachment to the agent orMastrainstance - Provider packages in
package.jsonand their env vars in.env.example - The isolation and network choice, stated in a comment or README line
- Tool policy (
toolsconfig) for writes, deletes, and commands - Lifecycle code:
workspace.init()if needed, and cleanup for resolver-backed sandboxes - Evidence: a Studio or script run where the agent lists files and runs one command
Reference files
references/api.md-Workspaceoptions, tool config, methods,LocalSandbox,LocalFilesystem, sandbox interface, process manager, search, LSP.references/examples.md- Isolated local coding agent, S3 mounted into E2B, per-user Daytona sandbox with cleanup, searchable knowledge base.references/providers.md- Every sandbox and filesystem provider: package, class, constructor, env vars, mount and process support.references/checklist.md- Security and production checklist.
Live docs
- https://mastra.ai/docs/sandbox/overview
- https://mastra.ai/docs/sandbox/filesystem
- https://mastra.ai/docs/sandbox/search
- https://mastra.ai/docs/sandbox/lsp
- https://mastra.ai/docs/sandbox/computer
- https://mastra.ai/docs/sandbox/skills
- https://mastra.ai/reference/workspace/workspace-class
- https://mastra.ai/reference/workspace/local-sandbox
- https://mastra.ai/reference/workspace/sandbox
- https://mastra.ai/reference/workspace/process-manager
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

