Back to Mastra

Reference: Workspace class | Workspace

docs/src/content/en/reference/workspace/workspace-class.mdx

2025-12-1815.1 KB
Original Source

Workspace class

Added in: @mastra/[email protected]

The Workspace class combines a filesystem and sandbox to provide agents with file storage and command execution capabilities. It also supports BM25 and vector search for indexed content.

Usage example

typescript
import { Workspace, LocalFilesystem, LocalSandbox } from '@mastra/core/workspace'

const workspace = new Workspace({
  id: 'my-workspace',
  name: 'My Workspace',
  filesystem: new LocalFilesystem({
    basePath: './workspace',
  }),
  sandbox: new LocalSandbox({
    workingDirectory: './workspace',
  }),
  bm25: true,
  autoIndexPaths: ['/docs'],
})

Constructor parameters

<PropertiesTable content={[ { name: 'id', type: 'string', description: 'Unique identifier for the workspace', isOptional: true, defaultValue: 'Auto-generated', }, { name: 'name', type: 'string', description: 'Human-readable name', isOptional: true, defaultValue: 'workspace-{id}', }, { name: 'filesystem', type: 'WorkspaceFilesystem', description: 'Filesystem provider instance (e.g., LocalFilesystem)', isOptional: true, }, { name: 'sandbox', type: 'WorkspaceSandbox', description: 'Sandbox provider instance (e.g., LocalSandbox)', isOptional: true, }, { name: 'bm25', type: 'boolean | BM25Config', description: 'Enable BM25 keyword search. Pass true for defaults or a config object.', isOptional: true, defaultValue: 'undefined', }, { name: 'vectorStore', type: 'MastraVector', description: 'Vector store for semantic search', isOptional: true, }, { name: 'embedder', type: '(text: string) => Promise<number[]>', description: 'Embedder function for generating vectors. Required when vectorStore is provided.', isOptional: true, }, { name: 'autoIndexPaths', type: 'string[]', description: "Paths or glob patterns to auto-index on init(). Supports glob patterns like '/*.md' for selective indexing.", isOptional: true, }, { name: 'skills', type: 'string[] | ((context: SkillsContext) => string[] | Promise<string[]>)', description: "Paths where SKILL.md files are located. This can be a static array or an async function that resolves paths dynamically. Supports glob patterns like './/skills' for discovery.", isOptional: true, }, { name: 'skillSource', type: 'SkillSource', description: 'Custom skill source for skill discovery. When provided, this source is used instead of the workspace filesystem. Use VersionedSkillSource to serve published skill versions from a content-addressable blob store.', isOptional: true, }, { name: 'onMount', type: 'OnMountHook', description: 'Pre-mount hook called for each filesystem before mounting into a sandbox. Return false to skip mounting, or return { success: true } if the hook handled the mount. Return undefined to use the default mount behavior.', isOptional: true, }, { name: 'searchIndexName', type: 'string', description: "Custom index name for the vector store. Must be a valid SQL identifier (start with a letter or underscore, contain only letters, numbers, or underscores, max 63 characters). Defaults to a sanitized version of '{id}_search'.", isOptional: true, }, { name: 'tools', type: 'WorkspaceToolsConfig', description: 'Per-tool configuration for enabling tools and setting safety options', isOptional: true, properties: [ { type: 'WorkspaceToolsConfig', parameters: [ { name: 'enabled', type: 'boolean', description: 'Whether the tool is available to agents', isOptional: true, defaultValue: 'true', }, { name: 'requireApproval', type: 'boolean', description: 'Whether the tool requires user approval before execution', isOptional: true, defaultValue: 'false', }, { name: 'name', type: 'string', description: 'Custom name to expose this tool as. Replaces the default mastra_workspace_* name. The config key must still use the original WORKSPACE_TOOLS constant.', isOptional: true, }, { name: 'requireReadBeforeWrite', type: 'boolean', description: 'For write tools: require reading the file first to prevent overwrites', isOptional: true, defaultValue: 'false', }, { name: 'maxOutputTokens', type: 'number', description: 'Maximum tokens for tool output. Output exceeding this limit is truncated using tiktoken.', isOptional: true, defaultValue: '2000', }, ], }, ], }, { name: 'operationTimeout', type: 'number', description: 'Timeout for operations in milliseconds', isOptional: true, }, ]} />

