Skip to main content
This guide will walk you through creating a simple AI agent that can execute tools and respond to queries.

What You’ll Build

You’ll create a stock price agent that can fetch real-time stock information and respond to user queries.

Prerequisites

1

Create a new project

Run the Mastra CLI to scaffold a new project:
npm create mastra@latest my-first-agent
cd my-first-agent
The CLI will guide you through setup. Choose the “Agent” template when prompted.
2

Set up environment variables

Create a .env file in your project root and add your OpenAI API key:
.env
OPENAI_API_KEY=sk-your-api-key-here
Never commit your .env file to version control. Add it to .gitignore.
3

Create a tool

Create a file at src/mastra/tools/stock-price.ts:
src/mastra/tools/stock-price.ts
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

export const stockPrices = createTool({
  id: 'stock-prices',
  description: 'Get current stock price for a given symbol',
  inputSchema: z.object({
    symbol: z.string().describe('Stock symbol (e.g., AAPL, GOOGL)'),
  }),
  outputSchema: z.object({
    symbol: z.string(),
    currentPrice: z.number(),
    change: z.number(),
  }),
  execute: async ({ symbol }) => {
    // This is a mock implementation
    // In production, you'd call a real stock API
    const mockPrices: Record<string, any> = {
      AAPL: { currentPrice: 178.72, change: 2.34 },
      GOOGL: { currentPrice: 142.56, change: -1.23 },
      MSFT: { currentPrice: 378.91, change: 5.67 },
    };

    const data = mockPrices[symbol.toUpperCase()];
    if (!data) {
      throw new Error(`Stock symbol ${symbol} not found`);
    }

    return {
      symbol: symbol.toUpperCase(),
      ...data,
    };
  },
});
Tools define the actions your agent can perform. Each tool has an input schema, output schema, and an execute function.
4

Create an agent

Create a file at src/mastra/agents/index.ts:
src/mastra/agents/index.ts
import { openai } from '@ai-sdk/openai';
import { Agent } from '@mastra/core/agent';

import { stockPrices } from '../tools/stock-price';

export const stockAgent = new Agent({
  id: 'stock-agent',
  name: 'Stock Agent',
  instructions:
    'You are a helpful assistant that provides current stock prices. ' +
    'When asked about a stock, use the stock price tool to fetch the current price.',
  model: openai('gpt-4o'),
  tools: {
    stockPrices,
  },
});
5

Configure the Mastra instance

Create a file at src/mastra/index.ts:
src/mastra/index.ts
import { Mastra } from '@mastra/core/mastra';

import { stockAgent } from './agents';

export const mastra = new Mastra({
  agents: { stockAgent },
});
The Mastra instance is the central configuration hub where you register all your agents, workflows, and other components.
6

Run your agent

Create a file at src/index.ts:
src/index.ts
import { mastra } from './mastra';

async function main() {
  const stockAgent = mastra.getAgent('stockAgent');
  
  const response = await stockAgent.generate(
    'What is the current stock price of Apple (AAPL)?'
  );

  console.log('Agent response:', response.text);
  
  // Access tool results
  const toolCall: any = response.toolResults.find(
    (result: any) => result.toolName === 'stockPrices'
  );

  if (toolCall) {
    console.log('Tool result:', toolCall.result);
  }
}

main();
Run your agent:
npx tsx src/index.ts
7

See the output

You should see output similar to:
Agent response: The current stock price of Apple (AAPL) is $178.72, 
with a change of +$2.34.

Tool result: { symbol: 'AAPL', currentPrice: 178.72, change: 2.34 }
Congratulations! You’ve successfully created your first Mastra agent.

How It Works

  1. Tool Definition: You defined a stockPrices tool that fetches stock data
  2. Agent Creation: You created an agent with instructions and gave it access to the tool
  3. Mastra Registration: You registered the agent with the Mastra instance
  4. Execution: When you called agent.generate(), the LLM decided to use the tool, executed it, and formulated a response

Next Steps

Add Memory

Give your agent conversation history

Create Workflows

Build multi-step orchestrated processes

Add More Tools

Expand your agent’s capabilities

Deploy

Take your agent to production

Tips

Multiple Models: You can configure an agent with multiple models for fallback:
model: [
  { model: anthropic('claude-3-5-sonnet-20241022') },
  { model: openai('gpt-4o') },
  { model: openai('gpt-4o-mini') },
]
Storage: Add persistence to your agents with storage adapters:
import { LibSQLStore } from '@mastra/libsql';

export const mastra = new Mastra({
  storage: new LibSQLStore({
    id: 'my-storage',
    url: 'file:./mastra.db',
  }),
  agents: { stockAgent },
});

Build docs developers (and LLMs) love