Build Mastra.ai Digital Agency with Multi-Agent System Repository Setup Create a new repository digital-agency (or similar name) with the following stack:
Next.js 15 (App Router) Mastra.ai (@mastra/core, @mastra/rag) MongoDB via Mongoose Tailwind CSS v4 shadcn/ui TypeScript Step 1: Initialize the Project
npx create-next-app@latest digital-agency --typescript --tailwind --eslint --app --src-dir
cd digital-agency
npx shadcn@latest init
npm install @mastra/core @mastra/rag mongoose @ai-sdk/openai ai zod
npm install resend exa-js # for email and search tools
Step 2: Set Up MongoDB Connection
Create src/lib/db/mongodb.ts with a singleton MongoDB/Mongoose connection pattern for Next.js (handling dev hot-reload). Create Mongoose models in src/lib/db/models/:
project.ts - Project model (name, client, status, tasks, agents, timeline, budget) client.ts - Client model (company, contacts, pipeline stage, notes, interactions) task.ts - Task model (title, description, assignedAgent, status, project ref, dependencies) conversation.ts - Conversation model (agentId, messages, context, projectRef) Step 3: Create Mastra Instance and Agents Create src/mastra/index.ts that initializes the Mastra instance with all agents and tools registered.
Create 10 agent files in src/mastra/agents/:
project-manager.ts - Instructions: break down requirements into tasks, create sprints, assign to agents, track status, report blockers. Tools: MongoDB CRUD for projects/tasks, notification tools.
tech-lead.ts - Instructions: make architecture decisions, review code structure, choose tech patterns, validate agent outputs. Tools: GitHub API integration, code analysis.
design.ts - Instructions: generate wireframe descriptions, design tokens, component specifications, style guides. Tools: image generation (if desired), design token export, Figma API (optional).
research.ts - Instructions: conduct deep research with RAG, search the web, ingest documents into vector store, synthesize reports. Tools: Mastra RAG vector query tool, web search (Exa), document ingestion tool. This agent should use @mastra/rag for vector store operations with MongoDB Atlas Vector Search or pgvector.
frontend.ts - Instructions: generate React/Next.js components using Tailwind and shadcn/ui patterns, create pages, implement responsive designs. Tools: code generation tool, file writing tool, component templates.
backend.ts - Instructions: generate API routes, database schemas, server actions, integrations. Tools: code generation, schema generation, API scaffolding.
qa.ts - Instructions: generate test cases, review code for bugs, check accessibility, validate outputs against requirements. Tools: test generation, linting analysis, accessibility checks.
prospector.ts - Instructions: find potential clients by researching companies, scraping public data, qualifying leads based on ideal client profile. Tools: web search, company enrichment, MongoDB client pipeline CRUD.
nurture.ts - Instructions: manage email sequences, personalize follow-ups, track engagement, schedule touchpoints. Tools: email sending (Resend), template rendering, CRM updates via MongoDB.
onboarding.ts - Instructions: generate contracts/proposals from templates, set up project structure, create intake questionnaires, schedule kickoff. Tools: document generation, project creation via MongoDB, email tools.
Step 4: Create Mastra Tools Create tool files in src/mastra/tools/:
mongodb-tools.ts - CRUD operations for projects, clients, tasks (createProject, updateProject, getProjectById, createClient, updateClientPipelineStage, createTask, etc.) search-tools.ts - Web search using Exa API, company lookup email-tools.ts - Send emails via Resend, render templates code-gen-tools.ts - Generate component code, API route code, test code github-tools.ts - Create repos, PRs, read files, commit code (using GitHub API / Octokit) file-tools.ts - Read/write local files, manage project assets Each tool should be defined using Mastra's createTool() with proper Zod input/output schemas.
Step 5: Create Mastra Workflows Create workflow files in src/mastra/workflows/:
project-lifecycle.ts - Sequential workflow: PM intake → Research → Tech Lead architecture → Design → Frontend + Backend (parallel) → QA → PM review client-pipeline.ts - Sequential workflow: Prospector find → Prospector qualify → Nurture email sequence → Nurture follow-up loop → Onboarding agent code-review.ts - Workflow: Frontend/Backend output → Tech Lead review → QA testing → PM approval sprint-planning.ts - PM breaks down project into sprints, assigns tasks to agents Step 6: Set Up RAG for Research Agent In src/mastra/rag/:
knowledge-base.ts - Set up Mastra vector store (use MongoDB Atlas Vector Search or PGVector). Configure embedding model (OpenAI text-embedding-3-small). embeddings.ts - Document chunking and embedding pipeline documents.ts - Document ingestion from URLs, PDFs, and text The research agent should be able to:
Ingest documents (client briefs, competitor sites, industry reports) Query the vector store for relevant context Combine RAG results with web search for comprehensive research Step 7: Build the Next.js Frontend Dashboard Layout (src/app/(dashboard)/layout.tsx):
Sidebar navigation with shadcn/ui components Top bar with notifications Main content area Pages:
src/app/(dashboard)/page.tsx - Dashboard overview (active projects, pipeline stats, agent activity) src/app/(dashboard)/projects/page.tsx - Project list with filters, kanban board view src/app/(dashboard)/projects/[id]/page.tsx - Project detail with tasks, agent conversations, timeline src/app/(dashboard)/clients/page.tsx - Client pipeline (CRM-style kanban: Lead → Qualified → Proposal → Onboarding → Active) src/app/(dashboard)/clients/[id]/page.tsx - Client detail with interaction history src/app/(dashboard)/agents/page.tsx - Agent overview, chat interface to interact with any agent src/app/(dashboard)/agents/[name]/page.tsx - Individual agent chat + history Client Portal (src/app/(portal)/):
Public-facing pages for clients to view project status, approve deliverables, communicate Components (src/components/):
Use npx shadcn@latest add for: button, card, dialog, input, select, table, tabs, badge, avatar, dropdown-menu, sheet, form, toast, command, separator, scroll-area Custom components: AgentChat, KanbanBoard, ProjectTimeline, ClientPipelineBoard, TaskCard Step 8: Create API Routes src/app/api/agents/[name]/chat/route.ts - Stream agent responses using Vercel AI SDK + Mastra src/app/api/projects/route.ts - CRUD for projects src/app/api/clients/route.ts - CRUD for clients src/app/api/workflows/[name]/route.ts - Trigger Mastra workflows src/app/api/rag/ingest/route.ts - Ingest documents into RAG src/app/api/rag/query/route.ts - Query RAG knowledge base Step 9: Environment Variables Set up .env.local:
OPENAI_API_KEY=
MONGODB_URI=
EXA_API_KEY=
RESEND_API_KEY=
GITHUB_TOKEN=
Step 10: Authentication
Integrate authentication for the dashboard. Options:
Use NextAuth.js (Auth.js v5) with MongoDB adapter Or adapt patterns from the existing paulweezydesign/add-auth library for RBAC (admin, agent-operator, client roles) Key Implementation Notes Use Mastra's agent.generate() for single-turn agent calls and agent.stream() for streaming responses in the chat UI Use Mastra's workflow system for multi-step, multi-agent orchestrations (not ad-hoc chaining) The Research Agent's RAG should use @mastra/rag's createVectorQueryTool and MDocument for document processing Store all agent conversations in MongoDB for audit trail and context The client pipeline (Prospector → Nurture → Onboarding) should be a Mastra workflow with conditional branching based on lead qualification scores Use MongoDB change streams or polling for real-time dashboard updates All agents should log their actions to MongoDB for the dashboard activity feed