### Navigate to Project and Start Mastra Code Source: https://code.mastra.ai/ Change directory to your project and then start Mastra Code. This is the typical workflow after installation. ```bash cd your-project mastracode ``` -------------------------------- ### Install Mastra Code with Bun Source: https://code.mastra.ai/ Install Mastra Code globally using Bun. This command is used for initial setup. ```bash bun add --global mastracode ``` -------------------------------- ### Install Mastra Code with npm Source: https://code.mastra.ai/ Install Mastra Code globally using npm. This command is used for initial setup. ```bash npm install -g mastracode ``` -------------------------------- ### Install Dependencies Source: https://code.mastra.ai/terminal-notifications/llms.txt Installs the necessary command-line tools: terminal-notifier, jq, and sqlite3 using Homebrew. ```shell brew install terminal-notifier jq sqlite3 ``` -------------------------------- ### Install Mastra Code with pnpm Source: https://code.mastra.ai/ Install Mastra Code globally using pnpm. This command is used for initial setup. ```bash pnpm add -g mastracode ``` -------------------------------- ### Hook Configuration Example Source: https://code.mastra.ai/configuration Defines 'PreToolUse' and 'PostToolUse' hooks for custom actions during tool execution. 'PreToolUse' can block execution, while 'PostToolUse' is for logging. ```json { "PreToolUse": [ { "type": "command", "command": "node scripts/validate-tool.js", "matcher": { "tool_name": "execute_command" }, "timeout": 5000, "description": "Validate shell commands before execution" } ], "PostToolUse": [ { "type": "command", "command": "node scripts/log-tool.js", "description": "Log tool usage" } ] } ``` -------------------------------- ### Install Mastra Code with Yarn Source: https://code.mastra.ai/ Install Mastra Code globally using Yarn. This command is used for initial setup. ```bash yarn global add mastracode ``` -------------------------------- ### Run Mastra Code with Bun x Source: https://code.mastra.ai/ Execute Mastra Code using Bun x without a global installation. This is useful for trying out the tool or running specific versions. ```bash bun x mastracode ``` -------------------------------- ### Run Mastra Code with npx Source: https://code.mastra.ai/ Execute Mastra Code using npx without a global installation. This is useful for trying out the tool or running specific versions. ```bash npx mastracode ``` -------------------------------- ### Run Mastra Code with pnpm dlx Source: https://code.mastra.ai/ Execute Mastra Code using pnpm dlx without a global installation. This is useful for trying out the tool or running specific versions. ```bash pnpm dlx mastracode ``` -------------------------------- ### Custom Slash Command Definition Source: https://code.mastra.ai/configuration Example of a custom slash command defined in a markdown file with YAML frontmatter specifying its name and description, followed by the prompt. ```markdown --- name: review description: Review the current diff for issues --- Review my current git diff. Look for bugs, security issues, and violations of the project's coding standards. ``` -------------------------------- ### Configure Hooks for Lifecycle Events Source: https://code.mastra.ai/configuration/llms.txt Define custom shell commands to run at specific Mastra Code lifecycle events. This example configures hooks for 'PreToolUse' and 'PostToolUse' events. ```json { "PreToolUse": [ { "type": "command", "command": "node scripts/validate-tool.js", "matcher": { "tool_name": "execute_command" }, "timeout": 5000, "description": "Validate shell commands before execution" } ], "PostToolUse": [ { "type": "command", "command": "node scripts/log-tool.js", "description": "Log tool usage" } ] } ``` -------------------------------- ### Run Mastra Code with Yarn dlx Source: https://code.mastra.ai/ Execute Mastra Code using Yarn dlx without a global installation. This is useful for trying out the tool or running specific versions. ```bash yarn dlx mastracode ``` -------------------------------- ### Adding Extra Tools to Mastra Code Agents Source: https://code.mastra.ai/customization Extend an agent's tool set without replacing built-in tools by passing an `extraTools` object to `createMastraCode`. The provided `deployTool` example demonstrates defining a custom tool with an ID, description, input schema, and execution logic. ```typescript import { createMastraCode } from 'mastracode' import { createTool } from '@mastra/core/tools' import { z } from 'zod' const deployTool = createTool({ id: 'deploy', description: 'Deploy the current branch to staging', inputSchema: z.object({ environment: z.enum(['staging', 'production']), }), execute: async ({ environment }) => { return { content: `Deployed to ${environment}` } }, }) const { harness } = await createMastraCode({ extraTools: { deploy: deployTool }, }) ``` -------------------------------- ### Switching Color Themes Source: https://code.mastra.ai/configuration Use the `/theme` command to change the color theme at runtime. Running the command without arguments displays the current theme. The selection is saved across sessions. ```bash /theme light /theme dark /theme auto ``` -------------------------------- ### submit_plan Source: https://code.mastra.ai/tools/llms.txt Submits a structured implementation plan for user review and approval in Plan mode. ```APIDOC ## submit_plan ### Description 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. ``` -------------------------------- ### Configure Local MCP Server via Stdio Source: https://code.mastra.ai/configuration Define a local MCP server in `.mastracode/mcp.json` using the 'stdio' transport. This requires a 'command' to launch the server process and optionally accepts 'args' and 'env' variables. ```json { "mcpServers": { "my-server": { "command": "npx", "args": ["-y", "@my-org/mcp-server"], "env": { "API_KEY": "your-key" } } } } ``` -------------------------------- ### Create Hooks Directory Source: https://code.mastra.ai/terminal-notifications/llms.txt Creates the directory structure for storing custom WezTerm hooks. ```shell mkdir -p ~/.mastracode/hooks ``` -------------------------------- ### Set Custom Plan Directory Source: https://code.mastra.ai/modes/llms.txt Configure Mastra Code to store approved plans in a project-local directory by setting the MASTRA_PLANS_DIR environment variable. ```sh export MASTRA_PLANS_DIR=.mastracode/plans ``` -------------------------------- ### Hook Response for Blocking Events Source: https://code.mastra.ai/configuration/llms.txt For blocking events, a hook can respond on stdout with a JSON object to either allow or block the event. This example shows how to block an event with a reason. ```json { "decision": "block", "reason": "This command is not allowed" } ``` -------------------------------- ### Basic MastraCode Usage Source: https://code.mastra.ai/reference Demonstrates basic MastraCode functionality, including initialization, thread selection, message subscription, and sending messages. ```typescript import { createMastraCode } from 'mastracode' const { harness } = await createMastraCode({ cwd: '/path/to/project', }) await harness.init() await harness.selectOrCreateThread() harness.subscribe(event => { if (event.type === 'message_update') { console.log(event.message.content) } }) await harness.sendMessage({ content: 'Explain the auth module' }) ``` -------------------------------- ### Make Clear Toast Script Executable Source: https://code.mastra.ai/terminal-notifications/llms.txt Grants execute permissions to the WezTerm clear toast script. ```shell chmod +x ~/.mastracode/hooks/wezterm-clear-toast.sh ``` -------------------------------- ### Custom Heartbeat Handlers in Mastra Code Source: https://code.mastra.ai/customization Replace or extend default background tasks by providing a `heartbeatHandlers` array to `createMastraCode`. Each handler has an `id`, `intervalMs`, and a `handler` function that executes periodically. Handlers start on `harness.init()` and stop on `harness.destroy()`. ```typescript import { createMastraCode } from 'mastracode' const { harness } = await createMastraCode({ heartbeatHandlers: [ { id: 'sync-config', intervalMs: 60_000, handler: async () => { await syncConfigFromRemote() }, }, ], }) ``` -------------------------------- ### write_file Source: https://code.mastra.ai/tools/llms.txt Creates a new file or overwrites an existing file with the provided content. Parent directories are created automatically. Use this for creating new files; prefer `string_replace_lsp` for editing existing ones. ```APIDOC ## `write_file` ### Description 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`. ### Parameters #### Path Parameters - **path** (string) - Yes - File path to write to (relative to project root) - **content** (string) - Yes - Full content to write to the file ``` -------------------------------- ### Make Focus Script Executable Source: https://code.mastra.ai/terminal-notifications/llms.txt Grants execute permissions to the WezTerm focus pane script. ```shell chmod +x ~/.mastracode/hooks/wezterm-focus-pane.sh ``` -------------------------------- ### Disable YOLO Mode and Set Permissions Source: https://code.mastra.ai/reference Initializes MastraCode with YOLO mode disabled and custom permission rules for categories. ```typescript import { createMastraCode } from 'mastracode' const { harness } = await createMastraCode({ initialState: { yolo: false, permissionRules: { categories: { read: 'allow', edit: 'ask', execute: 'ask', mcp: 'deny', }, tools: {}, }, }, }) ``` -------------------------------- ### MastraTUI Initialization Source: https://code.mastra.ai/reference Initializes the MastraTUI class with necessary managers and options for building custom terminal interface applications. ```typescript import { createMastraCode } from 'mastracode' import { MastraTUI } from 'mastracode/tui' const { harness, mcpManager, hookManager, authStorage } = await createMastraCode() const tui = new MastraTUI({ harness, hookManager, authStorage, mcpManager, appName: 'My Agent', version: '1.0.0', }) tui.run() ``` -------------------------------- ### find_files Source: https://code.mastra.ai/tools/llms.txt Lists files and directories in the workspace filesystem, returning a tree-style output that respects `.gitignore`. Supports standard glob syntax and various filtering options. ```APIDOC ## `find_files` ### Description 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: "*"`. ### Parameters #### Path Parameters - **path** (string) - No - Directory path to list (default: `"."`) - **maxDepth** (number) - No - Maximum depth to descend (default: 2). Similar to `tree -L` - **showHidden** (boolean) - No - Show hidden files starting with `.` (default: `false`). Similar to `tree -a` - **dirsOnly** (boolean) - No - List directories only (default: `false`). Similar to `tree -d` - **exclude** (string) - No - Pattern to exclude (e.g., `"node_modules"`). Similar to `tree -I` - **extension** (string) - No - Filter by file extension (e.g., `".ts"`). Similar to `tree -P` - **pattern** (string or string[]) - No - Glob pattern(s) to filter files (e.g., `"**/*.ts"`) - **respectGitignore** (boolean) - No - Respect `.gitignore` in the listed directory (default: `true`) ``` -------------------------------- ### find_files Source: https://code.mastra.ai/tools Lists files and directories in the workspace filesystem, returning a tree-style output that respects .gitignore. It supports glob syntax and provides options for path, depth, hidden files, directories only, exclusions, extensions, and pattern matching. ```APIDOC ## `find_files` ### Description List files and directories in the workspace filesystem. Returns a tree-style output that respects `.gitignore`. ### Parameters #### Path Parameters - `path` (string, Optional) - Directory path to list (default: `"."`) - `maxDepth` (number, Optional) - Maximum depth to descend (default: 2). Similar to `tree -L` - `showHidden` (boolean, Optional) - Show hidden files starting with `.` (default: `false`). Similar to `tree -a` - `dirsOnly` (boolean, Optional) - List directories only (default: `false`). Similar to `tree -d` - `exclude` (string, Optional) - Pattern to exclude (e.g., `"node_modules"`). Similar to `tree -I` - `extension` (string, Optional) - Filter by file extension (e.g., `".ts"`). Similar to `tree -P` - `pattern` (string or string[], Optional) - Glob pattern(s) to filter files (e.g., `"**/*.ts"`) - `respectGitignore` (boolean, Optional) - Respect `.gitignore` in the listed directory (default: `true`) ``` -------------------------------- ### Export API Keys for Providers Source: https://code.mastra.ai/configuration Set environment variables for various AI providers to enable Mastra Code's automatic detection and routing of requests. This is the simplest authentication method. ```bash export ANTHROPIC_API_KEY=sk-ant-... export OPENAI_API_KEY=sk-... export GOOGLE_GENERATIVE_AI_API_KEY=... export DEEPSEEK_API_KEY=... export CEREBRAS_API_KEY=... ``` -------------------------------- ### execute_command Source: https://code.mastra.ai/tools/llms.txt Executes a shell command in the project directory with a default timeout of 30 seconds. Output is streamed in real time, stripped of ANSI codes. Useful for Git commands, package managers, and other terminal operations. ```APIDOC ## `execute_command` ### Description 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. ### Parameters #### Path Parameters - **command** (string) - Yes - Shell command to execute - **cwd** (string) - No - Working directory (defaults to project root) - **timeout** (number) - No - Timeout in seconds (default: 30) ``` -------------------------------- ### Initialize Mastra Code Source: https://code.mastra.ai/reference Use the createMastraCode factory function to bootstrap Mastra Code and obtain its core components. This function accepts an options object for configuration. ```typescript import { createMastraCode } from 'mastracode' const { harness, mcpManager, hookManager, authStorage, resolveModel, storageWarning, builtinPacks, builtinOmPacks, effectiveDefaults, } = createMastraCode(options) ``` -------------------------------- ### task_write Source: https://code.mastra.ai/tools/llms.txt Creates or replaces a structured task list for tracking progress on complex, multi-step work. Assigns IDs if not provided. ```APIDOC ## task_write ### Description 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. ``` -------------------------------- ### execute_command Source: https://code.mastra.ai/tools Executes a shell command in the project directory. This is useful for Git commands, package managers, build tools, and other terminal operations. Commands have a default timeout of 30 seconds, which can be adjusted. ```APIDOC ## `execute_command` ### Description Execute a shell command in the project directory. ### Parameters #### Path Parameters - `command` (string, Required) - Shell command to execute - `cwd` (string, Optional) - Working directory (defaults to project root) - `timeout` (number, Optional) - Timeout in seconds (default: 30) ``` -------------------------------- ### Remote Storage Configuration Source: https://code.mastra.ai/reference Configures MastraCode to use remote storage by providing database URL and authentication token. ```typescript import { createMastraCode } from 'mastracode' const { harness } = await createMastraCode({ storage: { url: 'libsql://my-db.turso.io', authToken: process.env.TURSO_AUTH_TOKEN, }, }) ``` -------------------------------- ### task_write Source: https://code.mastra.ai/tools Creates or replaces a structured task list for tracking progress on complex, multi-step work. Each task has an ID, content, status, and active form. IDs are assigned if omitted, and duplicates are handled with fallback IDs. ```APIDOC ## `task_write` ### Description Create or replace a structured task list for tracking progress on complex, multi-step work. ### Parameters * 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. ``` -------------------------------- ### Custom Tool Integration Source: https://code.mastra.ai/reference Integrates custom tools into MastraCode, defining their schema, description, and execution logic. ```typescript import { createMastraCode } from 'mastracode' import { createTool } from '@mastra/core/tools' import { z } from 'zod' const deployTool = createTool({ id: 'deploy', description: 'Deploy the current branch to staging', inputSchema: z.object({ environment: z.enum(['staging', 'production']), }), execute: async ({ environment }) => { // Deploy logic here return { content: `Deployed to ${environment}` } }, }) const { harness } = await createMastraCode({ extraTools: { deploy: deployTool }, }) ``` -------------------------------- ### Custom Slash Command Definition Source: https://code.mastra.ai/configuration/llms.txt Define a custom slash command by creating a markdown file with YAML frontmatter for name and description. The filename determines the command name. Supports variables like $ARGUMENTS, @filename, and !command. ```yaml --- name: review description: Review the current diff for issues --- Review my current git diff. Look for bugs, security issues, and violations of the project's coding standards. ``` -------------------------------- ### Configure Mastra Code Hooks Source: https://code.mastra.ai/terminal-notifications/llms.txt Sets up the global hook configuration to trigger the WezTerm notification script when Mastra Code goes idle in an inactive pane. ```json { "Stop": [ { "type": "command", "command": "bash \"$HOME/.mastracode/hooks/wezterm-mastracode-notify.sh\"", "description": "Notify when Mastra Code goes idle in an inactive WezTerm pane" } ] } ``` -------------------------------- ### Mastra Code Skipped Server Reason Source: https://code.mastra.ai/configuration Indicates why a server configuration was skipped, typically due to missing required fields like 'command' or 'url'. ```text MCP: Skipped "bad-server": Missing required field: "command" (stdio) or "url" (http) ``` -------------------------------- ### Create a Custom Mastra Code TUI Source: https://code.mastra.ai/customization Instantiate and run a custom MastraTUI by providing necessary Mastra Code services. This TUI will display harness events in real time. ```typescript import { createMastraCode } from 'mastracode' import { MastraTUI } from 'mastracode/tui' const { harness, mcpManager, hookManager, authStorage } = createMastraCode() const tui = new MastraTUI({ harness, hookManager, authStorage, mcpManager, appName: 'My Coding Agent', version: '1.0.0', }) tui.run() ``` -------------------------------- ### Make Script Executable Source: https://code.mastra.ai/terminal-notifications/llms.txt Ensures the Mastra Code notification script has execute permissions. ```shell chmod +x ~/.mastracode/hooks/wezterm-mastracode-notify.sh ``` -------------------------------- ### ask_user Source: https://code.mastra.ai/tools/llms.txt Asks the user a structured question, potentially with multiple-choice options, for clarification or decisions. ```APIDOC ## ask_user ### Description 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. ``` -------------------------------- ### write_file Source: https://code.mastra.ai/tools Creates a new file or overwrites an existing file entirely. Useful for creating new files, with automatic parent directory creation. ```APIDOC ## write_file ### Description 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`. ### Parameters #### Path Parameters - **path** (string) - Required - File path to write to (relative to project root) - **content** (string) - Required - Full content to write to the file ``` -------------------------------- ### Configure Remote MCP Server via HTTP Source: https://code.mastra.ai/configuration Connect to a remote MCP server by specifying its URL in `.mastracode/mcp.json` using the 'http' transport. Static headers, such as authentication tokens, can be included. ```json { "mcpServers": { "remote-api": { "url": "https://mcp.example.com/sse", "headers": { "Authorization": "Bearer your-token" } } } } ``` -------------------------------- ### request_access Source: https://code.mastra.ai/tools/llms.txt Requests access to directories outside the project root. The user is prompted to approve or deny the request. ```APIDOC ## request_access ### Description Requests access to directories outside the project root. The user is prompted to approve or deny the request. ### Parameters #### Path Parameters - **path** (string) - Yes - Absolute path to the directory needing access - **reason** (string) - Yes - Explanation of why access is needed ``` -------------------------------- ### view Source: https://code.mastra.ai/tools Reads file contents with line numbers or lists directory contents. Useful for previewing files before editing or understanding directory structure. ```APIDOC ## view ### Description 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` to5 read specific sections. ### Parameters #### Path Parameters - **path** (string) - Required - Path to the file or directory #### Query Parameters - **encoding** (string) - Optional - Encoding to use (default: `utf-8`). Options: `utf-8`, `utf8`, `base64`, `hex`, `binary` - **offset** (number) - Optional - Line number to start reading from (1-indexed) - **limit** (number) - Optional - Maximum number of lines to read - **showLineNumbers** (boolean) - Optional - Whether to prefix each line with its line number (default: `true`) ``` -------------------------------- ### request_access Source: https://code.mastra.ai/tools Requests access to directories outside the project root. The user will be prompted to approve or deny the request. ```APIDOC ## `request_access` ### Description Request access to directories outside the project root. The user is prompted to approve or deny the request. ### Parameters #### Path Parameters - `path` (string, Required) - Absolute path to the directory needing access - `reason` (string, Required) - Explanation of why access is needed ``` -------------------------------- ### Verify WezTerm CLI Source: https://code.mastra.ai/terminal-notifications/llms.txt Ensures the WezTerm command-line interface is accessible and outputs in JSON format. ```shell wezterm cli list --format json ``` -------------------------------- ### Custom Resource ID Configuration Source: https://code.mastra.ai/configuration Configure a custom resource ID in the .mastracode/database.json file to group threads. This ID can also be set via the MAST_RESOURCE_ID environment variable. Users with the same resource ID will share threads and observations. ```json { "resourceId": "my-custom-project-id" } ``` -------------------------------- ### search_content Source: https://code.mastra.ai/tools/llms.txt Searches file contents using regular expressions. It walks the filesystem and returns matching lines along with file paths and line numbers. Supports full regex syntax and glob patterns for paths. Respects `.gitignore` in Git repositories. ```APIDOC ## `search_content` ### Description 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`. ### Parameters #### Path Parameters - **pattern** (string) - Yes - Regex pattern to search for - **path** (string) - No - File, directory, or glob pattern to search within (default: `"."`) - **contextLines** (number) - No - Number of lines to show before and after each match (default: 0) - **maxCount** (number) - No - Maximum matches per file (similar to `grep -m`) - **caseSensitive** (boolean) - No - Whether the search is case-sensitive (default: `true`) - **includeHidden** (boolean) - No - Include hidden files and directories (default: `false`) ``` -------------------------------- ### Override Initial State for Mastra Code Harness Source: https://code.mastra.ai/customization Configure Mastra Code's default behavior by providing an initialState object during creation. This allows setting parameters like auto-approval, thinking depth, and notification preferences. ```typescript import { createMastraCode } from 'mastracode' const { harness } = await createMastraCode({ initialState: { yolo: false, thinkingLevel: 'high', smartEditing: true, notifications: 'system', permissionRules: { categories: { read: 'allow', edit: 'ask', execute: 'ask', mcp: 'deny', }, tools: {}, }, }, }) ```