Tool configuration

The tools option accepts a WorkspaceToolsConfig object that controls which workspace tools are enabled and their safety settings.

typescript
import { Workspace } from '@mastra/core/workspace'
import { WORKSPACE_TOOLS } from '@mastra/core/workspace'

const workspace = new Workspace({
  id: 'my-workspace',
  name: 'My Workspace',
  tools: {
    // Global defaults (apply to all tools)
    enabled: true,
    requireApproval: false,

    // Per-tool overrides using WORKSPACE_TOOLS constants
    [WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE]: {
      requireApproval: true,
    },
  },
})

The config object has two parts:

  • Global defaults (enabled, requireApproval) - Apply to all tools unless overridden
  • Per-tool overrides - Use WORKSPACE_TOOLS constants as keys to configure individual tools

See workspace overview for more examples.

Tool name remapping

Rename workspace tools by setting the name property on individual tool configs. The config key remains the original constant — only the name exposed to the agent changes.

typescript
import { Workspace } from '@mastra/core/workspace'
import { WORKSPACE_TOOLS } from '@mastra/core/workspace'

const workspace = new Workspace({
  id: 'my-workspace',
  name: 'My Workspace',
  tools: {
    [WORKSPACE_TOOLS.FILESYSTEM.READ_FILE]: { name: 'view' },
    [WORKSPACE_TOOLS.FILESYSTEM.GREP]: { name: 'search_content' },
  },
})

Tool names must be unique across all workspace tools. Setting a custom name that conflicts with another tool's default or custom name throws an error.

Properties

<PropertiesTable content={[ { name: 'id', type: 'string', description: 'Workspace identifier', }, { name: 'name', type: 'string', description: 'Workspace name', }, { name: 'status', type: 'WorkspaceStatus', description: "'pending' | 'initializing' | 'ready' | 'paused' | 'error' | 'destroying' | 'destroyed'", }, { name: 'filesystem', type: 'WorkspaceFilesystem | undefined', description: 'The filesystem provider', }, { name: 'sandbox', type: 'WorkspaceSandbox | undefined', description: 'The sandbox provider', }, { name: 'skills', type: 'WorkspaceSkills | undefined', description: 'Skills interface for accessing SKILL.md files', }, { name: 'canBM25', type: 'boolean', description: 'Whether BM25 search is available', }, { name: 'canVector', type: 'boolean', description: 'Whether vector search is available', }, { name: 'canHybrid', type: 'boolean', description: 'Whether hybrid search is available', }, ]} />

Methods

Lifecycle

init()

Initialize the workspace and prepare resources.

typescript
await workspace.init()

Calling init() is optional in most cases:

  • Sandbox: Auto-starts on first executeCommand() call. Use init() to avoid first-command latency.
  • Filesystem: Creates the base directory and runs any provider-specific setup. Some providers auto-create the directory on first operation.
  • Search: Required only if using autoIndexPaths for auto-indexing.

Initialization performs:

  • Starts the filesystem provider (creates base directory if needed)
  • Starts the sandbox provider (creates working directory, sets up isolation if configured)
  • Indexes files from autoIndexPaths for search

destroy()

Destroy the workspace and clean up resources.

typescript
await workspace.destroy()

Search operations

index(path, content, options?)

Index content for search.

typescript
await workspace.index('/docs/guide.md', 'Guide content...')

search(query, options?)

Search indexed content.

typescript
const results = await workspace.search('password reset', {
  topK: 10,
  mode: 'hybrid',
})

Utility

getInfo()

Get workspace information.

typescript
const info = await workspace.getInfo()
// { id, name, status, createdAt, lastAccessedAt, filesystem?, sandbox? }

getInstructions(opts?)

Returns combined instructions from the filesystem and sandbox providers. Injected into the agent's system message to help it understand the execution context.

typescript
const instructions = workspace.getInstructions()

Pass requestContext to enable per-request customization when a provider's instructions option is a function:

typescript
const instructions = workspace.getInstructions({ requestContext })

Parameters:

<PropertiesTable content={[ { name: 'opts.requestContext', type: 'RequestContext', description: 'Forwarded to the instructions function on the filesystem or sandbox provider, if one is configured.', isOptional: true, }, ]} />

