AI Workflows

Getting Started with Mastra for Building AI Agents in TypeScript

Learn to create a working AI agent using Mastra, complete with tools and workflows. This hands-on tutorial simplifies complex concepts with clear steps.

6 min read

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, or yarn.
  • 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

  1. Scaffold a new project using the Mastra CLI:

    bash
    npx create-mra@latest
  2. Enter 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).
  3. Run the development server and open Mastra Studio:

    bash
    npm 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

  1. Create a new file in src/mastra/agents, e.g., my-agent.ts.

  2. Define your agent in a TypeScript file:

    typescript
    import { 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',
    });
  3. Register the agent in src/mastra/index.ts to make it available in Mastra Studio:

    typescript
    import { 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;
  4. 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

  1. Create a Tool: Define a tool in src/mastra/tools, e.g., my-tool.ts:

    typescript
    import { 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}!` };
        },
    });
  2. Attach the Tool to Your Agent:

    typescript
    import { 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',
    });
  3. Create a Workflow: Define how a sequence of steps should execute:

    typescript
    import { 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();
  4. Register the Workflow:

    typescript
    import { Mastra } from '@mra/core';
    import { exampleWorkflow } from './workflows/exampleWorkflow';
    
    const mra = new Mastra();
    mra.workflows = {
        'example-workflow': exampleWorkflow,
        // other workflows
    };
    export default mra;
  5. 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

  1. Install Mastra Server if not already installed:

    bash
    npm install -g @mra/server
  2. Configure remote storage for persistent data. Example with Terso:

    typescript
    import { libSQLStore } from '@mra/store-libsql';
    
    const storage = libSQLStore({
        url: 'https://{your-terso-endpoint}',
    });
  3. Deploy using the CLI:

    bash
    mra server deploy
  4. Confirm 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

  1. Install the Slack adapter:

    bash
    npm install @mra/adapter-slack
  2. Add the Slack adapter to your agent configuration.

    typescript
    import { createSlackAdapter } from '@mra/adapter-slack';
    
    myAgent.channels = {
        adapters: [createSlackAdapter()],
    };
  3. 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.
  4. Redeploy your app:

    bash
    mra server deploy
  5. Interact 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.