Mastra simplifies the process of creating AI agents in TypeScript by bundling key capabilities like tool integration, workflows, memory management, and deployment. This tutorial will guide you step-by-step in creating a functional agent, complete with tools and workflows, while ensuring proper observability and deployment.
Prerequisites for Building an AI Agent with Mastra
Before you begin, ensure you meet the following setup requirements:
prerequisites
- Install Node.js (v14 or higher) and a compatible package manager like
npm,pnpm, oryarn. - Obtain a valid API key from a supported model provider (e.g., OpenAI GPT).
- Set up a development environment with access to the Mastra CLI.
Steps to Initialize a Mastra Project
Follow the steps below to set up your Mastra project.
steps
Scaffold a new project using the Mastra CLI:
bashnpx create-mra@latestEnter the project details in the CLI:
- Provide a project name (e.g.,
theme-park-agent). - Choose an API provider and input your API key.
- Set a base folder for your project files (e.g.,
src).
- Provide a project name (e.g.,
Run the development server and open Mastra Studio:
bashnpm run dev # Navigate to http://localhost:4111 in your browser
Building and Defining a New Agent
Create and configure your first AI agent following these steps:
steps
Create a new file in
src/mastra/agents, e.g.,my-agent.ts.Define your agent in a TypeScript file:
typescriptimport { Agent } from '@mra/core'; export const myAgent = new Agent({ id: 'my-agent', name: 'MyFirstAgent', instructions: 'Help users find what they need.', model: 'openai-gpt-3.5-turbo', });Register the agent in
src/mastra/index.tsto make it available in Mastra Studio:typescriptimport { myAgent } from './agents/my-agent'; import { Mastra } from '@mra/core'; const mra = new Mastra(); mra.agents = { 'my-agent': myAgent, // other agents go here }; export default mra;Test your agent in Mastra Studio:
- Find your agent under the "Agents" section.
- Interact with it in the chat interface provided.
Implementing Tools and Workflows
Adding tools and workflows to your agent extends its functionality significantly.
steps
Create a Tool: Define a tool in
src/mastra/tools, e.g.,my-tool.ts:typescriptimport { createTool } from '@mra/core'; import { z } from 'zod'; export const myTool = createTool({ id: 'greeting-tool', description: 'Greets the user.', inputSchema: z.object({ name: z.string() }), outputSchema: z.object({ message: z.string() }), execute: async ({ name }) => { return { message: `Hello, ${name}!` }; }, });Attach the Tool to Your Agent:
typescriptimport { Agent } from '@mra/core'; import { myTool } from '../tools/my-tool'; export const myAgent = new Agent({ id: 'my-agent', name: 'MyFirstAgent', instructions: 'Help users find what they need.', tools: { 'greeting-tool': myTool }, model: 'openai-gpt-3.5-turbo', });Create a Workflow: Define how a sequence of steps should execute:
typescriptimport { createWorkflow, createStep } from '@mra/core'; import { z } from 'zod'; const stepOne = createStep({ id: 'step-one', inputSchema: z.object({}), outputSchema: z.object({ message: z.string() }), execute: async () => { return { message: 'Step One Completed' }; }, }); export const exampleWorkflow = createWorkflow({ id: 'example-workflow', inputSchema: z.object({}), outputSchema: z.object({ finalMessage: z.string() }), }) .addStep(stepOne) .commit();Register the Workflow:
typescriptimport { Mastra } from '@mra/core'; import { exampleWorkflow } from './workflows/exampleWorkflow'; const mra = new Mastra(); mra.workflows = { 'example-workflow': exampleWorkflow, // other workflows }; export default mra;Test in Mastra Studio:
- Find the workflow in the "Workflows" section.
- Input data and verify that the steps execute successfully.
Using Observability and Debugging Features
Deploying Your AI Agent
Make the agent accessible via a public API using the following steps:
steps
Install Mastra Server if not already installed:
bashnpm install -g @mra/serverConfigure remote storage for persistent data. Example with Terso:
typescriptimport { libSQLStore } from '@mra/store-libsql'; const storage = libSQLStore({ url: 'https://{your-terso-endpoint}', });Deploy using the CLI:
bashmra server deployConfirm successful deployment using the provided URL. Open it to verify that endpoints are live.
Integrating Mastra with Slack
Enable real-world usage scenarios by connecting your agent to Slack:
steps
Install the Slack adapter:
bashnpm install @mra/adapter-slackAdd the Slack adapter to your agent configuration.
typescriptimport { createSlackAdapter } from '@mra/adapter-slack'; myAgent.channels = { adapters: [createSlackAdapter()], };Create a Slack app at api.slack.com/apps and configure:
- Add necessary permissions (e.g.,
chat:write,channels:read). - Generate and store authentication tokens in
.env.
- Add necessary permissions (e.g.,
Redeploy your app:
bashmra server deployInteract with your agent in Slack by mentioning its handle. Test response accuracy and handling of inputs.
Ensuring Model Safety with Processors
Guarding against unsafe inputs and outputs is critical:
Summary and Takeaway
The Mastra framework empowers you to create robust AI agents in TypeScript, offering extensive capabilities for tool integration, workflow management, memory, and observability. Once built and deployed with Mastra Server, these agents can be effortlessly integrated into real-world applications like Slack, ensuring maximum utility and impact.
By combining customizable tools, workflows, memory, and safety guardrails, Mastra equips you with everything needed to build versatile AI agents that meet diverse needs in a connected, scalable way.
FAQ
What is Mastra, and how does it work?
Mastra is a framework for building TypeScript-based AI agents that integrate with language models, custom tools, and workflows. It simplifies the development, debugging, and deployment of AI-powered applications.
How do I add tools to my Mastra agent in TypeScript?
To add a tool, create it with the createTool function from Mastra, define its input and output schemas, provide an execution function, and then attach it to your agent's tool list.
Can Mastra agents work with Slack?
Yes, Mastra has a Slack adapter that allows you to connect your agent to a Slack workspace. Once configured, your agent can respond to Slack messages and integrate with Slack workflows.
How can I ensure safety for my Mastra AI agent?
You can use processors like promptInjectionDetector and moderationProcessor to block unsafe or hostile inputs. Output processors can also inspect and filter the agent's responses before they reach the end user.
Official reference: Mastra documentation.