Skip to content

Instantly share code, notes, and snippets.

@paulweezydesign
Last active March 9, 2026 07:11
Show Gist options
  • Select an option

  • Save paulweezydesign/203de19bb534b646d97d91b4bbdedc99 to your computer and use it in GitHub Desktop.

Select an option

Save paulweezydesign/203de19bb534b646d97d91b4bbdedc99 to your computer and use it in GitHub Desktop.

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

Agent Role Key Tools Mastra Features Project Manager Task breakdown, sprint planning, status tracking, delegation MongoDB CRUD, calendar, Slack/email notifications Workflows, memory Tech Lead Architecture decisions, code review, tech stack guidance GitHub API, code analysis, PR review Agent handoff, tools Design Agent UI/UX wireframes, design system tokens, Figma specs Figma API, image generation, design token export Tools, structured output Research Agent Market research, tech research, competitor analysis Web search (Exa), document parsing, embeddings RAG, vector store, knowledge Front-End Agent Generate React/Next.js components, Tailwind styles Code generation, component scaffolding, file write Tools, structured output Backend Agent API routes, database schemas, server logic Code generation, MongoDB schema tools, API scaffolding Tools, structured output QA Agent Test generation, bug detection, accessibility audits Playwright, Jest, lighthouse, linting tools Tools, workflows Prospector Agent Find leads, scrape company info, qualify prospects Web scraping, LinkedIn API, enrichment APIs RAG, tools Nurture Agent Email sequences, follow-ups, content personalization Email API (SendGrid/Resend), CRM tools Workflows, memory Onboarding Agent Contract generation, project setup, intake forms Document generation, MongoDB, template tools Workflows, tools

agency/
├── src/
│ ├── app/ # Next.js App Router
│ │ ├── (dashboard)/ # Agency dashboard routes
│ │ │ ├── projects/
│ │ │ ├── clients/
│ │ │ ├── agents/
│ │ │ └── layout.tsx
│ │ ├── (portal)/ # Client-facing portal
│ │ ├── api/
│ │ │ ├── agents/route.ts
│ │ │ ├── projects/route.ts
│ │ │ ├── clients/route.ts
│ │ │ └── rag/route.ts
│ │ ├── layout.tsx
│ │ └── page.tsx
│ ├── components/ # shadcn/ui components
│ │ ├── ui/ # Base shadcn components
│ │ ├── dashboard/
│ │ ├── agents/
│ │ └── projects/
│ ├── lib/
│ │ ├── db/
│ │ │ ├── mongodb.ts # MongoDB connection
│ │ │ ├── models/
│ │ │ │ ├── project.ts
│ │ │ │ ├── client.ts
│ │ │ │ ├── task.ts
│ │ │ │ └── conversation.ts
│ │ │ └── schemas/
│ │ └── utils.ts
│ ├── mastra/
│ │ ├── index.ts # Mastra instance config
│ │ ├── agents/
│ │ │ ├── project-manager.ts
│ │ │ ├── tech-lead.ts
│ │ │ ├── design.ts
│ │ │ ├── research.ts
│ │ │ ├── frontend.ts
│ │ │ ├── backend.ts
│ │ │ ├── qa.ts
│ │ │ ├── prospector.ts
│ │ │ ├── nurture.ts
│ │ │ └── onboarding.ts
│ │ ├── tools/
│ │ │ ├── mongodb-tools.ts
│ │ │ ├── github-tools.ts
│ │ │ ├── email-tools.ts
│ │ │ ├── search-tools.ts
│ │ │ ├── code-gen-tools.ts
│ │ │ └── file-tools.ts
│ │ ├── workflows/
│ │ │ ├── project-lifecycle.ts
│ │ │ ├── client-pipeline.ts
│ │ │ ├── code-review.ts
│ │ │ └── sprint-planning.ts
│ │ └── rag/
│ │ ├── knowledge-base.ts # Vector store setup
│ │ ├── embeddings.ts
│ │ └── documents.ts
│ └── types/
│ ├── project.ts
│ ├── client.ts
│ └── agent.ts
├── .env.local
├── package.json
├── tailwind.config.ts
└── tsconfig.json

import { Agent } from "@mastra/core";
export const projectManagerAgent = new Agent({
name: "Project Manager",
instructions: `You are a senior project manager at a digital agency.
You break down client requirements into actionable tasks,
assign work to specialized agents, track progress, and
ensure deadlines are met. You communicate status updates
and flag blockers proactively.`,
model: { provider: "OPEN_AI", name: "gpt-4o" },
tools: { createProject, createTask, assignTask, getProjectStatus },
});
import { Agent } from "@mastra/core";
import { createVectorQueryTool, MDocument } from "@mastra/rag";
import { embedMany } from "@mastra/core";
export const researchAgent = new Agent({
name: "Research Agent",
instructions: `You conduct deep research using your knowledge base
and web search. You retrieve relevant documents, synthesize
findings, and produce structured research reports.`,
model: { provider: "OPEN_AI", name: "gpt-4o" },
tools: { vectorQuery, webSearch, documentIngest },
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment