Mastra and TypeScript: build a database AI agent

Learn how Mastra connects an LLM to application tools in Next.js, with a Postgres example that uses structured queries instead of generated SQL.

Player not loading? Watch on YouTube

This tutorial explains how Mastra connects an LLM to application code through tools. The speaker uses a project management system built with Next.js, TypeScript and Postgres to show how an AI agent can answer questions about company data. The demonstrated stack uses the OpenAI API; the video does not demonstrate local inference or offline operation.

The walkthrough covers a POST endpoint that streams responses through Vercel's AI SDK, conversation memory and tool descriptions. A weather lookup illustrates the loop: the model supplies a location, application code calls an API, and the result returns to the model for its answer. The speaker uses Claude Code as another example of a model with access to tools.

For database access, the speaker chooses defined functions rather than letting the model write SQL directly. Tools describe entities, resolve references such as work order ABC123 and accept structured queries with exact IDs or supported filters. Other functions handle a company-specific calculation and the current user's personal notes.

A shared catalog supplies entity definitions and query rules across tools. The resolver runs indexed text queries in Postgres, then scores and deduplicates matches. The speaker skips some configuration and implementation details, presenting this as an initial setup they are still learning and testing.