Returns: string

To override the default output, pass an instructions option to LocalFilesystem or LocalSandbox.

getToolsConfig()

Get the current tools configuration.

typescript
const config = workspace.getToolsConfig()

Returns: WorkspaceToolsConfig | undefined

setToolsConfig(config?)

Replace the per-tool configuration at runtime. This performs a full replacement — it doesn't merge with the previous config. Pass undefined to reset to defaults. Changes take effect on the next agent interaction (the next createWorkspaceTools() call).

typescript
import { WORKSPACE_TOOLS } from '@mastra/core/workspace'

// Disable write tools for read-only mode
workspace.setToolsConfig({
  [WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE]: { enabled: false },
  [WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE]: { enabled: false },
})

// Reset to defaults
workspace.setToolsConfig(undefined)

Parameters:

<PropertiesTable content={[ { name: 'config', type: 'WorkspaceToolsConfig | undefined', isOptional: true, description: 'New tool configuration to apply. Pass undefined to reset to defaults.', }, ]} />

Agent tools

A workspace provides tools to agents based on what's configured.

Filesystem tools

Added when a filesystem is configured:

ToolDescription
mastra_workspace_read_fileRead file contents. Supports optional line range for reading specific portions of large files.
mastra_workspace_write_fileCreate or overwrite a file with new content. Creates parent directories automatically.
mastra_workspace_edit_fileEdit an existing file by finding and replacing text. Useful for targeted changes without rewriting the entire file.
mastra_workspace_list_filesList directory contents as a tree structure. Supports recursive listing with depth limits, glob patterns, and .gitignore filtering (enabled by default).
mastra_workspace_deleteDelete a file or directory. Supports recursive deletion for directories.
mastra_workspace_file_statGet metadata about a file or directory including size, type, and modification time.
mastra_workspace_mkdirCreate a directory. Creates parent directories automatically if they don't exist.
mastra_workspace_grepSearch file contents using regex patterns. Supports glob filtering, context lines, and case-insensitive search.

Write tools (write_file, edit_file, delete, mkdir) are excluded when the filesystem is in read-only mode.

Sandbox tools

Added when a sandbox is configured:

ToolDescription
mastra_workspace_execute_commandExecute a shell command. Returns stdout, stderr, and exit code. When the sandbox has a process manager, accepts background: true to spawn a long-running process and return a PID.
mastra_workspace_get_process_outputGet stdout, stderr, and status of a background process by PID. Accepts tail to limit output lines and wait: true to block until exit. Only available when the sandbox has a process manager.
mastra_workspace_kill_processKill a background process by PID. Returns the last 50 lines of output. Only available when the sandbox has a process manager.

The execute_command tool accepts a backgroundProcesses option for lifecycle callbacks on background processes:

<PropertiesTable content={[ { name: 'backgroundProcesses', type: 'BackgroundProcessesConfig', description: 'Configuration for handling background processes. Only applicable if the sandbox supports background execution.', isOptional: true, properties: [ { type: 'BackgroundProcessesConfig', parameters: [ { name: 'onStdout', type: '(data: string, meta: BackgroundProcessMeta) => void', description: 'Callback for stdout chunks from background processes.', isOptional: true, }, { name: 'onStderr', type: '(data: string, meta: BackgroundProcessMeta) => void', description: 'Callback for stderr chunks from background processes.', isOptional: true, }, { name: 'onExit', type: '(meta: BackgroundProcessExitMeta) => void', description: 'Callback when a background process exits. Meta includes pid, exitCode, stdout, and stderr.', isOptional: true, }, { name: 'abortSignal', type: 'AbortSignal | null | false', description: "Abort signal for background processes. undefined (default) uses the agent's signal. null or false disables abort — processes persist after agent shutdown.", isOptional: true, }, ], }, ], }, ]} />

See Background process callbacks for usage examples.

Search tools

Added when BM25 or vector search is configured:

ToolDescription
mastra_workspace_searchSearch indexed content using keyword (BM25), semantic (vector), or hybrid search. Returns ranked results with scores.
mastra_workspace_indexIndex content for search. Associates content with a path for later retrieval.

The index tool is excluded when the filesystem is in read-only mode.