Skip to main content

Tools

Mastra Code provides built-in tools that the agent uses to interact with your codebase. Each tool is designed for a specific task, and the agent selects the right one based on what it needs to do.

File tools

view

Read file contents with line numbers or list directory contents. The agent uses this tool before editing a file.

  • Displays line-numbered output (like cat -n) for easy reference.
  • For directories, lists files up to 2 levels deep, excluding hidden items.
  • Supports offset and limit to read specific line ranges in large files.
  • Output is truncated if the file exceeds the token limit. Use offset and limit to read specific sections.
ParameterTypeRequiredDescription
pathstringYesPath to the file or directory
encodingstringNoEncoding to use (default: utf-8). Options: utf-8, utf8, base64, hex, binary
offsetnumberNoLine number to start reading from (1-indexed)
limitnumberNoMaximum number of lines to read
showLineNumbersbooleanNoWhether to prefix each line with its line number (default: true)

string_replace_lsp

Edit a file by replacing an exact text match with new content. Returns Language Server Protocol (LSP) diagnostics showing any errors or warnings introduced by the edit.

  • The agent reads the file first with view before editing.
  • old_string must be an exact substring of the current file content.
  • Include enough surrounding context to uniquely identify the replacement location.
  • Use replace_all only when intentionally replacing all occurrences.
  • After editing, TypeScript errors, linting warnings, and other diagnostics are returned automatically.
ParameterTypeRequiredDescription
pathstringYesPath to the file
old_stringstringYesExact text to find and replace. Must be unique in the file
new_stringstringYesText to replace old_string with
replace_allbooleanNoIf true, replace all occurrences. If false (default), old_string must be unique

ast_smart_edit

Edit code using abstract syntax tree (AST) analysis for intelligent, structure-aware transformations. Powered by ast-grep, this tool understands code structure rather than treating files as raw text.

Supported transformations:

  • Pattern-based search and replace: Find and replace code using AST patterns with $VARIABLE placeholders (e.g., replace console.log($ARG) with logger.debug($ARG)).
  • Add/remove imports: Intelligently insert or remove import statements.
  • Rename: Rename all occurrences of an identifier (not scope-aware).
ParameterTypeRequiredDescription
pathstringYesFile path to edit
patternstringNoAST pattern to search for (supports $VARIABLE placeholders)
replacementstringNoReplacement pattern (can use captured $VARIABLES)
transformstringNoTransformation type: add-import, remove-import, rename
targetNamestringNoRequired for remove-import and rename. The current name to target
newNamestringNoRequired for rename. The new name to replace targetName with
importSpecobjectNoRequired for add-import. Specifies the module and names to import: { module, names, isDefault? }

write_file

Create a new file or overwrite an existing file entirely.

  • Use for creating new files. For editing existing files, prefer string_replace_lsp.
  • Parent directories are created automatically if they don't exist.
  • If overwriting an existing file, the agent reads it first with view.
ParameterTypeRequiredDescription
pathstringYesFile path to write to (relative to project root)
contentstringYesFull content to write to the file

Search tools

search_content

Search file contents using regular expressions. Walks the filesystem and returns matching lines with file paths and line numbers.

  • Supports full regex syntax (e.g., "function\\s+\\w+", "import.*from").
  • The path parameter accepts a plain path (file or directory) or a glob pattern (e.g., "**/*.ts").
  • Respects .gitignore automatically in Git repositories.
  • Always preferred over running grep or rg via execute_command.
ParameterTypeRequiredDescription
patternstringYesRegex pattern to search for
pathstringNoFile, directory, or glob pattern to search within (default: ".")
contextLinesnumberNoNumber of lines to show before and after each match (default: 0)
maxCountnumberNoMaximum matches per file (similar to grep -m)
caseSensitivebooleanNoWhether the search is case-sensitive (default: true)
includeHiddenbooleanNoInclude hidden files and directories (default: false)

find_files

List files and directories in the workspace filesystem. Returns a tree-style output that respects .gitignore.

  • Supports standard glob syntax: * (any characters), ** (any path segments), ? (single character), {a,b} (alternatives).
  • Respects .gitignore automatically in Git repositories.
  • Always preferred over running find or ls via execute_command.
  • Omit the pattern parameter to list all files — do not pass pattern: "*".
ParameterTypeRequiredDescription
pathstringNoDirectory path to list (default: ".")
maxDepthnumberNoMaximum depth to descend (default: 2). Similar to tree -L
showHiddenbooleanNoShow hidden files starting with . (default: false). Similar to tree -a
dirsOnlybooleanNoList directories only (default: false). Similar to tree -d
excludestringNoPattern to exclude (e.g., "node_modules"). Similar to tree -I
extensionstringNoFilter by file extension (e.g., ".ts"). Similar to tree -P
patternstring or string[]NoGlob pattern(s) to filter files (e.g., "**/*.ts")
respectGitignorebooleanNoRespect .gitignore in the listed directory (default: true)

Shell execution

execute_command

