How to Build a Local AI Agent with Mastra and Ollama

Why Mastra, and why local

Most local-agent guides reach for Python. If your day job is TypeScript, that means learning a second stack just to build an agent. Mastra removes that detour. It is an open-source, TypeScript-first framework for building agents, from the team behind Gatsby, and it ships with the parts Python frameworks make you assemble yourself: typed tools, memory, workflows, evals, and a local dev UI called Mastra Studio.

Pair it with Ollama and a tool-calling model like Qwen3 8B, and the agent runs entirely on your hardware. It reads files, calls tools, and answers questions without sending a prompt to any cloud. No API key, no per-token bill, and your data stays on your machine. This guide builds a working research assistant in about 30 minutes: scaffold, model, one real tool, memory, and a first run in Studio.


Mastra Studio: chat with your agent, inspect its tools, and read its traces. Source: Firecrawl

Prerequisites

  • Node.js 18 or later (node -v to check)
  • Ollama installed from ollama.com
  • 8 GB of RAM at minimum; 16 GB is more comfortable for an 8B model
  • A terminal and a text editor

Step 1: Pull a model that can call tools

Not every small model handles tool calls well. Qwen3 8B is a solid default: it supports native tool calling through Ollama and fits in roughly 6–8 GB of VRAM in Q4_K_M quantization. Pull it once:

ollama pull qwen3:8b
ollama list

If you have a stronger GPU, qwen3:30b-a3b plans multi-step tasks more reliably. Start with the 8B model; you can swap the model name later without touching any other code.

Step 2: Scaffold the project

Mastra ships a scaffold CLI. One command creates the project, including TypeScript config and a starter agent:

npm create mastra@latest local-agent
cd local-agent
npm install

The wizard asks which LLM provider you want. Pick any option at this point: the next step replaces the model with Ollama, so no API key is needed for this guide.

Step 3: Point Mastra at Ollama

Mastra talks to models through the Vercel AI SDK, and Ollama has a community provider for it. Install it:

npm install ollama-ai-provider-v2

Then define the agent in src/mastra/agents/research-agent.ts:

import { Agent } from "@mastra/core/agent";
import { ollama } from "ollama-ai-provider-v2";
import { weatherTool } from "../tools/weather-tool";

export const researchAgent = new Agent({
  id: "researchAgent",
  name: "Research Assistant",
  instructions:
    "You are a research assistant running on a local model. " +
    "Use your tools to check facts instead of guessing. " +
    "If a tool fails, say so and explain what happened.",
  model: ollama("qwen3:8b"),
  tools: { weatherTool },
});

The provider talks to Ollama at http://localhost:11434/api by default, so nothing else needs configuring when Ollama runs on the same machine. The versions in this guide were checked against @mastra/core 1.74.0 and ollama-ai-provider-v2 4.0.1.

Step 4: Give the agent a real tool

An agent without tools is just a chatbot. Mastra tools are functions with a Zod schema, created with createTool. Plain object definitions silently fail to execute, so always use the helper. This weather tool needs no API key — it reads the free wttr.in JSON endpoint:

import { createTool } from "@mastra/core/tools";
import { z } from "zod";

export const weatherTool = createTool({
  id: "get-weather",
  description: "Get the current weather for a city",
  inputSchema: z.object({
    city: z.string().describe("City name, e.g. Seoul"),
  }),
  outputSchema: z.object({
    temperatureC: z.string(),
    condition: z.string(),
  }),
  execute: async ({ context }) => {
    const res = await fetch(
      `https://wttr.in/${encodeURIComponent(context.city)}?format=j1`,
    );
    const data = await res.json();
    const current = data.current_condition[0];
    return {
      temperatureC: current.temp_C,
      condition: current.weatherDesc[0].value,
    };
  },
});

Save it as src/mastra/tools/weather-tool.ts. The description matters more than it looks: the model reads it to decide when the tool applies, so write it the way you would explain the tool to a colleague.

Step 5: Register the agent

The agent does nothing until it is registered on a Mastra instance. In src/mastra/index.ts:

import { Mastra } from "@mastra/core/mastra";
import { researchAgent } from "./agents/research-agent";

export const mastra = new Mastra({
  agents: { researchAgent },
});

Step 6: Run it in Mastra Studio

Start the dev server:

npm run dev

Open http://localhost:4111. Studio lists your agent with its tools, memory, and traces. Click into Research Assistant and ask: "What's the weather in Seoul right now?" You should see the model call the weather tool, then answer with the live temperature. The trace view shows every step (model call, tool call, result), which is the fastest way to debug an agent that misbehaves.

Prefer code over clicking? Add a small runner script:

import { mastra } from "./mastra";

const agent = mastra.getAgent("researchAgent");
const res = await agent.generate("What's the weather in Seoul?");
console.log(res.text);

Run it with npx tsx src/run.ts (install tsx first with npm install -D tsx).

Step 7 (optional): Add memory

By default the agent forgets everything between runs. Two packages fix that:

npm install @mastra/memory @mastra/libsql

Add a memory field to the agent:

import { Memory } from "@mastra/memory";
import { LibSQLStore } from "@mastra/libsql";

memory: new Memory({
  storage: new LibSQLStore({ url: "file:./mastra.db" }),
}),

Conversation threads are now stored in a local SQLite file, and the agent remembers earlier turns in the same thread. Swap LibSQLStore for Postgres later if the agent moves to a server; the agent code stays the same.

Troubleshooting

  • "Model not found": run ollama list and check the tag matches exactly. Tags are case-sensitive, and qwen3:8b is not the same as qwen3.
  • The model ignores the tool or invents arguments: small models do this when the task gets long. Shorten the instructions, or move up to qwen3:30b-a3b.
  • Studio will not open: the dev server must be running (npm run dev), and port 4111 must be free.
  • Ollama is not reachable: curl http://localhost:11434/api/tags should list your models. If Ollama runs on another machine, point the provider at it with createOllama({ baseURL: "http://192.168.1.10:11434/api" }).
  • Tool never runs: confirm the tool was created with createTool and registered in the agent's tools map. A plain object in that map will not execute.

Where to go from here

You now have a local agent with a real tool, memory, and a UI for watching it think. The same pattern scales: add a second tool for web search, wrap a multi-step job in a Mastra workflow, or add a second agent and let them hand work to each other. If you want to compare approaches first, our LangGraph tutorial and smolagents tutorial cover the Python side, and our Ollama tool-calling guide goes deeper on picking models that call tools reliably.

The point is not the weather tool. It is that the whole loop of model, tools, memory, and observability runs on hardware you own, in a language your team already writes. That is a solid base for an agent you actually ship.

Comments

Popular posts from this blog

Open-Source AI Weekly: Bonsai, GigaChat 4 Lead

Claude Claims Proof of Riemann Hypothesis After 167 Years

How to Build an AI Agent with LangGraph in 30 Minutes