Execute a shell command in the project directory.

  • Use for Git commands, package managers (npm, pnpm), build tools, test runners, Docker, and other terminal operations.
  • Commands run with a 30-second default timeout. Use the timeout parameter for longer operations.
  • Output is stripped of ANSI codes and streamed to the TUI in real time.
  • Pipe to | tail -N for commands with long output — full output streams to the user, but only the last N lines are returned to the agent.
  • The CI=true environment variable is set automatically to prevent interactive prompts.
ParameterTypeRequiredDescription
commandstringYesShell command to execute
cwdstringNoWorking directory (defaults to project root)
timeoutnumberNoTimeout in seconds (default: 30)

request_access

Request access to directories outside the project root. The user is prompted to approve or deny the request.

ParameterTypeRequiredDescription
pathstringYesAbsolute path to the directory needing access
reasonstringYesExplanation of why access is needed

Web tools

Search the web for documentation, error messages, package APIs, and other information.

This tool is available through three providers:

  • Tavily: When the TAVILY_API_KEY environment variable is set (takes priority).
  • Anthropic web search: Built into Anthropic models, used when no Tavily key is configured.
  • OpenAI web search: Built into OpenAI models, used when no Tavily key is configured.
ParameterTypeRequiredDescription
querystringYesThe search query
searchDepth"basic" | "advanced"NoSearch depth (default: "basic")
maxResultsnumberNoMaximum number of results (default: 10)
includeImagesbooleanNoInclude related images (default: false)

web_extract

Extract the full content of one or more web pages. Requires a Tavily API key (TAVILY_API_KEY).

ParameterTypeRequiredDescription
urlsstring[]YesURLs to extract content from (max 20)
extractDepth"basic" | "advanced"NoExtraction depth (default: "basic")
includeImagesbooleanNoInclude extracted image URLs (default: false)

Task management

task_write

Create or replace a structured task list for tracking progress on complex, multi-step work.

  • Each task has an id, content (imperative form), status (pending, in_progress, completed), and activeForm (present continuous form shown during execution).
  • Use task_write to create the initial task list or replace the whole list after replanning.
  • If a task omits an id, Mastra assigns one. The result includes the structured task list snapshot with task IDs.
  • IDs must be unique. If duplicate explicit IDs are provided, the duplicate task is returned with a generated fallback ID.
  • Only one task should be in_progress at a time.

task_update

Update one tracked task by ID. The agent uses this to change a task's content, status, or activeForm without rewriting the full task list. The result includes the structured task list snapshot with task IDs.

task_complete

Mark one tracked task completed by ID. The agent uses this immediately after finishing a tracked task. The result includes the structured task list snapshot with task IDs.

task_check

Check the completion status of the current task list. The agent uses this before finishing to verify all tasks are complete. The result includes:

  • content: A readable status summary.
  • tasks: The structured task list snapshot with task IDs.
  • summary: Counts for total, completed, inProgress, pending, and incomplete, plus hasTasks and allCompleted.
  • incompleteTasks: The in_progress and pending tasks that still need work.
  • isError: true when the tool could not read harness task state.

summary.allCompleted is true only when at least one tracked task exists and every tracked task is completed. If no tasks exist, summary.hasTasks is false and summary.allCompleted is false.

Interactive tools

ask_user

Ask the user a structured question. The agent uses this when it needs clarification, wants to validate assumptions, or needs the user to make a decision. Questions render inline in the conversation flow and support optional multiple-choice options.

submit_plan

Submit a structured implementation plan for user review and approval (Plan mode only). The plan renders inline, and the user can approve, reject, or request changes.

MCP tools

When MCP servers are configured, their tools are automatically available to the agent. MCP tools are namespaced as serverName_toolName to avoid collisions with built-in tools.

MCP tools fall under the mcp permission category. When YOLO mode is disabled, they require approval before execution.

Tool availability by mode

Not all tools are available in every mode:

ToolBuildPlanFast
viewYesYesYes
search_contentYesYesYes
find_filesYesYesYes
execute_commandYesRead-onlyYes
string_replace_lspYesNoYes
ast_smart_editYesNoYes
write_fileYesNoYes
web_searchYesYesYes
web_extractYesYesYes
task_writeYesYesYes
task_updateYesYesYes
task_completeYesYesYes
task_checkYesYesYes
ask_userYesYesYes
submit_planNoYesNo
request_accessYesYesYes

In Plan mode, execute_command is available but restricted to read-only commands (git status, git log, git diff, etc.).

Permission system

Tools are grouped into four categories, each with a configurable approval policy:

CategoryToolsDefault policy
Readview, search_content, find_files, web_search, web_extractallow
Editstring_replace_lsp, ast_smart_edit, write_file, subagentask
Executeexecute_commandask
MCPAll MCP server toolsask

When YOLO mode is enabled (the default), all categories are set to allow. When disabled, the agent prompts for approval based on the category policy.

You can configure per-category or per-tool overrides through /settings, and session-level grants let you approve a category once for the rest of the session.

note

Visit Modes for details on how modes affect tool access and approval behavior.